Skip to main content

fats/
fetch.rs

1//! FETCH: the router. `auto` = the ladder (`Plan::ladder`): plain first, then the keyed tiers cheapest first, Oxylabs
2//! and Decodo without JavaScript, then the renders (Bright Data, Oxylabs, Decodo) racing one hedge apart (`hedge:`,
3//! 5 s) while the content check fails. Oxylabs without JS is a page rung: after plain's captcha with both keys, first
4//! with the free fetch off, on every page with its key alone, never after a shell (`Plan::ladder`; Decodo's the same);
5//! it also serves a search, a PDF's bytes and `provider:oxy`.
6//! The first good body wins and the other call is cancelled, its bill unverified (`billed`). Government hosts skip
7//! Bright Data (it refuses them). A PDF (`pdf_run`) goes plain → Oxylabs without JS → Bright Data for its bytes, never
8//! JavaScript; a `/pdf/` path (`Plan::hint`) only gets the file timeout and raw bytes, page rules otherwise; a zip
9//! document (docx, xlsx) never goes to a provider, and a text document plain served (`clean::Lists::text`) stops it.
10//! `next` is the whole decision table, pure, so it is tested without a network.
11//! Every page fetch walks the same ladder; `js:true` walks the table's render order (`JS_QUOTE`).
12
13use crate::cache::{Cache, HopRow, Meta, guarded, raw_name};
14use crate::clean::{self, Doc};
15use crate::html::{Node, Tree, py_space};
16use crate::lang::{At, Cmd, Flag, bang, bin, fix, priced, restamp, uniq};
17use crate::outline::{fmt_age, is_thin, lost_page};
18use crate::provider::{
19    Ask, Fail, Hit, Limit, OWN_REASON, PROVIDERS, REFUSED, Raw, SEARCH_TIMEOUT, Tier, search_country, sent, spend,
20};
21use crate::settings::limit;
22use std::collections::BTreeMap;
23use std::future::Future;
24use std::pin::Pin;
25use std::sync::LazyLock;
26use std::time::{Duration, Instant};
27
28/// Default `cost:` cap per command, USD.
29pub const COST_CAP: f64 = 0.05;
30/// The URL tables (`src/data/sites.json`).
31#[derive(serde::Deserialize)]
32#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
33pub struct Sites {
34    /// Government labels (`gov()`), a TLD convention, no site: Bright Data refuses those hosts, so `auto` sends
35    /// them straight to Oxylabs. The first two are TLDs; the rest are public suffixes under a country code.
36    pub gov: Vec<&'static str>,
37    /// URL suffixes that name a document, and its kind (what `clean::kind_of` finds in the answer; `html` = a
38    /// page). A text document's suffix only keeps a `/pdf/` path from being a PDF hint (`Plan::hint`): the answer
39    /// says what it is; `secret` = a key or credential (`cli::secret`: never read from disk). THE list: a token
40    /// with one of them is a path too (`lang::is_file`, `doc_kind`).
41    doc_ext: Vec<(&'static str, &'static str)>,
42    /// Path segments that may name a PDF without the suffix (`arxiv.org/pdf/2405.15793`, `…/doi/pdf/10.1145/…`);
43    /// a hint only, since `…/docs/pdf/merge.html` is a page (`Plan::hint`).
44    pdf_path: Vec<&'static str>,
45    /// Second-level labels under a two-letter country code that are public suffixes themselves (`co.uk`,
46    /// `gov.uk`, `com.au`). A built-in approximation of the Public Suffix List's ICANN section.
47    sld: Vec<&'static str>,
48    /// Hosts where every subdomain is someone else's site (`alice.github.io`): each is its own route. The few the
49    /// Public Suffix List's private section has that agents meet most (a registry row like `sld`, no site).
50    shared: Vec<&'static str>,
51    /// The fence's blocks (`provider::private_ip`, CIDR): this host (0/8), private, CGNAT, loopback, link-local
52    /// (169.254.169.254 = cloud metadata), IETF, documentation, benchmarking, multicast, reserved and broadcast;
53    /// IPv6 ULA, link-local, site-local, multicast, documentation (`::` and `::1` carry IPv4 0.0.0.0 and 0.0.0.1).
54    pub fence: Vec<&'static str>,
55}
56
57pub static SITES: LazyLock<Sites> = LazyLock::new(|| crate::settings::table("sites"));
58/// Oxylabs without JS in a PDF run: the whole file comes back as escaped JSON (a 4.9 MB PDF took 9.5 s,
59/// a 352 kB one 2.1 s; measured 2026-10-12).
60pub const PDF_OXY: Duration = Duration::from_secs(30);
61/// How long the first provider runs alone before the second starts beside it (`hedge:0` = both at once).
62/// Both are billed when both run, so the hedge only buys time on slow answers.
63pub const HEDGE: Duration = Duration::from_secs(5);
64/// The hedge on a web search (Oxylabs, then Bright Data): a hedge starts at the first provider's p50, and a
65/// search's p50 is about 2 s (Web API `/v1/search` measured 0.9-1.5 s), so Bright Data still has time to answer
66/// inside a short `wait:` when Oxylabs is slow.
67pub const SEARCH_HEDGE: Duration = Duration::from_millis(2500);
68
69/// The hedges in effect, as `dry:true` and `fats config` show them: `hedge search 2.5 s · fetch 5 s · default`,
70/// or the one `hedge:` mod value that sets both.
71pub fn hedges(flag: Option<&str>) -> String {
72    let default =
73        || format!("hedge search {} s · fetch {} s · default", SEARCH_HEDGE.as_secs_f64(), HEDGE.as_secs_f64());
74    flag.map_or_else(default, |v| format!("hedge {v} s · flag hedge:{v}"))
75}
76#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
77pub enum Mode {
78    #[default]
79    Auto,
80    Only(Tier),
81}
82
83#[derive(Default, Clone)]
84pub struct Plan {
85    pub mode: Mode,
86    /// `js:true`: skip plain (and Oxylabs without JS, where it runs); Bright Data, then Oxylabs rendering JavaScript.
87    pub js: bool,
88    pub cap: f64,
89    pub gov: bool,
90    /// The URL names a document by its suffix: `pdf`, `zip`, a text document (`Sites::doc_ext`).
91    pub doc: Option<&'static str>,
92    /// The path may name a file (`Sites::pdf_path`, no `.htm(l)` suffix): Oxylabs gets `PDF_OXY` and Bright Data sends
93    /// raw bytes, but a page that passes the content check is served as a page; only an answer that says PDF makes it
94    /// a PDF run.
95    pub hint: bool,
96    /// Tiers with a key configured.
97    pub keys: Vec<Tier>,
98    /// `timeout:` for the JavaScript tiers (bd, oxyjs); plain and oxy without JS keep their own.
99    pub timeout: Option<Duration>,
100    pub hedge: Duration,
101    /// A web search, not a page: no gate tiers (an answer has no content check), search prices and timeout.
102    pub search: bool,
103    /// A search's prefetch (`fetch:N`): speculative work is free, so plain only, whatever `provider:` the search
104    /// named; a page that needs a paid tier is fetched when opened (`fats u<N>` runs the whole ladder).
105    pub prefetch: bool,
106    /// The render that sent the page's stored copy: `js:true` never asks it again (`rendered`).
107    pub avoid: Option<Tier>,
108    /// A search's `wait:` (every command answers by it): no tier starts after it, a call still running is cut
109    /// (`provider::late`).
110    /// None = a detached fetch, which runs to its end.
111    pub wait: Option<Duration>,
112    /// The command's `wait:` (`cli::wait_of`), a page's too: a rate limit's pause ends inside it or is no retry (`pause`).
113    pub patience: Duration,
114    /// The folder of the copy stored before, the Markdown guard's yardstick (`md_weak`); None = none.
115    pub prior: Option<std::path::PathBuf>,
116    /// A batch's `cost:` pool (`pooled`) and this run's id in it; None = the run has `cap` to itself.
117    pub pool: Option<(std::path::PathBuf, usize)>,
118}
119
120impl Plan {
121    pub fn new(url: &str, mode: Mode, js: bool, cap: f64, timeout: Option<Duration>) -> Plan {
122        let gov = gov(url);
123        let path = url.split(['?', '#']).next().unwrap_or("").to_ascii_lowercase();
124        let kind = doc_kind(&path);
125        let (page, doc) = (kind == Some("html"), kind.filter(|k| *k != "html"));
126        let hint = doc.is_none() && !page && SITES.pdf_path.iter().any(|p| path.contains(p));
127        Plan { mode, js, cap, gov, doc, hint, keys: keyed(), timeout, hedge: HEDGE, ..Plan::default() }
128    }
129
130    /// A web search: the search rows (Oxylabs, then Bright Data beside it after the hedge); `provider:` = that one
131    /// only.
132    pub fn search(mode: Mode, cap: f64, timeout: Option<Duration>) -> Plan {
133        let mut p = Plan { search: true, hedge: SEARCH_HEDGE, ..Plan::new("", mode, false, cap, timeout) };
134        p.keys.retain(|t| t.can("search"));
135        p
136    }
137
138    /// THE plan of a command's mods (`provider:`, `js:`, `cost:`, `timeout:`, `hedge:`), a page's for `url`, else a
139    /// search's: what a fetch runs, `dry:true` routes and an arrow quotes (`worst`).
140    pub fn of(cmd: &Cmd, url: Option<&str>) -> Plan {
141        let mode = cmd.get("provider").and_then(Tier::parse).map_or(Mode::Auto, Mode::Only);
142        let cap = cmd.get("cost").and_then(|v| v.parse::<f64>().ok()).unwrap_or(COST_CAP).max(0.0);
143        let timeout = cmd.get("timeout").and_then(|v| v.parse().ok()).map(Duration::from_secs);
144        let mut p =
145            url.map_or_else(|| Plan::search(mode, cap, timeout), |u| Plan::new(u, mode, cmd.flag("js"), cap, timeout));
146        p.hedge = cmd.get("hedge").and_then(|v| v.parse().ok()).map_or(p.hedge, Duration::from_secs);
147        p.patience = crate::cli::wait_of(cmd);
148        p
149    }
150
151    /// THE document rule: this run fetches a PDF when its URL names one (`.pdf`) or an answer said
152    /// so (magic, or the content type on a failure). A PDF is never rendered: no oxyjs, and `js:true` does not
153    /// skip plain.
154    pub fn pdf_run(&self, done: &[Hop]) -> bool {
155        !self.search && (self.doc == Some("pdf") || done.iter().any(|h| h.kind == "pdf"))
156    }
157
158    /// THE ladder rule: the tiers in the order they may run, given the finished hops (`pdf_run`; none = before any
159    /// answer). `auto` = the capability rows (`provider::Spec::can`) that do this job, cheapest first (table order on a
160    /// tie: bd before oxyjs); a paid no-JS tier leaves a page's ladder when another provider's render has a key (it
161    /// served 3 of 20 pages plain failed on), so with one provider's key every rung of that provider runs, unless
162    /// plain's wall needs a render (`Check::render_first`: after a JS challenge or shell oxy no-JS served 0/33, after a
163    /// 403 or captcha 11/26). With both keys it stays, before the renders, after plain's captcha only
164    /// (`Check::no_js_first`: Reddit 25/34 in ~4.4 s for $0.0010, a render $0.0015), or first when plain is off (no
165    /// free verdict to wait for: a page both renders cut at 60 s served without JS in 6.4 s); one try, no site log.
166    /// Never after a shell, the page needs JS (0/3 served, each +$0.0010, +4–10 s), nor after a paid no-JS tier OUR cut
167    /// stopped: the next is the same slow page without JS (oxy 10 s, then decodo 15 s).
168    /// `provider:oxy` = every tier of that key, without JS first (oxy, oxyjs).
169    pub fn ladder(&self, done: &[Hop]) -> Vec<Tier> {
170        let pdf = self.pdf_run(done);
171        let job = match () {
172            _ if self.search => "search",
173            _ if pdf => "pdf",
174            _ if self.js => "js",
175            _ => "page",
176        };
177        let mut rows: Vec<Tier> = Tier::ALL.into_iter().filter(|t| t.can(job) && (!self.gov || t.can("gov"))).collect();
178        rows.sort_by(|a, b| a.spec().price.total_cmp(&b.spec().price));
179        let render = |t: Tier| rows.iter().any(|&r| r.can("js") && r.owner() != t.owner() && self.keys.contains(&r));
180        let page = job == "page" && !self.hint;
181        let plain = |codes: &[&str]| done.iter().any(|h| h.tier == Tier::Plain && codes.contains(&h.code.as_str()));
182        // a paid no-JS tier yields to another provider's render but after plain's `no_js_first` wall, or when plain
183        // is off (no free verdict to wait for: the cheap fast rung leads), to its own render after a `render_first` one
184        let first = !self.keys.contains(&Tier::Plain) || plain(&CHECK.no_js_first);
185        let cut = done.iter().any(|h| !h.tier.can("js") && h.tier.spec().price > 0.0 && h.code == "provider_timeout");
186        let yields = |t: Tier| cut || if render(t) { !first } else { plain(&CHECK.render_first) };
187        let drops = |t: &Tier| page && !t.can("js") && t.spec().price > 0.0 && yields(*t);
188        let all = match self.mode {
189            _ if self.prefetch => vec![Tier::Plain],
190            Mode::Only(o) => Tier::ALL.into_iter().filter(|&t| t == o || t.owner() == o).collect(),
191            Mode::Auto => rows.iter().copied().filter(|t| !drops(t)).collect(),
192        };
193        // behind a `one_render` gate, plain's or a render's, ONE render: it answers every render alike (bd and oxyjs
194        // both billed for one shell); a render the provider refused or erred on rendered nothing, so the next may try
195        let gate = done.iter().any(|h| CHECK.one_render.contains(&h.code.as_str()));
196        let refused = |t: &Tier| done.iter().any(|h| h.tier == *t && REFUSED.contains(&h.code.as_str()));
197        let one = all.iter().copied().find(|t| t.can("js") && self.keys.contains(t) && !refused(t)).filter(|_| gate);
198        let keep = |t: Tier| t.can(job) && self.avoid != Some(t);
199        all.into_iter().filter(|&t| keep(t) && one.is_none_or(|o| o == t || !t.can("js"))).collect()
200    }
201
202    /// A tier's timeout, given the finished hops. `timeout:` stretches only the slow tiers: the 10 s plain and oxy
203    /// no-JS gates exist to hand a hard page on quickly, so they keep their time, but never past what the agent's wall
204    /// left (`agent_left`; plain runs first, so its cap is `timeout:` itself: `timeout:2` on a 12 s page ran 12 s;
205    /// `provider:oxy timeout:1` ran its no-JS call 20 s, 21 s in all). In a PDF run, or on a `/pdf/` path (`hint`),
206    /// Oxylabs gets `PDF_OXY`. The one-key retry of a timed-out call (`retries`) gets twice OUR time, never twice the
207    /// agent's `timeout:` (a cap it asked for), and never past the one-key wall (`wall_left`). A named no-JS tier
208    /// (`provider:oxy`, the cut tier's offer) gates nothing to hand on quickly: twice its time, as a cut one's retry.
209    fn timeout_of(&self, t: Tier, done: &[Hop]) -> Duration {
210        let cut = done.iter().find(|h| h.tier == t && h.code == "provider_timeout");
211        let k = 1 + u32::from(one_call(self) || cut.is_some() || (self.mode == Mode::Only(t) && !t.can("js")));
212        let wall = cut.and_then(|h| wall_left(done, h)).unwrap_or(Duration::MAX);
213        let left = self.agent_left(done);
214        let ours = |d: Duration| left.unwrap_or((d * k).min(wall));
215        let paid_file = t.spec().price > 0.0 && t.can("pdf") && (self.pdf_run(done) || self.hint);
216        match () {
217            _ if self.search => ours(SEARCH_TIMEOUT),
218            _ if t.can("js") => ours(t.spec().timeout),
219            _ if paid_file => ours(PDF_OXY),
220            _ => (t.spec().timeout * k).min(wall).min(left.unwrap_or(Duration::MAX)),
221        }
222    }
223
224    /// Plain and oxy without JS (the no-JS rows, `!t.can("js")`) are gates of a fetch: what follows waits for their
225    /// verdict, and only some failures are worth it. In a paid ask (`js:true`, `provider:`) every tier is a gate: ONE
226    /// provider runs, the next only on its failure (`hedge:off`; a hedge bills both). Bd leads a render: it won 14/14
227    /// of the races it answered, and fails fast (js_shell ~2.3 s) where oxyjs fails slow (68-71 s timeouts over
228    /// 192 runs).
229    fn gate(&self, t: Tier) -> bool {
230        !self.search && (!t.can("js") || !self.hedged() || self.timeout.is_some())
231    }
232
233    /// With `timeout:8` and both keys, bd was cut at 8 s and oxyjs, hedged at 5 s, cut 8 s later: 13.3 s. So
234    /// the agent's `timeout:` is ONE wall for the provider calls of a page run, one at a time (`gate`): what the
235    /// finished ones left of it (plain, free, capped by it but not counted, and the host check before it); the run
236    /// stops with < 1 s left (`next`). None = no `timeout:`.
237    fn agent_left(&self, done: &[Hop]) -> Option<Duration> {
238        let used = done.iter().filter(|h| !self.search && h.tier != Tier::Plain).map(|h| h.ms).sum();
239        self.timeout.map(|t| t.saturating_sub(Duration::from_millis(used)))
240    }
241
242    /// The router picks and races the tiers (`auto`), or the one tier asked for is free (`provider:plain`: no
243    /// `hedge:off` to print); false = the agent asked for a paid tier (`js:true`, `provider:bd`): `hedge:off`.
244    pub fn hedged(&self) -> bool {
245        self.search || self.mode == Mode::Only(Tier::Plain) || (self.mode == Mode::Auto && !self.js)
246    }
247
248    /// THE search patience: `wait:`, or longer, the leading keyed search provider's own
249    /// answer time (`Spec::search_s`: bd answers in 4.5-25 s, bd-only got 0/3 searches at 5 s).
250    /// Longer than `wait:` = the search runs detached (`cli::searching`): the caller still answers at `wait:`.
251    pub fn search_wait(&self, wait: Duration) -> Duration {
252        let lead = self.ladder(&[]).into_iter().find(|t| self.keys.contains(t)).map_or(0, |t| t.spec().search_s);
253        wait.max(Duration::from_secs(lead))
254    }
255}
256
257// ---------------------------------------------------------------- site
258
259/// The site of a URL (`canonical`: a same-site landing): its registrable domain (`m.youtube.com` → `youtube.com`,
260/// `www.bbc.co.uk` → `bbc.co.uk`), on a shared host the subdomain (`alice.github.io`); an IP address or a
261/// one-label host stays whole.
262pub fn site(url: &str) -> String {
263    let host = clean::host_of(url);
264    let host = host.trim_end_matches('.');
265    if host.parse::<std::net::IpAddr>().is_ok() {
266        return host.into();
267    }
268    let host = host.strip_prefix("www.").unwrap_or(host);
269    let labels: Vec<&str> = host.split('.').collect();
270    let shared = SITES.shared.iter().find(|s| host.ends_with(&format!(".{s}")));
271    let keep = match labels.as_slice() {
272        _ if let Some(s) = shared => s.split('.').count() + 1,
273        // `co.uk` alone keeps its 2 labels either way
274        [.., sld, tld] if tld.len() == 2 && SITES.sld.contains(sld) => 3,
275        _ => 2,
276    };
277    labels[labels.len().saturating_sub(keep)..].join(".")
278}
279
280/// What `js:true` takes: a render's time (oxyjs renders measured 14-32 s, 2026-10); its price = `worst`.
281/// `≈`, never `~`: an arrow pasted into zsh unquoted stops at `~25s` (a user's home dir it looks up).
282pub const JS_QUOTE: &str = "≈25s";
283
284/// One call's outcome: the hop row in meta.json, plus the body and doc for the store.
285#[derive(Default)]
286pub struct Hop {
287    pub tier: Tier,
288    pub ok: bool,
289    pub code: String,
290    pub status: u16,
291    pub ms: u64,
292    pub cost: f64,
293    /// `cache::HopRow::upto`: a call we cut, its price unverified (`billed`).
294    pub upto: f64,
295    /// The request shape (`cache::HopRow`): the country sent (`run`, `run_search`), the timeout (`drive`).
296    pub country: String,
297    pub timeout_s: u64,
298    /// `clean::kind_of`: `html`, `pdf`, `zip`, `text`, `json`, `xml`; empty = no body.
299    pub kind: &'static str,
300    pub body: Vec<u8>,
301    /// The answer's status (`HTTP 200`) and its headers as `Raw::headers` keeps them (lower case), no credential
302    /// (`provider::header_lines`): `Meta::headers`.
303    pub headers: String,
304    /// Where the answer came from: the base of its links and pictures.
305    pub final_url: String,
306    /// Where a bd ask landed by its same-site canonical link (`canonical`): `Meta::landed`, never a base.
307    pub landed: Option<String>,
308    /// The page whose meta refresh plain followed to this one (`provider::refresh`): `Meta::refreshed_from`.
309    pub refreshed_from: Option<String>,
310    /// Visible characters (picks the best copy when every hop fails).
311    pub vis: usize,
312    pub doc: Option<Doc>,
313    /// A failed HTML answer's parse, kept so the best failed copy is cleaned without a second parse.
314    pub tree: Option<Tree>,
315    pub charset: &'static str,
316    /// A search's answer, best first.
317    pub hits: Vec<Hit>,
318    /// The provider's own error answer, masked: kept as `error.txt`, never printed.
319    pub err: Vec<u8>,
320    /// `Fail::why`: the token the `!` row adds to the code.
321    pub why: String,
322    /// The provider's request budget from this answer (`provider::Limit`): stored as two numbers in the hop.
323    pub limit: Option<Limit>,
324    /// When the call landed (`billed`): a thin answer waits the hedge window from here (`next`).
325    pub end: Option<Instant>,
326    /// The HTML answer's `<html lang>` primary subtag, lower case (`it`); empty = none declared (`langs`).
327    pub lang: String,
328    /// Ms plain waited for its turn before it started (`provider::pace`), not in `ms`.
329    pub waited: u64,
330}
331
332impl Hop {
333    /// A call the provider failed: its code, status, reason token, budget and (masked) answer.
334    fn failed(tier: Tier, f: Fail) -> Hop {
335        Hop { tier, code: f.code.into(), status: f.status, err: f.body, why: f.why, limit: f.limit, ..Hop::default() }
336    }
337
338    pub fn row(&self) -> HopRow {
339        HopRow {
340            provider: self.tier.spec().name.into(),
341            code: self.code.clone(),
342            cost: self.cost,
343            ms: self.ms,
344            why: self.why.clone(),
345            upto: self.upto,
346            country: self.country.clone(),
347            timeout_s: self.timeout_s,
348            limit: self.limit.map(|l| l.limit),
349            remaining: self.limit.map(|l| l.remaining),
350            waited_ms: Some(self.waited).filter(|&w| w > 0),
351        }
352    }
353}
354
355#[derive(Debug, PartialEq)]
356pub enum Step {
357    Start(Tier),
358    Wait(Duration),
359    Stop,
360}
361
362/// THE final answers: about the target itself, so every tier gets the same one. The first ends the job and cancels
363/// every call in flight: a missing page, an oversized body, a private address (a provider must not be sent one
364/// either), a host that does not exist or got no verdict on its address (`host_hop`). Not final: a provider's
365/// refusal or unlock failure, such as Bright Data's 502 / `x-brd-error-code` (`reject_block`, `resolve_failed_*`:
366/// "each attempt uses a different peer, and the same request has been observed to succeed on a later attempt",
367/// docs.brightdata.com products/web-unlocker/error-codes) or its policy refusals (another provider may serve that
368/// host).
369const FINAL: &[&str] =
370    &["not_found", "too_big", "private_address", "no_host", "dns_timeout", "dns_failed", "tls_failed"];
371
372/// A failed gate hop (plain, or oxy without JS) worth the next tier: not a zip document, not a final answer
373/// (`FINAL`).
374fn escalates(h: &Hop) -> bool {
375    !h.ok && h.kind != "zip" && !FINAL.contains(&h.code.as_str())
376}
377
378/// Codes that are about the key, not the page: a refused key or zone, or its request budget spent. The same key on
379/// another tier gets the same answer.
380pub const KEY_CODES: &[&str] = &["bad_key", "bad_zone", "rate_limited"];
381
382/// A provider refused `t`'s key, said its budget is spent, or refused this URL (`provider_refused`, bd's policy:
383/// a government host the labels missed) on an earlier hop: no tier sends that key again in this run (oxy → oxyjs
384/// share one), and it is no provider left to cover a failure (`retries`).
385fn refused(done: &[Hop], t: Tier) -> bool {
386    let no = |c: &str| KEY_CODES.contains(&c) || c == "provider_refused";
387    done.iter().any(|h| no(&h.code) && h.tier.owner() == t.owner())
388}
389
390/// THE decision table: what happens next, given finished hops and running calls (tier, time running).
391pub fn next(p: &Plan, done: &[Hop], running: &[(Tier, Duration)]) -> Step {
392    // a call still running `grace_s` past its own timeout is given up on
393    let over = running.iter().any(|&(t, e)| e > p.timeout_of(t, done) + Duration::from_secs(limit("grace_s")));
394    // a thin first answer waits for the other provider's call already running, for the hedge
395    // window after it landed (not the call's whole timeout; reddit served bd's 1.2k tok, oxyjs held 9.3k)
396    let other = |h: &Hop| running.iter().any(|r| r.0.owner() != h.tier.owner());
397    let window = |h: &Hop| p.hedge.saturating_sub(h.end.map_or(Duration::ZERO, |e| e.elapsed()));
398    let thin_wait = done.iter().filter(|h| h.ok).map(window).min().filter(|w| !w.is_zero());
399    if let Some(w) = thin_wait.filter(|_| !over && done.iter().all(|h| !h.ok || thin(h) && other(h))) {
400        return Step::Wait(left(p, running, done).min(w));
401    }
402    let spent_wall = p.agent_left(done).is_some_and(|l| l < Duration::from_secs(1));
403    if over || spent_wall || done.iter().any(|h| h.ok || FINAL.contains(&h.code.as_str())) {
404        return Step::Stop;
405    }
406    let started = |t: Tier| done.iter().any(|h| h.tier == t) || running.iter().any(|r| r.0 == t);
407    // a gate's verdict worth the next tier (a zip document goes on whatever plain said)
408    let settled = |q: Tier| p.doc == Some("zip") || !done.iter().any(|h| h.tier == q && escalates(h));
409    let spent = held(done, running);
410    let can = |t: Tier| p.keys.contains(&t) && !refused(done, t) && spent + t.spec().price <= p.cap + 1e-9;
411    // `prev` = the last tier that ran: one that could not start (no key, no budget) does not gate the next
412    let mut prev: Option<Tier> = None;
413    for t in p.ladder(done) {
414        if started(t) {
415            prev = Some(t);
416            continue;
417        }
418        match prev.map(|q| (q, running.iter().find(|r| r.0 == q).map(|r| r.1))) {
419            // plain and oxy without JS are gates: what follows waits for their verdict, and only some failures
420            // are worth the next tier
421            Some((q, Some(_))) if p.gate(q) => break,
422            Some((q, None)) if p.gate(q) && settled(q) => break,
423            // a provider still inside its hedge delay runs alone
424            Some((_, Some(e))) if e < p.hedge && can(t) => {
425                return Step::Wait((p.hedge - e).min(left(p, running, done)));
426            }
427            _ => {}
428        }
429        if can(t) {
430            return Step::Start(t);
431        }
432    }
433    match done.last() {
434        _ if !running.is_empty() => Step::Wait(left(p, running, done)),
435        Some(h) if retries(p, done, h) && can(h.tier) => Step::Start(h.tier),
436        Some(h) if let Some(step) = pause(p, done, h, spent) => step,
437        _ => Step::Stop,
438    }
439}
440
441/// THE rate-limit wait: a call the provider rate-limited with a time (`retry in 5s`, `provider::read`) is a wait,
442/// not a no: asked ONCE more when its pause ends inside the command's `wait:` (`Plan::patience`, from the run's
443/// start) and `cost:` (`spent` so far). Wait out what is left of it, then ask; None = no retry (no time given, a
444/// second limit, past `wait:`).
445fn pause(p: &Plan, done: &[Hop], h: &Hop, spent: f64) -> Option<Step> {
446    let s = h.why.split_once("retry in ")?.1.strip_suffix('s')?.parse().ok()?;
447    let at = h.end? + Duration::from_secs(s);
448    let first = done.iter().filter(|d| d.tier == h.tier).count() == 1;
449    let fits = at <= started(done)? + p.patience && spent + h.tier.spec().price <= p.cap + 1e-9;
450    let w = at.saturating_duration_since(Instant::now());
451    (h.code == "rate_limited" && first && fits).then_some(if w.is_zero() { Step::Start(h.tier) } else { Step::Wait(w) })
452}
453
454/// THE retry rule: with ONE paid provider on the keyed ladder (one key, or a gov
455/// host or `provider:bd` with both, or the other one refused this run) there is no other provider to cover a transient
456/// failure, so its failed call gets ONE retry after OUR cut (`provider_timeout`) or a network error, never after the
457/// provider's own refusal (`provider_error`, a non-200 API answer, `provider::read`: a final refusal; retries served
458/// 0/7 vs 3/9 after our cut), never on the site's own status (`Hop::status`: a 5xx page, a wall served as
459/// 503), a wall or a shell (the same answer again), nor in a prefetch (its page fetch covers it), nor a detached
460/// search (`one_call`: it got the retry's time at once, `timeout_of`), nor under the agent's `timeout:` (a hard budget;
461/// a search cut there is not asked again either); inside `cost:` (`next`'s `can`); never with less time than the call
462/// it repeats had (bd-only retries after a 60 s cut got 23.9-30 s under the wall, served 0/5): the run ends at the
463/// first timeout, its row buys more time (`fix_arg`). Never after a page render's own cut (a `js` row at its 40 s; a
464/// search is no render): of 131 served renders 8 took 40-60 s (1 of them read later), 0 longer, so a second render at
465/// twice the time and price buys almost nothing and blocks the run 40-80 s more; that cut ends the run.
466fn retries(p: &Plan, done: &[Hop], h: &Hop) -> bool {
467    let keyed = p.ladder(&[]).into_iter().filter(|t| p.keys.contains(t) && t.spec().price > 0.0 && !refused(done, *t));
468    let paid = uniq(keyed, |t| t.owner());
469    let cut = h.code == "provider_timeout" && (p.search || !h.tier.can("js"));
470    let transient = (cut || h.code == "net_error") && !one_call(p) && p.timeout.is_none();
471    let first = done.iter().filter(|d| d.tier == h.tier).count() == 1;
472    let time = wall_left(done, h).is_none_or(|w| w >= Duration::from_millis(h.ms));
473    paid.len() == 1 && h.tier.spec().price > 0.0 && transient && first && time
474}
475
476/// THE one-key wall (bd-only took 154 s to fail, a 60 s cut, then a 120 s retry): a run with one paid provider
477/// is final within `one_key_wall_s` of its first call, first visit included. What is left of it when `failed`
478/// landed (the run's start = the earliest hop's landing less its time); None = no landing time kept (a test's hop).
479/// The retry gets at most that (`timeout_of`), none when less than the failed call had is left (`retries`).
480fn wall_left(done: &[Hop], failed: &Hop) -> Option<Duration> {
481    let gone = failed.end?.saturating_duration_since(started(done)?);
482    Some(Duration::from_secs(limit("one_key_wall_s")).saturating_sub(gone))
483}
484
485/// When the run started: the earliest hop's landing less its time; None = no landing time kept (a test's hop).
486fn started(done: &[Hop]) -> Option<Instant> {
487    done.iter().filter_map(|h| h.end?.checked_sub(Duration::from_millis(h.ms))).min()
488}
489
490/// A search asked once: a detached one (no `wait:`: `cli::search_of` past `wait:`, `cli::resume`; one detached
491/// search ran bd 15,004 + 14,999 ms) runs its call to the retry's time at once, never cut and asked again under
492/// the same cut (bd-only `timeout:1` asked twice for one cut; `timeout:` = `retries`). An inline search keeps its
493/// retry whatever its `wait:` (the 30 s default is no detach, S6).
494fn one_call(p: &Plan) -> bool {
495    p.search && p.wait.is_none()
496}
497
498/// A served answer the reader would flag `! thin` (`outline::is_thin`).
499fn thin(h: &Hop) -> bool {
500    h.ok && h.doc.as_ref().is_some_and(is_thin)
501}
502
503/// An app page (`no_copy`): a JS shell, and shells or timeouts from two different paid providers (one
504/// provider's shell is that provider's failure, airbnb: bd shells, Oxylabs renders it; OUR short cut is no
505/// provider's answer). The ladder runs on
506/// until then, so this only names the outcome.
507fn app_page(done: &[Hop]) -> bool {
508    let ran = |h: &&Hop| h.tier.spec().price > 0.0 && !ours(&h.code, h.upto);
509    let paid = |h: &&Hop| ran(h) && matches!(h.code.as_str(), "js_shell" | "provider_timeout");
510    done.iter().any(|h| h.code == "js_shell") && uniq(done.iter().filter(paid), |h| h.tier.owner()).len() > 1
511}
512
513/// Time until the longest running call is given up on.
514fn left(p: &Plan, running: &[(Tier, Duration)], done: &[Hop]) -> Duration {
515    let grace = Duration::from_secs(limit("grace_s"));
516    let d = running.iter().map(|&(t, e)| (p.timeout_of(t, done) + grace).saturating_sub(e)).max();
517    d.unwrap_or(Duration::ZERO).max(Duration::from_millis(10))
518}
519
520pub type Call = Pin<Box<dyn Future<Output = Hop> + Send>>;
521
522/// Run the table: start what `next` says, wait for the first answer, cancel what is left. `call` gets the tier
523/// and the hops so far (a PDF run by then: `pdf_run`; its timeout: `timeout_of`).
524/// A cancelled call is a hop too (`abandoned`, or cut at the plan's `wait`; its bill unverified, `billed`).
525/// `done` = hops settled before the first call (`host_hop`); `seen` gets the tiers so far each time one starts or
526/// lands.
527pub fn drive(p: &Plan, call: &dyn Fn(Tier, &[Hop]) -> Call, mut done: Vec<Hop>, seen: Seen) -> Vec<Hop> {
528    crate::provider::block(async {
529        let mut set = tokio::task::JoinSet::new();
530        let mut running = Vec::<Running>::new();
531        let (end, mut cut) = (p.wait.map(|w| Instant::now() + w), None);
532        loop {
533            let now: Vec<(Tier, Duration)> = running.iter().map(|r| (r.0, r.1.elapsed())).collect();
534            let step = pooled(p, &done, &now);
535            let left = end.map(|e| e.saturating_duration_since(Instant::now()));
536            if left == Some(Duration::ZERO) && !matches!(step, Step::Stop) {
537                cut = p.wait;
538                break;
539            }
540            match step {
541                Step::Start(t) => {
542                    let id = set.spawn(call(t, &done)).id();
543                    running.push((t, Instant::now(), id, p.timeout_of(t, &done)));
544                }
545                Step::Wait(d) => {
546                    let d = left.map_or(d, |l| d.min(l));
547                    // a pool's turn has no call to land (`pooled`): a sleep, never a join on an empty set (a spin)
548                    if set.is_empty() {
549                        tokio::time::sleep(d).await;
550                    } else if let Ok(Some(r)) = tokio::time::timeout(d, set.join_next_with_id()).await
551                        && let Some(h) = landed(r, &mut running)
552                    {
553                        done.push(cut_why(p, h));
554                    }
555                }
556                Step::Stop => break,
557            }
558            let mark = |h: &Hop| if h.ok { "✓".to_string() } else { format!(":{}✗", h.code) };
559            let tried = done.iter().map(|h| format!("{}{}", h.tier.spec().short, mark(h)));
560            let busy = running.iter().map(|r| format!("{} running", r.0.spec().short));
561            // the newest running call's start, and the last running call's deadline (its timeout as it started)
562            let at = |i: Instant| crate::cache::now() - i.elapsed().as_secs_f64();
563            let since = running.iter().map(|r| at(r.1)).fold(0.0, f64::max);
564            let until = running.iter().map(|r| at(r.1) + r.3.as_secs_f64()).fold(0.0, f64::max);
565            seen((tried.chain(busy).collect::<Vec<_>>().join(" · "), since, until));
566        }
567        set.abort_all();
568        let abandoned = |t: Tier| Hop { tier: t, code: "abandoned".into(), ..Hop::default() };
569        let gone = |t: Tier| cut.map_or_else(|| abandoned(t), |wait| Hop::failed(t, crate::provider::late(wait)));
570        for (t, t0, _, d) in running {
571            done.push(cut_why(p, Hop { timeout_s: d.as_secs(), ..billed(t0, false, t.spec().price, gone(t)) }));
572        }
573        done
574    })
575    .unwrap_or_else(|| vec![Hop { code: "net_error".into(), ..Hop::default() }])
576}
577
578/// A batch's `cost:` pool file: each run's `[floor, hold]` (`seed`, `pooled`).
579type Pool = BTreeMap<usize, [f64; 2]>;
580
581/// THE batch's `cost:` pool (`Plan::pool`, one file a batch): under its lock this run's cap is what the other runs
582/// leave (`claims`), a paid call holds its price before it starts, and every turn sets the run's hold to what it
583/// `held`; its floor goes when it stops (plain served it: within its plain call): Σ billed ≤ `cost:`. The trade-offs
584/// of a floor set at launch (`seed`): a queued page keeps its share until its turn; a page short of its rung stops
585/// and gives its share back, so of two pages on even shares the one that meets the cap second gets both (which one
586/// is a race, never input order; one of them always runs on). A run short only of the floors of runs already
587/// started waits a turn (`POOL_TURN`, within its `timeout:`) with its own floor given back, never `budget_hit`
588/// while those come back (2 pages at `cost:0.002`, $0.001 each: the one plain could not serve needs a $0.0015 render
589/// as the other's plain serves); two such runs never wait on each other.
590fn pooled(p: &Plan, done: &[Hop], running: &[(Tier, Duration)]) -> Step {
591    let Some((at, me)) = &p.pool else { return next(p, done, running) };
592    crate::cache::edit(at, |pool: &mut Pool| {
593        let left = |soon| (p.cap - spend(claims(at, pool, *me, soon).into_iter().map(|o| o.1))).max(0.0);
594        let step = next(&Plan { cap: left(false), ..p.clone() }, done, running);
595        let hope = || matches!(next(&Plan { cap: left(true), ..p.clone() }, done, running), Step::Start(_));
596        let turn = matches!(step, Step::Stop) && hope();
597        let start = if let Step::Start(t) = step { t.spec().price } else { 0.0 };
598        let floor = if matches!(step, Step::Stop) { 0.0 } else { pool.get(me).map_or(0.0, |h| h[0]) };
599        pool.insert(*me, [floor, held(done, running) + start]);
600        if turn { Step::Wait(p.agent_left(done).map_or(POOL_TURN, |l| l.min(POOL_TURN))) } else { step }
601    })
602    .unwrap_or(Step::Stop)
603}
604
605/// How often a run short of the pool looks again (`pooled`): a plain call it waits for takes ~0.1-10 s.
606const POOL_TURN: Duration = Duration::from_millis(250);
607
608/// The other runs' claims on the pool `at`, each the larger of its hold and the floor it still holds (` held`: not
609/// spent yet); none = no row. A run that died (`cache::run_at`: its lock let go, killed before it gave its floor
610/// back) holds no floor; its hold stays, a call it started may be billed. `soon` = only a queued run's floor
611/// (`Detached::by`, not started: no pid) counts: a started one gives its floor back when it stops.
612fn claims(at: &std::path::Path, pool: &Pool, me: usize, soon: bool) -> Vec<(usize, f64, &'static str)> {
613    let run = |n: usize| crate::cache::run_at(&at.with_file_name(format!("u{n}.json")));
614    let alive = |n| run(n).is_none_or(|(r, alive)| alive && !(soon && (r.by == 0 || r.pid != 0)));
615    let claim = |(&n, &[f, h]): (&usize, &[f64; 2])| if f > h && alive(n) { (n, f, " held") } else { (n, h, "") };
616    pool.iter().filter(|o| *o.0 != me).map(claim).filter(|o| o.1 > 0.0).collect()
617}
618
619/// What a run spent or holds, THE one rule of the cap: billed, maybe billed (a cut call's `upto`) and running.
620fn held(done: &[Hop], running: &[(Tier, Duration)]) -> f64 {
621    spend(done.iter().map(|h| h.cost + h.upto).chain(running.iter().map(|r| r.0.spec().price)))
622}
623
624/// A batch's pool at its launch: each run's floor = one paid try whatever plain says (its uncapped route's dearest
625/// rung: the cheapest, oxy's $0.001, left a page plain sent to a render short), held until the run stops, so one
626/// page's hedge never buys a queued page's first paid try. Floors over `cap` are cut to an even share each
627/// (`cap` / pages; a first page's whole floor left the next none, which a $0.001 rung would have served): no page
628/// is starved before it runs; one whose share is short stops and gives it back (`pooled`).
629pub fn seed(at: &std::path::Path, runs: impl Iterator<Item = (usize, Plan)>, cap: f64) -> Result<(), String> {
630    let dearest = |p: Plan| route(&Plan { cap: f64::INFINITY, ..p }).0.into_iter().map(|t| t.0.spec().price);
631    let floors: Vec<(usize, f64)> = runs.map(|(n, p)| (n, dearest(p).fold(0.0, f64::max))).collect();
632    let share = if spend(floors.iter().map(|f| f.1)) > cap + 1e-9 { cap / floors.len() as f64 } else { cap };
633    let pool: Pool = floors.into_iter().map(|(n, f)| (n, [f.min(share), 0.0])).collect();
634    crate::cache::edit(at, |old: &mut Pool| *old = pool)
635}
636
637/// Why WE cut a call (`Hop::why`, named by `fail_detail`): `timeout:8s` = the agent's `timeout:` (its fix is
638/// the default time), else `took > 40 s here` (`fail_detail` reads it as `cut at 40 s (3m ago)`).
639fn cut_why(p: &Plan, mut h: Hop) -> Hop {
640    let s = h.timeout_s;
641    if h.code == "provider_timeout" && h.status == 0 && h.why.is_empty() {
642        // under `timeout:` a render gets what the agent's wall left (`agent_left`): its cut is named as the agent typed
643        // it
644        let user = p.timeout.map(|w| w.as_secs()).filter(|&w| (h.tier.can("js") && s <= w) || s == w);
645        h.why = user.map_or_else(|| format!("took > {s} s here"), |w| format!("timeout:{w}s"));
646    }
647    h
648}
649
650/// THE host check's hop (`provider::host_check`), before any tier runs: a plain hop, final, $0.
651fn host_hop(url: &str, wall: Option<Duration>) -> Option<Hop> {
652    let t0 = Instant::now();
653    let (code, why) = crate::provider::host_check(url, wall)?;
654    Some(Hop { tier: Tier::Plain, code: code.into(), ms: t0.elapsed().as_millis() as u64, why, ..Hop::default() })
655}
656
657/// A running call, and its timeout (`Plan::timeout_of` when it started).
658type Running = (Tier, Instant, tokio::task::Id, Duration);
659
660/// Who watches a run (`drive`): its status, the newest running call's start and the last one's deadline (epoch
661/// seconds); a detached fetch writes them to its run file; a call nobody watches passes `&drop`.
662pub type Seen<'a> = &'a dyn Fn((String, f64, f64));
663
664/// A finished call's hop, taken off `running` (a call that panicked is `parse_failed`); None = not one of ours.
665fn landed(r: Result<(tokio::task::Id, Hop), tokio::task::JoinError>, running: &mut Vec<Running>) -> Option<Hop> {
666    let at = running.iter().position(|x| x.2 == r.as_ref().map_or_else(|e| e.id(), |(id, _)| *id))?;
667    let (tier, t0, _, d) = running.remove(at);
668    let failed = || Hop { tier, code: "parse_failed".into(), ms: t0.elapsed().as_millis() as u64, ..Hop::default() };
669    Some(Hop { timeout_s: d.as_secs(), ..r.map(|(_, h)| h).unwrap_or_else(|_| failed()) })
670}
671
672/// THE billing rule's other half (both providers): a finished provider call → its hop: how long it took, the
673/// tier's price when the provider bills its answer (`provider::charged`), else for a call WE cut (our timeout,
674/// `timeout:`, `wait:`, abandoned: no status, the provider never answered) the price as `upto`, unverified: the
675/// provider may finish it (bd billed ≥ 2 of 4 searches cut at 15 s; +0 for 1-s cuts); the
676/// provider's own refusal, error envelope or 5xx stays $0. THE one place a hop's time and bill are set.
677fn billed(t0: Instant, bill: bool, price: f64, mut h: Hop) -> Hop {
678    let cut = h.status == 0 && matches!(h.code.as_str(), "provider_timeout" | "abandoned");
679    (h.ms, h.end) = (t0.elapsed().as_millis() as u64, Some(Instant::now()));
680    (h.cost, h.upto) = if bill { (price, 0.0) } else { (0.0, if cut { price } else { 0.0 }) };
681    h
682}
683
684/// One provider call → its hop (`billed`): a failure as `Hop::failed`, an answer through `ok`.
685async fn hop_of<T>(t: Tier, price: f64, call: impl Future<Output = Called<T>>, ok: impl FnOnce(T) -> Hop) -> Hop {
686    let t0 = Instant::now();
687    let (r, bill) = call.await;
688    billed(t0, bill, price, r.map_or_else(|f| Hop::failed(t, f), ok))
689}
690
691/// A provider call's answer, and whether it may be billed (`provider::get`).
692type Called<T> = (Result<T, Fail>, bool);
693
694/// The network transport: one provider call, then the content check. A `/pdf/` path (`hint`) asks Bright Data for
695/// raw bytes like a PDF run, but only a PDF run fails a page as `not_pdf`.
696pub fn run(p: &Plan, ask: &Ask, seen: Seen) -> Vec<Hop> {
697    let call = |t: Tier, done: &[Hop]| -> Call {
698        let (mut ask, pdf) = (ask.clone(), p.pdf_run(done));
699        (ask.js, ask.doc) = (t.renders(), pdf || p.hint);
700        ask.timeout = Some(p.timeout_of(t, done));
701        let (key, price, prior, card) = (t.key().unwrap_or_default(), t.spec().price, p.prior.clone(), !p.js && !pdf);
702        let (langs, turn) = (langs(&ask, done), (t == Tier::Plain).then(|| crate::provider::pace(&ask.url)));
703        Box::pin(async move {
704            let ok = |raw: Raw| Hop { limit: raw.limit, ..judge(t, raw, &ask.url, ask.js, pdf) };
705            let (key, ok) = (&key, &ok);
706            let get = |a: Ask| async move { hop_of(t, price, crate::provider::get(t, &a, key), ok).await };
707            let mut first = get(ask.clone()).await;
708            if let Some(why) = first.doc.as_ref().and_then(|d| md_weak(d, prior.as_deref())) {
709                // the HTML ask failing keeps the Markdown copy, its why says so (`md:thin+html:blocked_403`)
710                let h = get(Ask { html: true, ..ask.clone() }).await;
711                let (ms, failed) = (first.ms + h.ms, format!("{why}+html:{}", h.code));
712                first = if h.ok { Hop { ms, why: why.into(), ..h } } else { Hop { ms, why: failed, ..first } };
713            }
714            first.waited = turn.map_or(0, |t| t.1);
715            geo(if card && !ask.js { og_card(first, &ask.url) } else { first }, &langs)
716        })
717    };
718    let hops = drive(p, &call, host_hop(&ask.url, p.agent_left(&[])).into_iter().collect(), seen).into_iter();
719    hops.map(|h| Hop { country: sent(ask, h.tier).unwrap_or_default(), ..h }).collect()
720}
721
722/// THE language rule: the languages a provider's copy should be in: the `country:` mod's (`locale`),
723/// else the page's own: its URL's locale words (the ccTLD, the first host label and the FIRST path segment shaped
724/// `xx` / `xx-yy`: `.fr`, `de.`, `en-gb.`, `/es/es/`, `/pt-br/`; a later segment is the site's own word, Booking's
725/// `/hotel/fr/` is the hotel's country: 10 of 16 false flags in a 196-copy replay) with
726/// the `<html lang>` of plain's copy when plain held the page (`judge`: never a wall's). None of them = no
727/// expectation, no flag: `js:true`, which skips plain, never flags a non-English `.com`. A served copy whose
728/// primary tag is none of them is a provider's geo copy: its hop's `why` says `lang:it` (`oxyjs✓lang:it`),
729/// `outline::page_flags` flags it on every read with the fix. Where none of them names one and no query value
730/// does either (`hl=fr`, `lang=de`), a call that sends no country (`provider::sent`: Bright Data at home US) expects
731/// `en`; the ask is kept for that (`geo`). Its own pick served Booking and Airbnb in Spanish (a
732/// replay on 234 saved paid copies: 21 more foreign copies flagged, 0 English or own-language ones).
733fn langs(ask: &Ask, done: &[Hop]) -> (Vec<String>, Option<Ask>) {
734    let named = ask.country.as_deref().map(|c| locale(&c.to_lowercase())).unwrap_or_default();
735    let plain = done.iter().filter(|h| h.tier == Tier::Plain && !h.lang.is_empty()).map(|h| h.lang.clone());
736    let Ok(u) = url::Url::parse(&ask.url) else { return (named, None) };
737    let host: Vec<&str> = u.host_str().unwrap_or_default().split('.').collect();
738    let label = host.first().filter(|_| host.len() > 2).copied();
739    let shaped = |s: &&str| s.len() == 2 || (s.len() == 5 && matches!(s.as_bytes()[2], b'-' | b'_'));
740    let first = u.path_segments().into_iter().flatten().next();
741    let words = label.into_iter().chain(first).filter(shaped).flat_map(|s| s.split(['-', '_']));
742    let words = host.last().copied().into_iter().chain(words).flat_map(|w| locale(&w.to_lowercase()));
743    let own = uniq(words.chain(plain), String::clone);
744    let tagged = |v: &str| shaped(&v) && v.split(['-', '_']).any(|w| !locale(&w.to_lowercase()).is_empty());
745    let bare = (named.is_empty() && own.is_empty() && !u.query_pairs().any(|(_, v)| tagged(&v))).then(|| ask.clone());
746    (if named.is_empty() { own } else { named }, bare)
747}
748
749/// The languages a locale word names through `Providers::cctld`: a ccTLD (`uk`) or a country (`gb`) → its row's
750/// (`ch` → de fr it), a row's language (`en`) → itself; any other word names none.
751fn locale(word: &str) -> Vec<String> {
752    let rows = &PROVIDERS.cctld;
753    let langs = |r: &&str| r.split(' ').skip(1).map(String::from).collect::<Vec<_>>();
754    let row = rows.get(word).or_else(|| rows.values().find(|r| r.split(' ').next() == Some(word)));
755    row.map_or_else(|| rows.values().flat_map(langs).filter(|l| l == word).take(1).collect(), langs)
756}
757
758/// A provider's copy outside `langs` (none = no expectation; `en` when it names no locale and the call sent no
759/// country) says so in its `why`, after a status it carries: `lang:it`, `403+lang:it`. A copy whose own canonical
760/// link names the asked URL (`landed`) is the site's page in the site's language, so no `en` is expected of it: a
761/// geo copy names its language's URL (`x.es.html`) or another site. The dropped expectation leaves a trace, never
762/// a flag: `own:es` in its `why` (`bd✓own:es` in the tried path: `stats`, meta.json's hops).
763fn geo(mut h: Hop, (langs, bare): &(Vec<String>, Option<Ask>)) -> Hop {
764    let own = |a: &Ask| url::Url::parse(&a.url).is_ok_and(|u| h.landed.as_deref() == Some(u.as_str()));
765    let unsent = bare.as_ref().filter(|a| sent(a, h.tier).is_none());
766    let langs = if unsent.is_some() { &vec!["en".into()] } else { langs };
767    if h.ok && h.tier != Tier::Plain && !h.lang.is_empty() && !langs.is_empty() && !langs.contains(&h.lang) {
768        let tag = if unsent.is_some_and(own) { "own" } else { "lang" };
769        h.why = format!("{}{}{tag}:{}", h.why, if h.why.is_empty() { "" } else { "+" }, h.lang);
770    }
771    h
772}
773
774/// THE Markdown guard: a server's own `text/markdown` answer (`clean::kind_of` `md`) is not served when it is thin
775/// (`thin_chars` of prose) or under a fifth of the prose of the copy stored before, or flat (no heading) where
776/// that copy had ≥ 3 sections; plain then asks again for HTML only (`Ask::html`), and the Markdown is served when
777/// that ask fails. `prior` = the stored copy's folder: its doc.json is read only for a Markdown answer, never
778/// rebuilt. The reason is the served hop's `why` (`plain✓md:thin` in `tried`).
779fn md_weak(d: &Doc, prior: Option<&std::path::Path>) -> Option<&'static str> {
780    if d.mode != "md" {
781        return None;
782    }
783    let flat = d.sections.iter().enumerate().all(|(i, s)| s.title == format!("part {}", i + 1));
784    let stored = prior.and_then(|p| crate::cache::jload::<Doc>(&p.join("doc.json")));
785    let (n, tok) = stored.map_or((0, 0), |p| (p.sections.len(), p.tokens.clean));
786    let thin = d.loss.pruned_chars < limit("thin_chars") || d.tokens.clean * 5 < tok;
787    thin.then_some("md:thin").or((flat && n >= 3).then_some("md:flat"))
788}
789
790/// og_only, THE card rule (any tier but the render, oxyjs, and never in a `js:true` or PDF run): a JS shell, or a
791/// 4xx that is not a missing page, whose head carries a page's own og card is served now as that card: `mode` og,
792/// ok, the ladder stops (`outline` adds `! js_shell → … js:true` while a render is left). A page's own card = an
793/// og:description of ≥ 40 chars, an og:title or og:image beside it, and an og:title that is not the og:site_name:
794/// a wall or an app shell carrying the site-wide card (a maps shell, a login wall) is not the page. Stored as kind
795/// `og` (`clean::card`), so a rebuild of the body makes the card again.
796fn og_card(mut h: Hop, url: &str) -> Hop {
797    let shell = !h.ok && (h.code == "js_shell" || (400..500).contains(&h.status) && !FINAL.contains(&h.code.as_str()));
798    let own = |t: &Tree| {
799        let (title, site) = (t.meta("og:title").map(clean::fold), t.meta("og:site_name").map(clean::fold));
800        let desc = t.meta("og:description").map_or(0, |d| d.trim().chars().count());
801        desc >= 40 && (title.is_some() || t.meta("og:image").is_some()) && (title.is_none() || title != site)
802    };
803    let Some(tree) = h.tree.as_ref().filter(|t| shell && own(t)) else { return h };
804    let fin = if h.final_url.is_empty() { url } else { &h.final_url };
805    if let Ok(card) = guarded(|| Ok(clean::card(clean::build_doc(tree, url, fin, false)))) {
806        (h.ok, h.code, h.kind, h.doc, h.tree) = (true, "ok".into(), "og", Some(card), None);
807    }
808    h
809}
810
811/// The search transport: one search call per tier `next` starts; an answer that parses is `ok`, even empty.
812pub fn run_search(p: &Plan, q: &str, limit: usize, country: Option<&str>) -> Vec<Hop> {
813    let call = |t: Tier, done: &[Hop]| -> Call {
814        let (q, country, wait, price) =
815            (q.to_string(), country.map(String::from), p.timeout_of(t, done), t.spec().price);
816        Box::pin(async move {
817            let ok = |(hits, limit)| Hop { tier: t, ok: true, code: "ok".into(), hits, limit, ..Hop::default() };
818            hop_of(t, price, crate::provider::search(t, &q, limit, country.as_deref(), wait), ok).await
819        })
820    };
821    let cc = search_country(country);
822    drive(p, &call, Vec::new(), &drop).into_iter().map(|h| Hop { country: cc.clone(), ..h }).collect()
823}
824
825/// `route`'s answer: each tier with its hedge delay (None = after the call before it), and the worst-case cost.
826pub type Route = (Vec<(Tier, Option<Duration>)>, f64);
827
828/// What `dry:true` prints: the tiers a fully failing run would try, in order, each with the delay after which it
829/// starts beside the call before it (`next` hedges it) or None (it waits for that call's verdict), and the
830/// worst-case cost.
831pub fn route(p: &Plan) -> Route {
832    // a worst case: every call runs out its time (a clock, so the one-key wall decides a retry); under the
833    // agent's one wall every render fails at once, so each one left gets to start and bill; plain meets the
834    // wall that keeps every rung after it (a captcha keeps oxy no-JS with both keys), and so does a page's no-JS
835    // rung (cut, it would skip the next one: `ladder`)
836    let page = !p.search && !p.hint && !p.pdf_run(&[]);
837    let fail = |t: Tier, ms: Duration, end| {
838        let ms = if p.timeout.is_some() { 0 } else { ms.as_millis() as u64 };
839        let wall = t == Tier::Plain || page && !t.can("js");
840        let code = if wall { CHECK.no_js_first[0] } else { "provider_timeout" }.into();
841        Hop { tier: t, code, kind: "html", cost: t.spec().price, ms, end, ..Hop::default() }
842    };
843    let (mut done, mut path, mut clock) = (Vec::new(), Vec::new(), Instant::now());
844    while let Step::Start(t) = next(p, &done, &[]) {
845        // a tier hedged at or past a search's `wait:` never starts beside: it runs only after a fast failure
846        let beside = match next(p, &done, &[(t, p.hedge)]) {
847            Step::Start(u) if p.wait.is_none_or(|w| p.hedge < w) => Some((u, Some(p.hedge))),
848            _ => None,
849        };
850        let start = clock;
851        for (u, d) in std::iter::once((t, None)).chain(beside) {
852            let (ms, at) = (p.timeout_of(u, &done), start + d.unwrap_or_default());
853            path.push((u, d));
854            clock = clock.max(at + ms);
855            done.push(fail(u, ms, Some(at + ms)));
856        }
857    }
858    (path, spend(done.iter().map(|h| h.cost)))
859}
860
861/// The `!` row for what the provider that served the page did not honour: `device:mobile` on Bright Data (the
862/// page's language: a page flag, `outline::page_flags`).
863pub fn ignored(ask: &Ask, hops: &[Hop], id: &str) -> Vec<String> {
864    let bd = hops.iter().any(|h| h.ok && h.tier == Tier::Bd);
865    let at = At { id, url: &ask.url, arg: "device:mobile", ..Default::default() };
866    let what = "device bd · Bright Data has no device setting: desktop page";
867    (ask.mobile && bd).then(|| bang(id, "ignored", what, &at)).into_iter().collect()
868}
869
870/// `!` rows for tiers a failed run never tried: one per missing key, one for the cap with what the rest would
871/// cost. `subject` heads the rows (a snapshot's id, empty for a search); `id` = what the hint reruns, on `url` ("" =
872/// a search; the cap's arrow priced for the URL's own plan, as its `dry:true`).
873pub fn skipped(p: &Plan, hops: &[Hop], subject: &str, id: &str, url: &str) -> Vec<String> {
874    let zip = p.doc == Some("zip") && p.ladder(&[])[0] == Tier::Plain;
875    if hops.iter().any(|h| h.ok) || zip || hops.iter().any(|h| p.gate(h.tier) && !escalates(h)) {
876        return Vec::new();
877    }
878    // a provider that refused a page leaves the auto ladder's other rungs, pinned or not: their key rows are the move
879    let refusal = !p.search && hops.iter().any(|h| h.code == "provider_refused");
880    let ladder = Plan { mode: if refusal { Mode::Auto } else { p.mode }, ..p.clone() }.ladder(hops);
881    let left: Vec<Tier> = ladder.into_iter().filter(|t| !hops.iter().any(|h| h.tier == *t)).collect();
882    // two paid providers lost the page: the site refuses it, a third key is no move (so no `→ fats setup` either)
883    let lost = uniq(hops.iter().filter(|h| !h.ok && h.tier.spec().price > 0.0), |h| h.tier.owner()).len();
884    let mut rows = if lost >= 2 { Vec::new() } else { no_key(p, &left, subject, false) };
885    let over: Vec<Tier> = left.into_iter().filter(|t| p.keys.contains(t) && !refused(hops, *t)).collect();
886    // the same rule as `next`/`pooled`: a tier the cap stopped (one cut at a search's `wait:` was not); in a batch
887    // the cap the agent typed, the other runs' claims read under the pool's lock (who spent it: `budget_row`)
888    let others =
889        |(at, me): &(std::path::PathBuf, usize)| crate::cache::edit(at, |o: &mut Pool| claims(at, o, *me, false));
890    let by = p.pool.as_ref().and_then(|pool| others(pool).ok());
891    let (spent, others) = (held(hops, &[]), spend(by.unwrap_or_default().iter().map(|o| o.1)));
892    if over.iter().any(|t| spent + others + t.spec().price > p.cap + 1e-9) {
893        let want = spent + spend(over.iter().map(|t| t.spec().price));
894        let names: Vec<&str> = over.iter().map(|t| t.spec().short).collect();
895        // up to the next $0.0001, past a sum's float noise: 3 × $0.0015 sums to 0.0045000000000000005, never $0.0046
896        let (cap, want) = (p.cap, (want * 1e4 - 1e-6).ceil() / 1e4);
897        let what = format!("{} not tried · ${want:.4} > cost:{cap}", names.join(" "));
898        rows.push(bang(subject, "budget_hit", &what, &At { id, url, arg: &want.to_string(), ..At::default() }));
899    }
900    rows
901}
902
903/// The document kind a path's suffix names (`Sites::doc_ext`), lower case in: `html` = a page.
904pub fn doc_kind(path: &str) -> Option<&'static str> {
905    SITES.doc_ext.iter().find(|e| path.ends_with(e.0)).map(|e| e.1)
906}
907
908/// The tiers with a key configured (`Tier::key`). Unit tests run with the keys of the world they model
909/// (`tests::KEYED`): the key dir of the machine that runs them never changes an answer (the binary's tests set
910/// their own).
911pub fn keyed() -> Vec<Tier> {
912    #[cfg(test)]
913    let has = |t: &Tier| tests::KEYED.contains(t);
914    #[cfg(not(test))]
915    let has = |t: &Tier| t.key().is_some();
916    Tier::ALL.into_iter().filter(has).collect()
917}
918
919/// THE `no_key` row (fetch, search, dry, setup, account), one per provider of `left` without a key: what its key
920/// would add to this run and the price, `! no_key bd · would try unblock+JS ≤$0.0015 → fats setup bd` (the key's
921/// one way in: its form, which names the sign-up page; a key in the environment is never sent); `setup` = said
922/// inside `fats setup`: what the key adds and its form, no arrow (`offer`).
923pub fn no_key(p: &Plan, left: &[Tier], subject: &str, setup: bool) -> Vec<String> {
924    let row = |o: &Tier| {
925        let (s, mine) = (o.owner().spec(), left.iter().filter(|t| t.owner() == o.owner()));
926        let buys = if p.search { vec!["web search"] } else { uniq(mine.clone().map(|t| t.spec().buys), |b| *b) };
927        let (cost, sw) = (spend(mine.map(|t| t.spec().price)), o.switch());
928        let kept = crate::settings::key(sw).map_or("", |_| " (key kept)");
929        // a switch turned off, or bd's key without its zone, is no missing key: its row says which (`! off free`)
930        let (code, what, arg) = match (crate::settings::on(sw), sw) {
931            (false, "free") => ("off", "free fetch turned off".into(), sw),
932            (false, _) => ("off", format!("turned off{kept}"), sw),
933            (true, "bd") if !kept.is_empty() => ("no_zone", "key saved, no Web Unlocker zone yet".into(), "<name>"),
934            // a key in the environment: its row (`setup::env_row`) says so and copies it in
935            _ if let Some(env) = crate::setup::env_row(sw).filter(|_| !setup) => {
936                return format!("{subject} {env}").trim_start().into();
937            }
938            _ => ("no_key", String::new(), ""),
939        };
940        if code != "no_key" {
941            return bang(subject, code, &format!("{sw} · {what}"), &At { arg, ..At::default() });
942        }
943        if setup {
944            return format!("! no_key {}", offer(o.owner()));
945        }
946        let what = format!("{} · would try {} ≤${cost:.4}", s.short, buys.join(" + "));
947        let next = fix("no_key", &At { arg: s.short, ..At::default() });
948        Flag { code: "no_key".into(), what, next, row: true }.bang(subject)
949    };
950    // the tiers without a key, one row a provider (both Oxylabs tiers share one), the cheapest first
951    let mut owners = uniq(left.iter().filter(|t| !p.keys.contains(t)), |t| t.owner());
952    let cost = |o: &&Tier| spend(left.iter().filter(|t| t.owner() == o.owner()).map(|t| t.spec().price));
953    owners.sort_by(|a, b| cost(a).total_cmp(&cost(b)));
954    owners.into_iter().map(row).collect()
955}
956
957/// What provider `o`'s key adds, said inside `fats setup` (and `keys`) with no price: an agent relays a bare `≤$X` on
958/// a status row as the price of an answer. Then its form, for the user (`oxy · search + JS pages · fats setup oxy,
959/// 3 steps for the user`); a provider that cannot search says so (`decodo · JS pages, no web search · …`).
960fn offer(o: Tier) -> String {
961    let (b, s) = (bin(), o.spec().short);
962    if Tier::ALL.into_iter().any(|t| t.owner() == o && t.can("search")) {
963        format!("{s} · search + JS pages · {b} setup {s}, 3 steps for the user")
964    } else {
965        format!("{s} · JS pages, no web search · {b} setup {s}")
966    }
967}
968
969/// The move to the key a web search needs first, the cheapest searcher's (`→ fats setup oxy`, `lang::fix`).
970pub fn search_key() -> String {
971    fix("no_key", &At { arg: searchers().first().copied().unwrap_or_default(), ..At::default() })
972}
973
974/// The providers a web search runs on, cheapest first by the price a search there is billed at (a tier's one price
975/// a request, page or search: `billed`): the first is the key to add (`oxy`).
976pub fn searchers() -> Vec<&'static str> {
977    let mut all: Vec<Tier> = Tier::ALL.into_iter().filter(|t| t.can("search")).collect();
978    all.sort_by(|a, b| a.spec().price.total_cmp(&b.spec().price));
979    all.into_iter().map(|t| t.spec().short).collect()
980}
981
982/// The heads of `no_key`'s rows: a provider's key missing, its switch off (`! off oxy · …`), bd's zone missing.
983pub const KEY_ROWS: [&str; 3] = ["! no_key ", "! off ", "! no_zone "];
984
985/// A failed run's stored rows for the tiers it never tried (`skipped`).
986pub fn skips(m: &Meta) -> impl Iterator<Item = &str> {
987    m.extra.get("skipped").and_then(|v| v.as_array()).into_iter().flatten().filter_map(|r| r.as_str())
988}
989
990/// A failed run's stored `budget_hit` row (`skipped`: the cap stopped it) as read now: a batch page's says who spent
991/// the batch's pool (`m`'s `pool`), every page with a claim, this one too, the parts summing to it: `(spent $0.0020:
992/// u1 $0.0010, u3 $0.0010)` (the others alone read as $0.0010 left). Read at each print, never stored: a page stops
993/// while another still holds an unbilled try (`u1 $0.0015 held`), which it bills after ($0.0020). Its arrow is the
994/// reader's (`lang::restamp` for `id`), through the settle gate (`clear`, `others` = the session's other copies):
995/// one that plans a settled tier is dropped, the row stays. Then, for a user who asked to pay, one provider's ask
996/// by name (` · if the user said pay, fats u1 fresh:true provider:oxy ≤$0.0025`, `left_ask`): a provider that
997/// fetches without JS first (oxy, then decodo: the table's order; its ask starts at that call and renders after),
998/// then bd; past the same gate, priced as that provider's whole path (`dry:true`'s `up to`). Only while two paid
999/// providers have a key: with one, the ask would repeat the row's own move.
1000pub fn budget_row(m: &Meta, id: &str, others: &[Meta]) -> Option<String> {
1001    let row = skips(m).find(|r| r.starts_with("! budget_hit "))?;
1002    let at = std::path::Path::new(m.extra.get("pool").and_then(|v| v.as_str()).unwrap_or_default());
1003    let all = crate::cache::jload(at).map(|pool: Pool| claims(at, &pool, 0, false)).filter(|a| !a.is_empty());
1004    let ids = all.iter().flatten().map(|o| format!("u{} ${:.4}{}", o.0, o.1, o.2)).collect::<Vec<_>>().join(", ");
1005    let by = all.map(|a| format!(" (spent ${:.4}: {ids}) → ", spend(a.iter().map(|o| o.1))));
1006    let row = crate::lang::restamp(&row.replacen(" → ", by.as_deref().unwrap_or(" → "), 1), id, &m.url);
1007    let row = row.split_once(" → ").filter(|r| !clear(r.1, m, others)).map_or(row.clone(), |r| r.0.into());
1008    let mut own: Vec<Tier> = keyed().into_iter().filter(|t| t.owner() == *t && t.spec().price > 0.0).collect();
1009    own.sort_by_key(|t| t.can("js"));
1010    let pay = left_ask(id, &m.url, &own, &[], |a| clear(a, m, others)).filter(|_| own.len() > 1);
1011    Some(row + &pay.map_or(String::new(), |a| format!(" · if the user said pay, {}", a.1)))
1012}
1013
1014/// A failed run's stored `no_key` rows (`skipped`) whose provider still has no key (`Tier::switch` names it).
1015pub fn no_key_left(m: &Meta) -> Vec<&str> {
1016    let left = |n: &str| !keyed().iter().any(|t| t.switch() == n);
1017    skips(m).filter(|&r| KEY_ROWS.iter().find_map(|k| r.strip_prefix(k)?.split(' ').next()).is_some_and(left)).collect()
1018}
1019
1020/// THE re-render rule: `js:true` on a page whose copy a render sent never asks that render again while another
1021/// provider's render has a key: it sends the same copy (bd's thin Reddit copy, bought twice).
1022pub fn rendered(m: &Meta, keys: &[Tier]) -> Option<Tier> {
1023    let t = Tier::parse(&m.provider).filter(|t| t.can("js"))?;
1024    keys.iter().any(|k| k.can("js") && k.owner() != t.owner()).then_some(t)
1025}
1026
1027/// A government host by its labels (`Sites::gov`), never a site list: its last label is one (`sec.gov`,
1028/// `army.mil`), or the one before a two-letter country code under which it sits (`data.gov.uk`, `x.gouv.fr`,
1029/// not `go.pl`). Bright Data refuses such hosts; one it refuses outside the rule (`europa.eu`) costs one $0 hop.
1030fn gov(url: &str) -> bool {
1031    let host = clean::host_of(url);
1032    let l: Vec<&str> = host.trim_end_matches('.').rsplit('.').collect();
1033    SITES.gov.contains(&l[0]) || l.len() >= 3 && l[0].len() == 2 && SITES.gov.contains(&l[1])
1034}
1035
1036/// The tiers a fix must not send again (`lang::At::done`): every tier this run called, every tier without a key
1037/// (`keys`: a hint never names a provider the user has no key for), bd on a gov host, and a no-JS
1038/// tier after a JS shell or challenge (`Check::render_first`: oxy no-JS served 0/33 there). Once no other paid
1039/// tier is left, a no-JS tier whose only signal was OUR cut (`ours`: it never said no) is not spent: it is the
1040/// move, at twice its time (`timeout_of`; oxy cut at 10 s served a thread 6 of 6 later). A render we cut is
1041/// spent: no longer call follows it (`fix_arg`).
1042/// `cuts` = the hops of the URL's other copies this session (cli `seen`): a tier another copy of the URL tried is no
1043/// fix either (a `provider:oxy` offer never shows again after the `provider:oxy` copy).
1044pub fn spent(m: &Meta, cuts: &[HopRow], keys: &[Tier]) -> Vec<&'static str> {
1045    let all_hops: Vec<&HopRow> = m.hops.iter().chain(cuts).collect();
1046    let js_wall = all_hops.iter().any(|h| CHECK.render_first.contains(&h.code.as_str()));
1047    // a provider's error page, or its refusal of the URL (Oxylabs' `url: value not supported`), is each of its tiers'
1048    let said = |h: &HopRow| matches!(h.code.as_str(), "error_page" | "provider_refused");
1049    let site_no = |t: &Tier| all_hops.iter().any(|h| said(h) && Tier::parse(&h.provider) == Some(t.owner()));
1050    let barred = |t: &Tier| !keys.contains(t) || gov(&m.url) && !t.can("gov") || js_wall && !t.can("js") || site_no(t);
1051    // Nor, then, one whose only word was its own error (`provider_error`) unless another copy's too or it settled
1052    let error = |h: &HopRow| h.code == "provider_error" && !cuts.iter().any(|c| c.provider == h.provider);
1053    let sett = settled(m, cuts, None);
1054    let error = |h: &HopRow| error(h) && !sett.contains(&h.provider.as_str());
1055    let done = |all: bool| {
1056        let gate = |h: &HopRow| ours(&h.code, h.upto) && Tier::parse(&h.provider).is_some_and(|t| !t.can("js"));
1057        // a rate limit is a wait, never the tier's answer (bd's `rate_limited` → `provider:bd`)
1058        let hops = all_hops.iter().filter(|h| h.code != "rate_limited" && (all || !gate(h) && !error(h)));
1059        let tiers = hops.filter_map(|h| Tier::parse(&h.provider)).chain(Tier::ALL.into_iter().filter(barred));
1060        tiers.map(|t| t.spec().short).collect::<Vec<_>>()
1061    };
1062    let all = done(true);
1063    if Tier::ALL.iter().any(|t| t.spec().price > 0.0 && !all.contains(&t.spec().short)) { all } else { done(false) }
1064}
1065
1066/// THE settle rule: the tiers (names) a provider's error settled for `m`'s URL: its own 4xx (the same request is
1067/// refused again: Oxylabs' 400-404 are not retryable) or its own retries given up (`faulted`). The hop keeps no
1068/// status, so it is read from `why`, which `provider::reason` starts with it (`400 url: value not supported`).
1069/// `m`'s own hops settle; another copy's (`cuts`) settles every copy when it gave up, is a 404 or names the `url`,
1070/// else only when the arrow's own request (`country` its `country:` mod) sends that tier the country the refused
1071/// call sent (`provider::sent`: `400 geo_location: …` refuses that country again, never another).
1072pub fn settled<'a>(m: &'a Meta, cuts: &'a [HopRow], country: Option<&str>) -> Vec<&'a str> {
1073    let is =
1074        |h: &HopRow| OWN_REASON.contains(&h.code.as_str()) && (h.why.starts_with('4') || h.why.contains("faulted"));
1075    let all = |h: &HopRow| h.why.contains("faulted") || h.why.starts_with("404") || h.why.contains(" url: ");
1076    let ask = Ask { url: m.url.clone(), country: country.map(String::from), ..Ask::default() };
1077    let same = |h: &HopRow| Tier::parse(&h.provider).is_some_and(|t| sent(&ask, t).unwrap_or_default() == h.country);
1078    let hops = m.hops.iter().chain(cuts).filter(|h| is(h) && (all(h) || same(h)));
1079    hops.map(|h| h.provider.as_str()).collect()
1080}
1081
1082/// A call WE cut (`upto`: no answer) is no provider's answer: no `app_page` vote.
1083fn ours(code: &str, upto: f64) -> bool {
1084    code == "provider_timeout" && upto > 0.0
1085}
1086
1087/// The cut a failed run's move and reason follow when the run ended in OUR cut, whatever code
1088/// heads the row (`outcome` puts a wall any tier met there): the tiers decide, not the head. Of two cuts, the first
1089/// render's of the table (`js:true`'s order, one provider at a time: bd), else the last.
1090pub fn cut_of(m: &Meta) -> Option<&HopRow> {
1091    let last = m.hops.iter().rfind(|h| h.code != "abandoned")?;
1092    let ended =
1093        last.code == "provider_timeout" && (m.code == last.code || m.code.ends_with("_wall") || last.upto > 0.0);
1094    let all = m.hops.iter().enumerate().filter(|(_, h)| ended && h.code == "provider_timeout");
1095    let first = Tier::ALL.into_iter().find(|t| t.can("js")).map(|t| t.spec().name);
1096    all.max_by_key(|(i, h)| (Some(h.provider.as_str()) == first, *i)).map(|(_, h)| h)
1097}
1098
1099/// The code a failed run's move follows (`lang::fix`): a timeout's when it ended in our cut (`cut_of`), else its own.
1100pub fn move_code(m: &Meta) -> &str {
1101    if cut_of(m).is_some() { "provider_timeout" } else { &m.code }
1102}
1103
1104/// `{arg}` of a failed fetch's fix (`lang::fix`), THE timeout move, judged on the session's hops of the URL (`cuts`
1105/// = its other copies'): after the agent's own `timeout:` cut shorter than the tier's time, none (`fresh:true`
1106/// = the default time, never `nothing left to try`); with no other keyed tier left untried, None = a COUNT, no
1107/// arrow, the run's end (no longer call after our cut: 0 of 131 saved renders answered in 60-150 s, the
1108/// four `timeout:150` calls that served did so in under 60 s), as after an error page with nothing left;
1109/// else a render (`js:true`, `lang::fix` names the keyed tier left; shells + timeouts = `no_copy`).
1110pub fn fix_arg(m: &Meta, cuts: &[HopRow]) -> Option<&'static str> {
1111    let (cut, done) = (cut_of(m), spent(m, cuts, &keyed()));
1112    // in a timeout's move a tier WE cut is tried too, else two cut renders defer to each other (`js:true`)
1113    let tried = |t: &Tier| cut.is_some() && m.hops.iter().chain(cuts).any(|h| h.provider == t.spec().name);
1114    let open = |t: &Tier| t.spec().price > 0.0 && !done.contains(&t.spec().short);
1115    let left = |not: Tier| Tier::ALL.iter().any(|t| open(t) && *t != not && !tried(t));
1116    // the certificate's answer (`provider::plain`): the keyed no-JS tier by name (`provider:oxy`), else none
1117    let no_js = Tier::ALL.iter().find(|t| open(t) && !t.can("js")).map(|t| ASK[*t as usize].as_str());
1118    let short = |h: &HopRow, t: Option<Tier>| t.is_none_or(|t| h.timeout_s < t.spec().timeout.as_secs());
1119    // The tier whose own failure ended the run, still unspent (`spent`: its error, the one tier left), by name
1120    let err = |h: &HopRow| Tier::parse(&h.provider).filter(|t| h.code == m.code && !done.contains(&t.spec().short));
1121    match cut.map(|h| (h, Tier::parse(&h.provider))) {
1122        None if m.code == "tls_failed" => no_js,
1123        // The site refused every keyed provider with its error page: a count; so is a site's 4xx
1124        None if (m.code == "error_page" || m.code.starts_with("http_4")) && !left(Tier::Plain) => None,
1125        // a settled tier is never asked again: `fail_row`'s gate (`settled`) names the tier left
1126        None => Some(m.hops.iter().find_map(err).map_or("", |t| &ASK[t as usize])),
1127        Some((h, t)) if h.why.starts_with("timeout:") && short(h, t) => Some(""),
1128        Some((_, Some(t))) if !left(t) => None,
1129        _ => Some("js:true"),
1130    }
1131}
1132
1133/// The re-render rule (`rendered`) for `url` applied to `p`, from the URL's newest stored copy.
1134pub fn route_of(c: &Cache, url: &str, p: &mut Plan) {
1135    p.avoid = c.lookup(url).and_then(|(dir, _)| c.meta(&dir)).filter(|_| p.js).and_then(|m| rendered(&m, &p.keys));
1136}
1137
1138/// The most an arrow (`fats u1 fresh:true …`, the words after the binary) can spend on `url`
1139/// ("" = its id's page, or a search), with the tiers it would call in order (`outline::js_next` names the first,
1140/// `fail_row`'s settle gate reads them all); None = it spends nothing. THE `≤$X` of every paid arrow
1141/// (`lang::priced`): `dry:true`'s `up to` for that command, the same plan (`Plan::of`, `route_of`) through the same
1142/// `route`.
1143pub fn worst(arrow: &str, url: &str) -> Option<Route> {
1144    // a key's move, then the page (`fats setup bd on, then fats u4 …`): the page's move, that provider keyed
1145    let added = arrow.split([' ', ',']).skip_while(|w| *w != "setup").nth(1);
1146    let arrow = arrow.split_once(", then ").filter(|_| added.is_some()).map_or(arrow, |(_, a)| a);
1147    // The words after the binary that heads the arrow or a `· ` part of it (`check the certificate · fats u1 …`),
1148    // never after its name inside them, before its price
1149    let at = format!(" · {arrow}").split_once(&format!(" · {} ", bin())).map(|p| p.1.to_string()).unwrap_or_default();
1150    let cmd = crate::lang::parse(&[at.split(" ≤$").next().unwrap_or_default().to_string()]);
1151    // a command that can spend: a fetch or search past the cache (`account`, `setup`: free reads)
1152    // GitHub's search is free (a re-read once quoted ≤$0.0025, a web search's)
1153    let spends = ["fresh", "js", "provider", "timeout"].iter().any(|k| cmd.get(k).is_some());
1154    if !spends || !cmd.reserved.is_empty() || crate::cli::is_gh(&cmd) {
1155        return None;
1156    }
1157    let page = cmd.urls.first().map(String::as_str).or((!url.is_empty() || !cmd.ids.is_empty()).then_some(url));
1158    let mut p = Plan::of(&cmd, page);
1159    p.keys.extend(Tier::ALL.into_iter().filter(|t| added == Some(t.switch())));
1160    let s = crate::settings::get();
1161    route_of(&Cache::at(s.cache.value.clone(), s.session.value.clone()), page.unwrap_or_default(), &mut p);
1162    Some(route(&p))
1163}
1164
1165/// THE settle gate, every printed paid arrow (`fail_row`, `outline::js_next`, `outline::geo_flags`, `budget_row`):
1166/// false when the arrow's own dry (`worst`: its tiers, by name or ladder) plans a tier settled for `m`'s URL
1167/// (`settled`, for the country the arrow's request sends), the hops of the URL's `others` copies read too.
1168pub fn clear(arrow: &str, m: &Meta, others: &[Meta]) -> bool {
1169    let cuts: Vec<HopRow> = others.iter().flat_map(|o| o.hops.clone()).collect();
1170    let sett = settled(m, &cuts, crate::lang::parse(&[arrow.into()]).get("country"));
1171    worst(arrow, &m.url).is_none_or(|r| r.0.iter().all(|t| !sett.contains(&t.0.spec().name)))
1172}
1173
1174/// A failed record's count once another record of the same URL or query in this session (`others`) failed the
1175/// same way: ` · failed k/n here` (the same failures / the records). With a fix (`arg`) the same way = the same
1176/// move code and the same LAST tier, code and country (a lap ending where an earlier one ended, whatever
1177/// tiers ran before or time each call had), and the caller drops the arrow (it would send the call that failed
1178/// again: a bd outage = an endless $0 loop; consent.google's 400). With no fix (None) every copy failed with the
1179/// same move code counts, whatever path, said from the first (`failed 1/1 here` on a one-key error page, the row
1180/// with no arrow). A code is the move's (`move_code`: an older build's stored `no_copy` whose renders were both cut is
1181/// the timeout it was).
1182pub fn fail_count<'a>(m: &Meta, others: impl Iterator<Item = &'a Meta>, arg: Option<&str>) -> Option<String> {
1183    let same: Vec<&Meta> = others.filter(|s| s.url == m.url).collect();
1184    let last = |s: &Meta| s.hops.last().map(|h| [&h.provider, &h.code, &h.country].map(String::clone));
1185    let way = |s: &Meta| move_code(s) == move_code(m) && (arg.is_none() || last(s) == last(m));
1186    let k = 1 + same.iter().filter(|s| !s.ok && way(s)).count();
1187    (arg.is_none() || k > 1).then(|| format!(" · failed {k}/{} here", same.len() + 1))
1188}
1189
1190/// D1: THE failed copy's row parts, for `cli::no_doc` and `outline::page_flags`: why it failed (`fail_detail`, `page`
1191/// when no reason), its count (`fail_count`), its fix (`lang::fix`, None = a count or no fix), the accounts named.
1192/// No count when a newer copy `served` (its row points there, never "failed" beside the page).
1193pub fn fail_row(m: &Meta, others: &[Meta], page: &str, id: &str, served: bool) -> FailRow {
1194    let cuts: Vec<HopRow> = others.iter().flat_map(|o| o.hops.clone()).collect();
1195    let done = spent(m, &cuts, &keyed());
1196    let arg = fix_arg(m, &cuts);
1197    let at = At { id, url: &m.url, arg: arg.unwrap_or_default(), done: &done };
1198    // the settle gate (`clear`): an arrow that plans a settled tier names the keyed paid tier left whose dry plans
1199    // none (`left_ask`), else none: a count from the first copy (oxy-only: `failed 1/1`)
1200    let gate = |a: &str| clear(a, m, others);
1201    let (arg, arrow) = match arg.map(|_| fix(move_code(m), &at)) {
1202        Some(a) if !gate(&a) => left_ask(id, &m.url, &Tier::ALL, &done, gate).unzip(),
1203        arrow => (arg, arrow),
1204    };
1205    let again = fail_count(m, others.iter(), arg).filter(|_| !served);
1206    // a run the cap stopped: its `budget_hit` row (`skipped`) is the one move while it has one
1207    let budget = budget_row(m, id, others).is_some_and(|r| r.contains(" → "));
1208    // a repeat drops the arrow only when it changes nothing: the same call again (an empty `arg`); a tier never
1209    // asked (both keys: `provider:bd` after oxyjs cut twice) stays the move beside the count
1210    let arrow = arrow.filter(|_| !(again.is_some() && arg == Some("")) && !budget);
1211    // a key this run lacked could still serve it (its first key row): that row's move, then this page again, never
1212    // "nothing left" or none (`! off bd` → `fats setup bd on, then fats u1 fresh:true`)
1213    let none = arrow.as_ref().is_none_or(|a| a.starts_with("nothing left")) && !budget;
1214    let key = no_key_left(m).first().filter(|_| none).map(|r| restamp(r, id, &m.url));
1215    // that row's move, then this page from that provider by name (never the ladder again), priced with its key in
1216    // (`worst`): `→ fats setup bd on, then fats u4 fresh:true provider:bd ≤$0.0015`
1217    let to = |k: &String| {
1218        let p = Tier::ALL.into_iter().find(|t| k.split(' ').nth(2) == Some(t.switch()))?.spec().short;
1219        Some(priced(&format!("{}, then {} {id} fresh:true provider:{p}", k.split_once(" → ")?.1, bin()), &m.url))
1220    };
1221    let arrow = key.as_ref().map_or(arrow, to);
1222    let (why, owners) = fail_detail(m, page);
1223    (why, again.unwrap_or_default(), arrow, owners)
1224}
1225
1226/// `fail_row`: (why, ` · failed k/n here`, the fix, the accounts named).
1227pub type FailRow = (String, String, Option<String>, Vec<&'static str>);
1228
1229/// THE paid ask by name: the "keyed paid tier left" arrow (`lang::fix` after a render or a refusal, `fail_row`'s
1230/// settle gate; `tiers` = the table) and a `budget_hit` row's provider ask (`budget_row`): the first of `tiers` that
1231/// is paid and not `done` whose `fats <id> fresh:true <ask>` passes `ok`, priced (`lang::priced`), and its ask.
1232pub fn left_ask(id: &str, url: &str, tiers: &[Tier], done: &[&str], ok: impl Fn(&str) -> bool) -> Asked {
1233    let left = tiers.iter().copied().filter(|t| t.spec().price > 0.0 && !done.contains(&t.spec().short));
1234    let mut arrows = left.map(|t| (ASK[t as usize].as_str(), format!("{} {id} fresh:true {}", bin(), ASK[t as usize])));
1235    arrows.find(|a| ok(&a.1)).map(|(a, arrow)| (a, priced(&arrow, url)))
1236}
1237
1238/// `left_ask`'s answer: the ask (`provider:oxy`) and the whole priced arrow; None = no tier passes.
1239pub type Asked = Option<(&'static str, String)>;
1240
1241/// A tier asked by name (`provider:oxy js:true`: its owner, and `js:true` for an owner's render rung).
1242static ASK: LazyLock<Vec<String>> = LazyLock::new(|| {
1243    let ask = |t: Tier| format!("provider:{}{}", t.owner().spec().short, if t.renders() { " js:true" } else { "" });
1244    Tier::ALL.map(ask).to_vec()
1245});
1246
1247/// What a failed run's `!` row names: a refused key is named as `fats config` lists it (`oxy`, `bd`); a failure the
1248/// provider gave a reason token for (`Hop::why`) names the account and the token (`bd proxy_error`, `oxy retry in 5s`,
1249/// `bd cut at 40 s (3m ago)`); never the provider's answer itself. Any other failure names `page`. Also the accounts
1250/// the row names, for their dashboard pages (`provider::pages`). THE reason of every failed copy's row, with or without
1251/// a doc.
1252pub fn fail_detail(m: &Meta, page: &str) -> (String, Vec<&'static str>) {
1253    // the account a hop bills (`oxy` for oxyjs), a tier's or one of its own (`gh`: GitHub)
1254    let owner = |h: &HopRow| {
1255        let tier = Tier::parse(&h.provider).map(|t| t.owner().spec().short);
1256        tier.or(crate::provider::links(&h.provider).map(|l| l.short))
1257    };
1258    if m.code != "bad_key" {
1259        let code = move_code(m);
1260        let last = cut_of(m).or(m.hops.iter().rev().find(|h| h.code == code));
1261        // Our cut, stored as `took > 40 s here` (0.1.6 rows too), reads its time and age: `cut at 40 s (3m ago)`;
1262        // No age under a minute (the answer that made the cut said `(0s ago)`)
1263        let age = crate::cache::now() - m.t;
1264        let age = if age < 60.0 { String::new() } else { format!(" ({} ago)", fmt_age(age)) };
1265        let ours = |h: &HopRow| h.why.strip_prefix("took > ").map(|_| format!("cut at {} s{age}", h.timeout_s));
1266        let why = last.map(|h| ours(h).unwrap_or(h.why.clone()));
1267        // a certificate's refusal names its reason, never the http copy's: `certificate-verify-failed · $0`
1268        let tls = why.clone().filter(|_| code == "tls_failed").and_then(|w| Some(w.strip_prefix("tls:")?.to_owned()));
1269        // a call we cut or a provider's error names its tier (`oxyjs cut at 40 s`, `oxyjs 400 url: value not
1270        // supported`), a provider's other reason its account (`oxy retry in 5s`)
1271        let cut = last.and_then(|h| Tier::parse(&h.provider));
1272        let cut = cut.filter(|_| code == "provider_timeout" || OWN_REASON.contains(&code));
1273        return match (last.and_then(owner), why.filter(|w| !w.is_empty())) {
1274            _ if let Some(t) = tls => (format!("{} · $0", t.split('+').next().unwrap_or_default()), Vec::new()),
1275            (Some(o), Some(w)) => (format!("{} {w}", cut.map_or(o, |t| t.spec().short)), vec![o]),
1276            _ => (page.into(), Vec::new()),
1277        };
1278    }
1279    // the accounts whose hop ended with the run's code, in call order
1280    let keys = uniq(m.hops.iter().filter(|h| h.code == m.code).filter_map(owner), |k| *k);
1281    (keys.join(" "), keys)
1282}
1283
1284/// Every provider error answer of a run, one block each (`# oxylabs 500 provider_error`), for `error.txt`.
1285pub fn error_text(hops: &[Hop]) -> Option<Vec<u8>> {
1286    let block =
1287        |h: &Hop| [format!("# {} {} {}\n", h.tier.spec().name, h.status, h.code).as_bytes(), &h.err, b"\n"].concat();
1288    let out: Vec<u8> = hops.iter().filter(|h| !h.err.is_empty()).flat_map(block).collect();
1289    (!out.is_empty()).then_some(out)
1290}
1291
1292/// The chain's result as a snapshot: the winner (or the best failed copy), meta with every hop.
1293pub struct Outcome {
1294    pub meta: Meta,
1295    pub file: Option<(String, Vec<u8>)>,
1296    pub doc: Option<Doc>,
1297    /// `error_text` of the hops: stored as `error.txt` (0600), never printed.
1298    pub error: Option<Vec<u8>>,
1299}
1300
1301pub fn outcome(url: &str, hops: &mut [Hop], ms: u64) -> Outcome {
1302    // the first full answer, else the first thin one (`next` waited for the other provider)
1303    let win = hops.iter().position(|h| h.ok && !thin(h)).or(hops.iter().position(|h| h.ok));
1304    // no winner: the cut PDF with the most pages read, else the HTML answer with the most visible text
1305    let pages = |h: &Hop| h.doc.as_ref().map_or(0, |d| d.sections.len() - crate::pdf::empty_pages(d).len());
1306    let score = |h: &Hop| match h.kind {
1307        "pdf" if h.doc.is_some() => Some((1, pages(h))),
1308        "html" if !h.body.is_empty() => Some((0, h.vis)),
1309        _ => None,
1310    };
1311    let wall = hops.iter().rfind(|h| h.code.ends_with("_wall"));
1312    let best = win.or_else(|| hops.iter().enumerate().filter_map(|(i, h)| Some((score(h)?, i))).max().map(|x| x.1));
1313    // a failed run is named by its last answer; a cut PDF shown as the best copy by its own code (`pdf_truncated`)
1314    let code = match (win, best.filter(|&i| hops[i].kind == "pdf")) {
1315        (Some(_), _) => "ok".to_string(),
1316        (None, Some(i)) => hops[i].code.clone(),
1317        // An app page (`app_page`): no copy from two providers, not a fault a retry fixes
1318        _ if app_page(hops) => "no_copy".into(),
1319        // A wall any tier met says more than the last tier's timeout (oxy-only Joomla: `cloudflare_wall`, not
1320        // `provider_timeout`)
1321        _ => match (hops.iter().rev().find(|h| h.code != "abandoned"), wall) {
1322            // a `one_render` gate names the run only when its render met it too (a shell, the gate), never a
1323            // render cut or refused: that one keeps its own fix (the other keyed provider, else the run's end)
1324            (Some(l), Some(w)) if CHECK.one_render.contains(&w.code.as_str()) => {
1325                if l.code == "js_shell" { w } else { l }.code.clone()
1326            }
1327            (Some(l), Some(w)) if l.code == "provider_timeout" => w.code.clone(),
1328            (last, _) => last.map_or("no_key".into(), |h| h.code.clone()),
1329        },
1330    };
1331    let error = if win.is_some() { None } else { error_text(hops) };
1332    let cost = spend(hops.iter().map(|h| h.cost));
1333    let landed = best.and_then(|i| hops[i].landed.clone());
1334    let refreshed_from = best.and_then(|i| hops[i].refreshed_from.clone());
1335    let (tier, kind, final_url, body, doc, tree, charset) = match best {
1336        Some(i) => {
1337            let h = &mut hops[i];
1338            (h.tier, h.kind, h.final_url.clone(), std::mem::take(&mut h.body), h.doc.take(), h.tree.take(), h.charset)
1339        }
1340        None => (hops.last().map_or(Tier::Plain, |h| h.tier), "html", String::new(), Vec::new(), None, None, ""),
1341    };
1342    let render = tier.renders();
1343    let fin = if final_url.is_empty() { url } else { &final_url };
1344    // `judge` parsed every body once (a PDF into its doc); a failed HTML answer is cleaned here from that parse
1345    let doc = doc.or_else(|| tree.and_then(|t| guarded(|| Ok(clean::build_doc(&t, url, fin, render))).ok()));
1346    let meta = Meta {
1347        url: url.into(),
1348        final_url: (!final_url.is_empty() && final_url != url).then_some(final_url),
1349        landed,
1350        refreshed_from,
1351        provider: tier.spec().name.into(),
1352        ms: ms.saturating_sub(hops.iter().map(|h| h.waited).sum()),
1353        cost: (cost * 1e6).round() / 1e6,
1354        ok: win.is_some(),
1355        code,
1356        t: crate::cache::now(),
1357        bytes: body.len() as u64,
1358        kind: kind.into(),
1359        hops: hops.iter().map(Hop::row).collect(),
1360        render: Some(render),
1361        charset: charset.into(),
1362        headers: best.map(|i| hops[i].headers.clone()).unwrap_or_default(),
1363        ..Meta::default()
1364    };
1365    Outcome { meta, file: (!body.is_empty()).then(|| (raw_name(kind), body)), doc, error }
1366}
1367
1368// ---------------------------------------------------------------- content check
1369
1370/// The content check's tables (`src/data/check.json`). `rules` = the walls, tried in order before anything else
1371/// (`Wall`); `stop` = title words that say nothing about the page; `js_needed` = sentences asking for JavaScript
1372/// (they name the page, "enable javascript to see google maps", so they never count as the page showing its
1373/// title); `render_first` = plain's codes after which a provider's own no-JS fetch is skipped for its render
1374/// (`Plan::ladder`), `no_js_first` = the ones after which one no-JS try runs before the other provider's render,
1375/// `sign_in` = the words that make a moved landing a sign-in (`sign_in_gate`; whole words, a compound's last).
1376/// `one_render` = the ones after which ONE render runs (a sign-in gate answers every render alike, `outcome`).
1377#[derive(serde::Deserialize)]
1378#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
1379pub struct Check {
1380    pub rules: Vec<Wall>,
1381    stop: Vec<&'static str>,
1382    js_needed: Vec<&'static str>,
1383    render_first: Vec<&'static str>,
1384    no_js_first: Vec<&'static str>,
1385    one_render: Vec<&'static str>,
1386    sign_in: Vec<&'static str>,
1387}
1388
1389pub static CHECK: LazyLock<Check> = LazyLock::new(|| crate::settings::table("check"));
1390
1391/// A wall rule: a page whose `on` part holds any of `any` (a header line by its start, the rest anywhere), with
1392/// fewer than `under` visible chars when set, is `code` ("" = the HTTP status's own code, `status_code`). Bot-wall
1393/// vendors (DataDome & co.) tag every answer of a protected site: only a short page is their challenge (etsy: 14k
1394/// chars, ok); Cloudflare's `cf-mitigated: challenge` is one at any length. No row walls a copy that holds the page
1395/// (`check`: its own words shown).
1396#[derive(serde::Deserialize)]
1397#[serde(deny_unknown_fields)]
1398pub struct Wall {
1399    on: On,
1400    any: Vec<&'static str>,
1401    under: Option<usize>,
1402    pub code: &'static str,
1403}
1404
1405/// Where a wall rule looks: response header lines, the raw HTML (unescaped, folded), the visible text, or the HTTP
1406/// status (an error status, ≥ 400, is a wall of its own).
1407#[derive(serde::Deserialize, Clone, Copy)]
1408#[serde(rename_all = "lowercase")]
1409enum On {
1410    Header,
1411    Html,
1412    Text,
1413    Status,
1414}
1415
1416/// A page's language: its `<html lang>` primary tag when that is 2–3 ASCII letters, lower case (a 10 kB
1417/// `lang` reached every printed read); "" when it names none.
1418fn page_lang(tree: &Tree) -> String {
1419    let tag = tree.nodes.iter().find(|n| n.tag == "html").and_then(|n| n.attr("lang")?.split(['-', '_']).next());
1420    let tag = tag.map(str::trim).filter(|l| (2..=3).contains(&l.len()) && l.bytes().all(|b| b.is_ascii_alphabetic()));
1421    tag.unwrap_or_default().to_lowercase()
1422}
1423
1424/// Body check for one answer → a hop (ok, code, visible chars, doc when it passed). DETECT (`clean::kind_of`) runs
1425/// on every body, any tier. A PDF is read here: a body without its end that lost a page (`pdf::cut_short`) is
1426/// `pdf_truncated`, its doc kept as the best copy. A text document (`clean::Lists::text`) that the site sent with a
1427/// success status is served as it is, so the ladder stops: no content check, no provider. In a PDF run (`pdf`) an
1428/// answer without the PDF magic is `not_pdf` (plain's keeps its wall code when the check names one): the next
1429/// tier is tried.
1430pub fn judge(tier: Tier, raw: Raw, url: &str, js: bool, pdf: bool) -> Hop {
1431    let (kind, magic) = (clean::kind_of(&raw.ctype, &raw.body), clean::sniff(&raw.body));
1432    let mut h = Hop { tier, kind, status: raw.status, charset: raw.charset, why: raw.why.clone(), ..Hop::default() };
1433    h.final_url.clone_from(&raw.final_url);
1434    h.refreshed_from.clone_from(&raw.refreshed_from);
1435    let fin = if raw.final_url.is_empty() { url } else { &raw.final_url };
1436    if pdf && magic != Some("pdf") && (tier != Tier::Plain || clean::LISTS.text.contains(&kind)) {
1437        // the site's own error status (Bright Data's `x-brd-status-code`) says more than "not the file"
1438        h.code = if raw.status >= 400 { status_code(raw.status) } else { "not_pdf".into() };
1439    } else if kind != "html" && raw.status >= 400 {
1440        h.code = status_code(raw.status);
1441    } else if kind == "pdf" && magic.is_none() {
1442        h.code = "not_pdf".into(); // a content type that named a PDF over a body that is not one
1443    } else if kind == "pdf" {
1444        match guarded(|| crate::pdf::build_pdf(&raw.body, url, fin, limit("pdf_budget_s"))) {
1445            Ok(d) => {
1446                // only Oxylabs' copy is rebuilt from text (`provider::file_bytes`), so only its offsets can shift
1447                let oxy = matches!(tier, Tier::Oxy | Tier::OxyJs);
1448                let code = match () {
1449                    _ if crate::pdf::cut_short(&raw.body, &d) => "pdf_truncated",
1450                    _ if oxy && !crate::pdf::xref_ok(&raw.body) => "pdf_mangled",
1451                    _ => "ok",
1452                };
1453                (h.ok, h.code, h.doc) = (code == "ok", code.into(), Some(d));
1454            }
1455            Err(_) => h.code = "parse_failed".into(),
1456        }
1457    } else if kind != "html" {
1458        (h.ok, h.code) = (true, "ok".into());
1459        if kind != "zip" {
1460            h.doc = crate::cache::build(&raw.body, url, fin, js, kind).ok();
1461        }
1462        // a server's Markdown says how it may be used (`content-signal: ai-train=yes, …`): kept for `stats`
1463        let signal = raw.headers.lines().find_map(|l| l.strip_prefix("content-signal: "));
1464        if let (Some(d), Some(s)) = (h.doc.as_mut(), signal.filter(|_| kind == "md")) {
1465            d.info.insert("signal".into(), s.into());
1466        }
1467    } else {
1468        let text = String::from_utf8_lossy(&raw.body);
1469        let tree = crate::html::parse(&text);
1470        let (ok, code, vis, shown) = check(&tree, &text, &raw, url);
1471        // the site's own language only from a copy of the site (served, or a shell/thin page below 400), never a
1472        // wall's or a challenge's (a CF challenge says `en-US` on any site)
1473        h.lang = if ok || (raw.status < 400 && !code.ends_with("_wall")) { page_lang(&tree) } else { h.lang };
1474        (h.ok, h.code, h.vis) = (ok, code, vis);
1475        // https refused for its certificate (`provider::plain`'s `tls:` why) and an error page over http: the site
1476        // is there, its certificate is the answer, no paid tier is asked (`FINAL`); http's other answers: `plain`
1477        h.code = if h.code == "error_page" && raw.why.starts_with("tls:") { "tls_failed".into() } else { h.code };
1478        // a page served under an error status says so in its tier path (`oxyjs✓403`)
1479        h.why = if ok && raw.status >= 400 { raw.status.to_string() } else { h.why };
1480        // A provider is named, never plain (no provider: its error page is the page's own answer)
1481        h.why = if h.code == "error_page" && tier != Tier::Plain { "refused here (error page)".into() } else { h.why };
1482        // Bright Data names a redirect only sometimes (`x-unblocker-redirected-to`): without it, the page's own
1483        // same-site canonical link says where the ask landed (`outline::lost_page` judges it)
1484        h.landed = (tier == Tier::Bd && h.final_url == url).then(|| canonical(&tree, url)).flatten();
1485        if ok {
1486            match guarded(|| Ok(clean::build_doc(&tree, url, &h.final_url, js))) {
1487                // a page that cleans to fewer than `thin_chars` is a shell unless its title is visibly there
1488                // (example.com)
1489                Ok(d) if d.loss.pruned_chars < limit("thin_chars") && !shown => {
1490                    (h.ok, h.code, h.doc) = (false, "thin_content".into(), Some(d))
1491                }
1492                // a page that passes for one in a PDF run is not the file (a bot check titled as itself)
1493                Ok(d) if pdf => (h.ok, h.code, h.doc) = (false, "not_pdf".into(), Some(d)),
1494                Ok(d) => h.doc = Some(d),
1495                Err(_) => (h.ok, h.code) = (false, "parse_failed".into()),
1496            }
1497        } else {
1498            h.tree = Some(tree);
1499        }
1500    }
1501    h.headers = format!("HTTP {}\n{}", raw.status, raw.headers);
1502    h.body = raw.body;
1503    h
1504}
1505
1506fn status_code(s: u16) -> String {
1507    match s {
1508        404 | 410 => "not_found".into(),
1509        401 | 403 | 429 | 451 => format!("blocked_{s}"),
1510        _ => format!("http_{s}"),
1511    }
1512}
1513
1514/// A page's `<link rel=canonical>`, absolute, when it is on the same site as `url`.
1515fn canonical(t: &Tree, url: &str) -> Option<String> {
1516    let rel = |n: &&Node| n.attr("rel").is_some_and(|r| r.eq_ignore_ascii_case("canonical"));
1517    let href = t.nodes.iter().filter(|n| n.tag == "link").find(rel)?.attr("href")?;
1518    let c = url::Url::parse(url).ok()?.join(href).ok()?.to_string();
1519    (site(&c) == site(url)).then_some(c)
1520}
1521
1522/// Text a no-JS browser shows (everything but head, script, style, template and svg), the same without the text
1523/// nodes that ask for JavaScript, and whether one of those, outside the page's chrome (noscript, nav, header,
1524/// footer, aside), is a paragraph (`clean::paragraph`): a text of the page's own.
1525pub fn visible(t: &Tree) -> (String, String, bool) {
1526    let skip = ["head", "script", "style", "template", "svg", "noscript", "nav", "header", "footer", "aside"];
1527    let asks_js = |f: &String| CHECK.js_needed.iter().any(|m| f.contains(m));
1528    let all: Vec<String> = t.texts(0, &skip[..5]).map(clean::fold).collect();
1529    let body: Vec<&str> = all.iter().filter(|f| !asks_js(f)).map(String::as_str).collect();
1530    let own = t.texts(0, &skip).map(clean::fold).any(|f| clean::paragraph(&f) && !asks_js(&f));
1531    (clean::collapse(&all.join(" ")), clean::collapse(&body.join(" ")), own)
1532}
1533
1534/// A search page (a URL whose query names the search: `q=`, a key ending in `query`) is judged by its results, by
1535/// no engine's markup: distinct link targets whose text holds ≥ `link_words` words. None = no search page.
1536fn serp_results(url: &str, t: &Tree) -> Option<usize> {
1537    let u = url::Url::parse(url).ok()?;
1538    u.query_pairs().any(|(k, _)| k == "q" || k.ends_with("query")).then_some(())?;
1539    let links = t.nodes.iter().enumerate().filter_map(|(i, n)| {
1540        let href = n.attr("href").filter(|h| n.tag == "a" && !h.starts_with('#'))?;
1541        let words = t.texts(i, &[]).flat_map(str::split_whitespace).count();
1542        (words >= limit("link_words")).then_some(href)
1543    });
1544    Some(links.collect::<std::collections::HashSet<_>>().len())
1545}
1546
1547/// The page's own words in `s` (THE rule, with `outline::anchor`): its distinct folded words of ≥ 4
1548/// letters outside `CHECK.stop` (`access`, `denied`, `page`: a wall's or a 404's title says nothing of the page).
1549pub fn words_of(s: &str) -> Vec<String> {
1550    let f = clean::fold(s);
1551    let long = f.split(|c: char| !(clean::is_word(c) && !clean::is_digit(c) && c != '_'));
1552    uniq(long.filter(|w| w.chars().count() >= 4 && !CHECK.stop.contains(w)).map(String::from), String::clone)
1553}
1554
1555/// The page title up to its site suffix (`Title | Site`, `Title – Site`).
1556pub fn title_head(s: &str) -> &str {
1557    let cs: Vec<(usize, char)> = s.char_indices().collect();
1558    cs.windows(3).find(|w| py_space(w[0].1) && "|·–—-".contains(w[1].1) && py_space(w[2].1)).map_or(s, |w| &s[..w[0].0])
1559}
1560
1561/// A sign-in gate, judged before `redirected` whatever the id, on a landing that moved off the asked path: the
1562/// landing's path holds a segment that ends in a `Check::sign_in` word (`/login`, `/customer-login`,
1563/// `/users/sign_in`, `/signin.php`), or a query pair whose name ends in one hands the asked page back
1564/// (`?redirect_after_login=%2Fa%2Fall`: a path, or a URL on the asked site). Words are whole: every mark parts
1565/// them, and a compound is named by its last word, so `/login-free`, `/signing-guide`, `/authors` and
1566/// `/docs/authentication` name none. A 404 bounce `?from=`, a country chooser `?return=`, a consent `?continue=`
1567/// hand the page back too and are no sign-in: `redirected`, both renders.
1568fn sign_in_gate(asked: &str, landed: &str) -> bool {
1569    let (Ok(a), Ok(f)) = (url::Url::parse(asked), url::Url::parse(landed)) else { return false };
1570    let path = |u: &url::Url| u.path().trim_end_matches('/').to_owned();
1571    let words = |s: &str| {
1572        let s = s.rsplit_once('.').map_or(s, |(name, _)| name).to_lowercase();
1573        s.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_owned).collect::<Vec<_>>()
1574    };
1575    let named = |s: &str| CHECK.sign_in.iter().any(|w| words(s).ends_with(&words(w)));
1576    let back = |v: &str| f.join(v).is_ok_and(|v| site(v.as_str()) == site(asked) && path(&v) == path(&a));
1577    let gate =
1578        f.path_segments().is_some_and(|mut s| s.any(named)) || f.query_pairs().any(|(k, v)| named(&k) && back(&v));
1579    path(&f) != path(&a) && gate
1580}
1581
1582/// Is the main content there? Walls, consent and login pages by their markers, on a thin copy only (short, and no
1583/// title shown in a 2xx); with no expected words to look for, the title's distinct words stand in for them (missing
1584/// from the visible text = the body is a JS shell). A short page is real when its title is visibly there.
1585/// (ok, code, visible chars, title shown).
1586pub fn check(tree: &Tree, html: &str, raw: &Raw, url: &str) -> (bool, String, usize, bool) {
1587    let (vis, body, own) = visible(tree);
1588    let chars = vis.chars().count();
1589    let folded = std::cell::OnceCell::new();
1590    let title = tree.meta("og:title").map(str::to_string).unwrap_or_else(|| tree.title.clone());
1591    // the page's own words are shown when at least half (and 2 or more) are in the visible text: its title's, or
1592    // its URL's last path segment's (`/comments/x1/job_interview_tips`: a site-wide title says nothing)
1593    let seen = |w: &[String]| w.len() >= 2 && 2 * w.iter().filter(|w| body.contains(w.as_str())).count() >= w.len();
1594    let words = words_of(title_head(&title));
1595    // the last non-empty path segment (`/comments/x1/job_interview_tips` → `job_interview_tips`)
1596    let last = url::Url::parse(url).ok().and_then(|u| Some(u.path_segments()?.rfind(|s| !s.is_empty())?.to_string()));
1597    let slug = url::form_urlencoded::parse(last.unwrap_or_default().as_bytes()).next().map(|(s, _)| words_of(&s));
1598    let shown = seen(&words) || slug.is_some_and(|s| seen(&s));
1599    // a copy that holds the page is served whatever its status or the scripts it loads: its own words shown in a
1600    // 2xx, or in a 4xx/5xx body of `page_chars` or more (a wall = wall text AND no page words),
1601    // never a 404/410: a missing page echoes the URL's words (Wikipedia's, 2,034 chars outside its h1, vs
1602    // a 403 Q&A's 1,767: no length tells them apart); a served page is never a wall, wherever it landed
1603    let gone = matches!(raw.status, 404 | 410);
1604    let page = shown && !gone && (raw.status < 400 || chars >= limit("page_chars"));
1605    let hit = |w: &Wall| {
1606        let found = |s: &str| w.any.iter().any(|p| s.contains(p));
1607        !page
1608            && w.under.is_none_or(|n| chars < n)
1609            && match w.on {
1610                On::Header => raw.headers.lines().any(|l| w.any.iter().any(|p| l.starts_with(p))),
1611                On::Html => found(folded.get_or_init(|| clean::fold(&crate::html::unescape(html)))),
1612                On::Text => found(&vis),
1613                On::Status => raw.status >= 400,
1614            }
1615    };
1616    if let Some(w) = CHECK.rules.iter().find(|w| hit(w)) {
1617        let code = if w.code.is_empty() { status_code(raw.status) } else { w.code.into() };
1618        return (false, code, chars, false);
1619    }
1620    if !page && sign_in_gate(url, &raw.final_url) {
1621        return (false, "login_wall".into(), chars, false);
1622    }
1623    // no wall path named: the copy landed where the asked id is gone (`lost_page`), and shows none of its own
1624    // words: a front page, a search; never the page
1625    if !page && lost_page(url, &raw.final_url).is_some() {
1626        return (false, "redirected".into(), chars, false);
1627    }
1628    if let Some(n) = serp_results(url, tree) {
1629        let ok = n >= limit("serp_links");
1630        return (ok, if ok { "ok" } else { "serp_empty" }.into(), chars, false);
1631    }
1632    // a shell loads JavaScript: a short one with none (no `<script>`, no refresh) and none of its own words is the
1633    // site's own answer, an error page (Akamai's 534 B "Site Maintenance"; no phrase list). A copy that shows a
1634    // text of its own in `thin_chars` or more is the page, whatever its title (one word, a site's label): a shell
1635    // shows chrome, notices and short rows only
1636    if !shown && !(own && chars >= limit("thin_chars")) && (words.len() >= 2 || chars < 800) {
1637        let refresh = |n: &Node| n.attr("http-equiv").is_some_and(|v| v.eq_ignore_ascii_case("refresh"));
1638        let bare = chars < limit("page_chars") && !tree.nodes.iter().any(|n| n.tag == "script" || refresh(n));
1639        return (false, if bare { "error_page" } else { "js_shell" }.into(), chars, false);
1640    }
1641    // a short copy that shows little more than its own title is a state page, an error page too ("Post
1642    // isn't available • Instagram", 111 chars; no phrase: visible text under `title_ratio` × the title's chars)
1643    let state = chars < limit("page_chars") && chars < limit::<usize>("title_ratio") * title.trim().chars().count();
1644    (!state, if state { "error_page" } else { "ok" }.into(), chars, shown && !state)
1645}
1646
1647#[cfg(test)]
1648mod tests {
1649    use super::*;
1650
1651    /// The two providers the unit tests model (oxy, bd); a third key has its own (`a_third_provider_takes_its_rungs`)
1652    pub const KEYED: [Tier; 4] = [Tier::Plain, Tier::Bd, Tier::Oxy, Tier::OxyJs];
1653
1654    fn plan(mode: Mode) -> Plan {
1655        Plan { mode, cap: COST_CAP, keys: KEYED.to_vec(), hedge: HEDGE, ..Plan::default() }
1656    }
1657
1658    /// A search has no gate: Oxylabs runs alone for the hedge, then Bright Data starts beside it (or at once when
1659    /// Oxylabs failed); the first answer stops both. Search prices, search timeout, rows headed by no id.
1660    #[test]
1661    fn search_hedges_bright_data() {
1662        let p = Plan { keys: vec![Tier::Oxy, Tier::Bd], ..Plan::search(Mode::Auto, COST_CAP, None) };
1663        let s = Duration::from_secs;
1664        assert_eq!(next(&p, &[], &[]), Step::Start(Tier::Oxy));
1665        assert_eq!(next(&p, &[], &[(Tier::Oxy, s(1))]), Step::Wait(Duration::from_millis(1500)));
1666        assert_eq!(next(&p, &[], &[(Tier::Oxy, SEARCH_HEDGE)]), Step::Start(Tier::Bd));
1667        assert_eq!(next(&p, &[hop(Tier::Oxy, "provider_error")], &[]), Step::Start(Tier::Bd));
1668        assert_eq!(next(&p, &[hop(Tier::Oxy, "ok")], &[(Tier::Bd, s(1))]), Step::Stop);
1669        let late = [(Tier::Oxy, s(36)), (Tier::Bd, s(36))];
1670        assert_eq!(next(&p, &[], &late), Step::Stop, "detached: twice 15 s at once (`one_call`) + grace");
1671        assert_eq!(route(&p), (vec![(Tier::Oxy, None), (Tier::Bd, Some(SEARCH_HEDGE))], 0.0025));
1672        let poor =
1673            Plan { cap: 0.001, ..Plan { keys: vec![Tier::Oxy, Tier::Bd], ..Plan::search(Mode::Auto, 0.0, None) } };
1674        assert_eq!(route(&poor), (vec![(Tier::Oxy, None)], 0.001));
1675        let only = Plan { keys: vec![Tier::Oxy, Tier::Bd], ..Plan::search(Mode::Only(Tier::Bd), COST_CAP, None) };
1676        assert_eq!(route(&only).0, vec![(Tier::Bd, None)], "bd alone, detached: one call at twice the time");
1677        assert_eq!(only.timeout_of(Tier::Bd, &[]), s(30));
1678        // bd-only detached (no `wait:`) ran 15,004 + 14,999 ms: one call at 2×; an inline one under the 30 s
1679        // default `wait:` keeps its retry (S6: the default once made every inline search one call)
1680        let only_bd = || Plan { keys: vec![Tier::Oxy, Tier::Bd], ..Plan::search(Mode::Only(Tier::Bd), COST_CAP, None) };
1681        let (detached, inline) = (only_bd(), Plan { wait: Some(s(30)), ..only_bd() });
1682        assert_eq!((route(&detached).0, detached.timeout_of(Tier::Bd, &[])), (vec![(Tier::Bd, None)], s(30)));
1683        assert_eq!((route(&inline).0, inline.timeout_of(Tier::Bd, &[])), (vec![(Tier::Bd, None); 2], s(15)));
1684        let cut = Hop { ms: 30_000, ..hop(Tier::Bd, "provider_timeout") };
1685        assert_eq!(next(&detached, &[cut], &[]), Step::Stop, "one hop, never a retry");
1686        let waits = Plan { wait: Some(s(5)), ..only };
1687        assert_eq!(route(&waits).0, vec![(Tier::Bd, None), (Tier::Bd, None)], "inside wait: a retry");
1688        // bd-only `timeout:1` made 2 hops for one cut: the agent's cut is the answer, asked once
1689        let cut = Plan { timeout: Some(s(1)), ..waits };
1690        assert_eq!(next(&cut, &[hop(Tier::Bd, "provider_timeout")], &[]), Step::Stop, "no retry under the same cut");
1691        let nobd = Plan { keys: vec![Tier::Oxy], ..Plan::search(Mode::Auto, COST_CAP, None) };
1692        let bd = Plan { keys: vec![Tier::Bd], ..Plan::search(Mode::Auto, COST_CAP, None) };
1693        let wait = |p: &Plan, asked: u64| p.search_wait(s(asked)).as_secs();
1694        assert_eq!(
1695            [wait(&p, 5), wait(&nobd, 5), wait(&bd, 5), wait(&bd, 1), wait(&bd, 30)],
1696            [5, 5, 10, 10, 30],
1697            "the search patience"
1698        );
1699        let rows = skipped(&nobd, &[hop(Tier::Oxy, "provider_error")], "", "rust news", "");
1700        let bd = "! no_key bd · would try web search ≤$0.0015";
1701        assert!(
1702            rows.len() == 1 && rows[0].starts_with(bd),
1703            "a failed search names the key that could serve it: {rows:?}"
1704        );
1705        assert!(
1706            rows[0].ends_with(&format!(" → run {} setup bd, give the user its 3 lines", bin())),
1707            "its key form: {rows:?}"
1708        );
1709    }
1710
1711    fn hop(t: Tier, code: &str) -> Hop {
1712        let cost = t.spec().price;
1713        Hop { tier: t, ok: code == "ok", code: code.into(), kind: "html", cost, ..Hop::default() }
1714    }
1715
1716    const S: fn(u64) -> Duration = Duration::from_secs;
1717
1718    /// host class × tier × outcome → next tier.
1719    #[test]
1720    fn decision_table() {
1721        use Step::*;
1722        use Tier::*;
1723        let auto = plan(Mode::Auto);
1724        type Row<'a> = (&'a str, &'a Plan, Vec<Hop>, Vec<(Tier, Duration)>, Step);
1725        let rows: Vec<Row> = vec![
1726            ("start with plain", &auto, vec![], vec![], Start(Plain)),
1727            ("plain running: wait for its verdict", &auto, vec![], vec![(Plain, S(1))], Wait(S(14))),
1728            ("plain ok: done", &auto, vec![hop(Plain, "ok")], vec![], Stop),
1729            ("plain js shell → bd, never oxy no-JS", &auto, vec![hop(Plain, "js_shell")], vec![], Start(Bd)),
1730            ("plain 403 → bd", &auto, vec![hop(Plain, "blocked_403")], vec![], Start(Bd)),
1731            ("plain captcha → oxy no-JS first", &auto, vec![hop(Plain, "captcha_wall")], vec![], Start(Oxy)),
1732            ("oxy no-JS running: its verdict", &auto, vec![hop(Plain, "captcha_wall")], vec![(Oxy, S(1))], Wait(S(14))),
1733            ("oxy no-JS failed → bd", &auto, vec![hop(Plain, "captcha_wall"), hop(Oxy, "x")], vec![], Start(Bd)),
1734            ("plain timeout → bd", &auto, vec![hop(Plain, "provider_timeout")], vec![], Start(Bd)),
1735            ("plain 404: a provider will not fix it", &auto, vec![hop(Plain, "not_found")], vec![], Stop),
1736            (
1737                "plain and bd shells: one provider's shell is its failure, the other renders (airbnb)",
1738                &auto,
1739                vec![hop(Plain, "js_shell"), hop(Oxy, "js_shell"), hop(Bd, "js_shell")],
1740                vec![],
1741                Start(OxyJs),
1742            ),
1743            (
1744                "plain and bd shells: the render beside them runs on",
1745                &auto,
1746                vec![hop(Plain, "js_shell"), hop(Oxy, "js_shell"), hop(Bd, "js_shell")],
1747                vec![(OxyJs, S(1))],
1748                Wait(S(44)),
1749            ),
1750            (
1751                "bd wall → oxyjs",
1752                &auto,
1753                vec![hop(Plain, "js_shell"), hop(Oxy, "x"), hop(Bd, "captcha_wall")],
1754                vec![],
1755                Start(OxyJs),
1756            ),
1757            ("bd just started: oxyjs waits the hedge", &auto, both(), vec![(Bd, S(0))], Wait(S(5))),
1758            ("bd 2 s in: 3 s left", &auto, both(), vec![(Bd, S(2))], Wait(S(3))),
1759            ("bd 5 s in: oxyjs starts beside it", &auto, both(), vec![(Bd, S(5))], Start(OxyJs)),
1760            ("bd failed fast → oxyjs now", &auto, and(vec![hop(Bd, "captcha_wall")]), vec![], Start(OxyJs)),
1761            ("both running: wait", &auto, both(), vec![(Bd, S(6)), (OxyJs, S(1))], Wait(S(39) + S(5))),
1762            ("oxyjs won: stop", &auto, and(vec![hop(OxyJs, "ok")]), vec![(Bd, S(9))], Stop),
1763            ("all failed: stop", &auto, and(vec![hop(Bd, "x"), hop(OxyJs, "x")]), vec![], Stop),
1764            ("stuck past timeout+grace: stop", &auto, both(), vec![(Bd, S(66))], Stop),
1765            (
1766                "shell + bd timeout: one provider failed, the other renders",
1767                &auto,
1768                vec![hop(Plain, "js_shell"), hop(Oxy, "js_shell"), hop(Bd, "provider_timeout")],
1769                vec![],
1770                Start(OxyJs),
1771            ),
1772        ];
1773        for (what, p, done, running, want) in rows {
1774            assert_eq!(next(p, &done, &running), want, "{what}");
1775        }
1776    }
1777
1778    /// The decision table's named cases: gov hosts, zip documents, `js:true`, missing keys, `provider:`, refused
1779    /// keys, the cost cap, `hedge:0`, `timeout:`.
1780    #[test]
1781    fn decision_cases() {
1782        use Step::*;
1783        use Tier::*;
1784        let auto = plan(Mode::Auto);
1785        let gov = Plan { gov: true, ..plan(Mode::Auto) };
1786        assert_eq!(gov.ladder(&[]), [Plain, Oxy, OxyJs, DecodoJs], "gov skips bd: no other render, oxy no-JS runs");
1787        let zip = Plan { doc: Some("zip"), ..plan(Mode::Auto) };
1788        assert_eq!(next(&zip, &[hop(Tier::Plain, "blocked_403")], &[]), Stop, "zip documents: plain only");
1789        assert!(skipped(&zip, &[hop(Tier::Plain, "blocked_403")], "u1", "u1", "").is_empty());
1790        let js = Plan { js: true, ..plan(Mode::Auto) };
1791        assert_eq!(js.ladder(&[]), [Bd, OxyJs, DecodoJs], "js:true skips plain and the no-JS rungs");
1792        assert_eq!(next(&js, &[], &[]), Start(Bd));
1793        // A paid ask runs ONE provider; the next starts only on its failure, never beside it (hedge:off)
1794        assert_eq!(next(&js, &[], &[(Bd, S(30))]), Wait(S(15)), "no oxyjs beside a slow bd");
1795        assert_eq!(next(&js, &[hop(Bd, "js_shell")], &[]), Start(OxyJs), "it failed: oxyjs");
1796        assert_eq!(next(&js, &[hop(Bd, "not_found")], &[]), Stop);
1797        assert_eq!((route(&js), js.hedged(), auto.hedged()), ((vec![(Bd, None), (OxyJs, None)], 0.003), false, true));
1798        assert!(!plan(Mode::Only(Bd)).hedged(), "a named tier is a paid ask too");
1799        assert!(plan(Mode::Only(Plain)).hedged(), "provider:plain is free: no hedge:off");
1800        let nobd = Plan { keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) };
1801        // one key: that provider's every rung, oxy no-JS gating the render (measured: a news page in 1.9 s)
1802        assert_eq!(next(&nobd, &both(), &[]), Start(Oxy), "no bd key → oxy no-JS");
1803        assert_eq!(next(&nobd, &[hop(Plain, "blocked_403"), hop(Oxy, "captcha_wall")], &[]), Start(OxyJs));
1804        let nooxy = Plan { keys: vec![Plain, Bd], ..plan(Mode::Auto) };
1805        assert_eq!(next(&nooxy, &[hop(Plain, "js_shell")], &[]), Start(Bd), "no oxy key → bd, gated by plain");
1806        let only = plan(Mode::Only(Plain));
1807        assert_eq!(next(&only, &[hop(Plain, "js_shell")], &[]), Stop, "provider:plain never escalates");
1808        let oxy = plan(Mode::Only(Oxy));
1809        assert_eq!(oxy.ladder(&[]), [Oxy, OxyJs], "provider:oxy keeps both oxy tiers");
1810        assert_eq!(next(&oxy, &[hop(Oxy, "provider_error")], &[]), Start(OxyJs));
1811        // a refused or rate-limited key is never sent again by a tier that shares it; a tier with its own key runs
1812        for code in KEY_CODES {
1813            assert_eq!(next(&oxy, &[hop(Oxy, code)], &[]), Stop, "provider:oxy {code}: no oxyjs");
1814            assert!(skipped(&oxy, &[hop(Oxy, code)], "u1", "u1", "").is_empty(), "{code}: no budget row for oxyjs");
1815            let refused_oxy = vec![hop(Plain, "js_shell"), hop(Oxy, code)];
1816            assert_eq!(next(&auto, &refused_oxy, &[]), Start(Bd), "oxy {code} → bd");
1817            assert_eq!(next(&auto, &refused_oxy, &[(Bd, S(9))]), Wait(S(36)), "{code}: bd alone, no oxyjs beside it");
1818            let mut all = refused_oxy;
1819            all.push(hop(Bd, "captcha_wall"));
1820            assert_eq!(next(&auto, &all, &[]), Stop, "{code}: bd failed, oxyjs still not tried");
1821            let search = Plan { keys: vec![Oxy, Bd], ..Plan::search(Mode::Auto, COST_CAP, None) };
1822            assert_eq!(next(&search, &[hop(Oxy, code)], &[]), Start(Bd), "search {code}: bd has its own key");
1823            assert_eq!(next(&search, &[hop(Oxy, code), hop(Bd, code)], &[]), Stop);
1824        }
1825        assert_eq!(Plan { js: true, ..plan(Mode::Only(Oxy)) }.ladder(&[]), [OxyJs]);
1826        let poor = Plan { cap: 0.002, ..plan(Mode::Auto) };
1827        assert_eq!(next(&poor, &both(), &[(Bd, S(6))]), Wait(S(39)), "no budget for oxyjs too");
1828        assert_eq!(next(&poor, &both(), &[(Bd, S(1))]), Wait(S(44)), "no hedge wake without budget");
1829        let race = Plan { hedge: S(0), ..plan(Mode::Auto) };
1830        assert_eq!(next(&race, &both(), &[(Bd, S(0))]), Start(OxyJs), "hedge:0 = both at once");
1831        let slow = Plan { timeout: Some(S(180)), ..plan(Mode::Auto) };
1832        assert_eq!(next(&slow, &[], &[(Plain, S(1))]), Wait(S(14)), "timeout: leaves plain at 10 s");
1833        let named = Plan { timeout: Some(S(180)), ..plan(Mode::Only(Oxy)) };
1834        assert_eq!(next(&named, &[], &[(Oxy, S(3))]), Wait(S(22)), "and named oxy no-JS at its 20 s");
1835        let late = [(Bd, S(66)), (OxyJs, S(61))];
1836        assert_eq!(next(&slow, &both(), &late), Wait(S(124)), "bd and oxyjs get the 180 s");
1837        let zero = Plan { cap: 0.0, ..plan(Mode::Auto) };
1838        assert_eq!(next(&zero, &[hop(Plain, "js_shell")], &[]), Stop, "cost:0 = plain only");
1839        // a final answer ends the run with a call in flight; a provider's refusal (bd 502) does not
1840        for code in ["not_found", "too_big", "no_host", "private_address"] {
1841            assert_eq!(next(&auto, &[hop(Bd, code)], &[(OxyJs, S(70))]), Stop, "{code}");
1842        }
1843        assert_eq!(next(&auto, &[hop(Plain, "no_host")], &[]), Stop, "no tier after a dead host");
1844        assert_ne!(next(&auto, &[hop(Bd, "provider_refused")], &[(OxyJs, S(9))]), Stop, "bd 502 is not final");
1845    }
1846
1847    /// Three keys (decodo beside oxy and bd): its no-JS rung after oxy's behind plain's captcha, never after a shell;
1848    /// its render joins bd ∥ oxyjs one hedge after the last start; `js:true` = every render, one at a time.
1849    #[test]
1850    fn a_third_provider_takes_its_rungs() {
1851        use Step::*;
1852        use Tier::*;
1853        let three = Plan { keys: Tier::ALL.to_vec(), ..plan(Mode::Auto) };
1854        assert_eq!(next(&three, &[hop(Plain, "captcha_wall")], &[]), Start(Oxy));
1855        assert_eq!(next(&three, &[hop(Plain, "captcha_wall"), hop(Oxy, "x")], &[]), Start(Decodo));
1856        let slow = [hop(Plain, "captcha_wall"), hop(Oxy, "provider_timeout")];
1857        assert_eq!(next(&three, &slow, &[]), Start(Bd), "a no-JS tier cut: the renders, never decodo's no-JS");
1858        let shell = [hop(Plain, "js_shell")];
1859        assert_eq!(next(&three, &shell, &[]), Start(Bd), "a shell skips both no-JS rungs");
1860        assert_eq!(next(&three, &shell, &[(Bd, S(5))]), Start(OxyJs));
1861        assert_eq!(next(&three, &shell, &[(Bd, S(6)), (OxyJs, S(1))]), Wait(S(4)), "a hedge after the last start");
1862        assert_eq!(next(&three, &shell, &[(Bd, S(10)), (OxyJs, S(5))]), Start(DecodoJs));
1863        let failed = [hop(Plain, "js_shell"), hop(Bd, "x"), hop(OxyJs, "x"), hop(DecodoJs, "x")];
1864        assert_eq!(next(&three, &failed, &[]), Stop);
1865        let js = Plan { js: true, keys: Tier::ALL.to_vec(), ..plan(Mode::Auto) };
1866        assert_eq!(route(&js).0, [(Bd, None), (OxyJs, None), (DecodoJs, None)], "one at a time, table order");
1867        let decodo = Plan { keys: vec![Plain, Decodo, DecodoJs], ..plan(Mode::Only(Decodo)) };
1868        assert_eq!(decodo.ladder(&[]), [Decodo, DecodoJs], "provider:decodo keeps both decodo tiers");
1869    }
1870
1871    /// Behind Bright Data with no redirect header, a same-site canonical link is where the ask landed.
1872    #[test]
1873    fn canonical_names_a_bd_landing() {
1874        let page = |canon: &str| {
1875            let html = format!(
1876                "<html><head><title>Base Set</title><link rel=canonical href=\"{canon}\"></head><body><h1>Base Set</h1>\
1877                 <p>{}</p><a href=\"2\">Next page</a></body></html>",
1878                "Singles from the Base Set, in stock today. ".repeat(20)
1879            );
1880            Raw {
1881                status: 200,
1882                body: html.into_bytes(),
1883                ctype: "text/html".into(),
1884                final_url: "https://a.example/i/9-x".into(),
1885                ..Raw::default()
1886            }
1887        };
1888        let fin = |t: Tier, canon: &str| judge(t, page(canon), "https://a.example/i/9-x", false, false).landed;
1889        assert_eq!(fin(Tier::Bd, "/singles").as_deref(), Some("https://a.example/singles"));
1890        assert_eq!(fin(Tier::Bd, "https://other.org/x"), None, "another site's canonical: syndication");
1891        assert_eq!(fin(Tier::Plain, "/singles"), None, "plain follows the redirects itself");
1892        // The landing is the redirect judgement only; links resolve against where the bytes came from
1893        let h = judge(Tier::Bd, page("/singles"), "https://a.example/i/9-x", false, false);
1894        let doc = h.doc.expect("a page");
1895        assert_eq!(
1896            (doc.final_url.as_str(), doc.links.first().map(String::as_str)),
1897            ("https://a.example/i/9-x", Some("https://a.example/i/2"))
1898        );
1899    }
1900
1901    /// Per key set: a run that fails at every rung leaves no keyed rung untried, and its fix
1902    /// never sends a provider without a key, nor `js:true` when no keyed render is left.
1903    #[test]
1904    fn every_keyed_rung_runs_and_no_hint_names_a_missing_key() {
1905        use Tier::*;
1906        for keys in [vec![Plain, Oxy, OxyJs], vec![Plain, Bd], Tier::ALL.to_vec()] {
1907            let p = Plan { keys: keys.clone(), ..plan(Mode::Auto) };
1908            for code in ["captcha_wall", "js_shell", "provider_timeout", "provider_error", "blocked_403", "login_wall"]
1909            {
1910                let mut hops = Vec::new();
1911                while let Step::Start(t) = next(&p, &hops, &[]) {
1912                    hops.push(hop(t, code));
1913                }
1914                let untried = |t: &Tier| keys.contains(t) && !hops.iter().any(|h| h.tier == *t);
1915                let left: Vec<Tier> = p.ladder(&hops).into_iter().filter(untried).collect();
1916                assert!(left.is_empty(), "{keys:?} {code}: {left:?} never ran");
1917                let render = Tier::ALL.into_iter().any(|t| t.can("js") && untried(&t));
1918                let m = outcome("https://a.example/", &mut hops, 1).meta;
1919                let done = spent(&m, &[], &keys);
1920                let fix = crate::lang::fix(
1921                    &m.code,
1922                    &crate::lang::At { id: "u1", url: &m.url, arg: fix_arg(&m, &[]).unwrap_or_default(), done: &done },
1923                );
1924                assert!(!fix.contains("provider:oxy") || keys.contains(&Oxy), "{keys:?} {code}: {fix}");
1925                assert!(!fix.contains("provider:bd") || keys.contains(&Bd), "{keys:?} {code}: {fix}");
1926                assert!(!fix.contains("js:true") || render, "{keys:?} {code}: {fix}");
1927            }
1928        }
1929    }
1930
1931    /// A thin first answer waits for the other provider's running call, and a full answer wins.
1932    #[test]
1933    fn thin_answer_waits_for_the_other_provider() {
1934        use Step::*;
1935        use Tier::*;
1936        let auto = plan(Mode::Auto);
1937        let loss = || clean::Loss { visible_chars: 9_000, ..clean::Loss::default() };
1938        let thin = || Hop { doc: Some(Doc { loss: loss(), ..Doc::default() }), ..hop(Bd, "ok") };
1939        assert!(crate::outline::is_thin(thin().doc.as_ref().expect("doc")), "the fixture is thin");
1940        let done = vec![hop(Plain, "js_shell"), thin()];
1941        assert_eq!(next(&auto, &done, &[(OxyJs, S(1))]), Wait(S(5)), "oxyjs running: wait the hedge window for it");
1942        // The window runs from the thin answer's landing, never to the other call's timeout
1943        let landed = |ago| vec![hop(Plain, "js_shell"), Hop { end: Instant::now().checked_sub(S(ago)), ..thin() }];
1944        assert_eq!(next(&auto, &landed(6), &[(OxyJs, S(3))]), Stop, "the window is over: the thin copy is served");
1945        assert!(matches!(next(&auto, &landed(2), &[(OxyJs, S(3))]), Wait(d) if d <= S(3)), "3 s of the window left");
1946        assert_eq!(next(&auto, &done, &[]), Stop, "nothing running: the thin answer is served");
1947        let full = vec![hop(Plain, "js_shell"), hop(Bd, "ok")];
1948        assert_eq!(next(&auto, &full, &[(OxyJs, S(1))]), Stop, "a full answer stops the ladder");
1949        let mut both: Vec<Hop> = done.into_iter().chain([hop(OxyJs, "ok")]).collect();
1950        assert_eq!(next(&auto, &both, &[]), Stop);
1951        assert_eq!(
1952            outcome("https://a.example/", &mut both, 1).meta.provider,
1953            "oxylabs-js",
1954            "the full answer is served"
1955        );
1956    }
1957
1958    /// A render cut at its own 40 s ends the run, whatever the keys: 8/131 served renders took 40-60 s, a second
1959    /// one at twice the time and price is the silent 60-100 s block; `dry:true` prices the one call. A network
1960    /// error still gets its retry where one provider is left.
1961    #[test]
1962    fn a_render_cut_is_never_retried() {
1963        use Step::*;
1964        use Tier::*;
1965        let nooxy = Plan { keys: vec![Plain, Bd], ..plan(Mode::Auto) };
1966        let bd = |code: &str| vec![hop(Plain, "blocked_403"), hop(Bd, code)];
1967        assert_eq!(next(&nooxy, &bd("provider_timeout"), &[]), Stop, "bd cut: the run ends");
1968        assert_eq!(route(&nooxy), (vec![(Plain, None), (Bd, None)], 0.0015), "dry: no bd → bd retry");
1969        let oxy = Plan { keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) };
1970        assert_eq!(next(&oxy, &[hop(Plain, "js_shell"), hop(OxyJs, "provider_timeout")], &[]), Stop, "oxyjs cut");
1971        // one provider on the LADDER, both keys present
1972        let gov = Plan { gov: true, ..plan(Mode::Auto) };
1973        let js = |code: &str| vec![hop(Plain, "js_shell"), hop(Oxy, "js_shell"), hop(OxyJs, code)];
1974        assert_eq!(next(&gov, &js("net_error"), &[]), Start(OxyJs), "a gov host: Oxylabs alone, once more");
1975        assert_eq!(next(&gov, &js("provider_timeout"), &[]), Stop, "but never a render after its cut");
1976        assert_eq!(next(&plan(Mode::Only(Bd)), &bd("net_error"), &[]), Start(Bd), "provider:bd: once more");
1977        assert_eq!(next(&plan(Mode::Only(Bd)), &bd("provider_timeout"), &[]), Stop, "provider:bd cut: the end");
1978    }
1979
1980    /// One paid key: ONE retry on a network error or a no-JS tier's timeout, never on a wall or a shell.
1981    #[test]
1982    fn one_key_retries_once() {
1983        use Step::*;
1984        use Tier::*;
1985        let (auto, nooxy) = (plan(Mode::Auto), Plan { keys: vec![Plain, Bd], ..plan(Mode::Auto) });
1986        let bd = |code: &str| vec![hop(Plain, "blocked_403"), hop(Bd, code)];
1987        assert_eq!(next(&nooxy, &bd("net_error"), &[]), Start(Bd), "a network error: once more");
1988        // the no-JS retry stays: an Oxylabs-only PDF, oxy cut at its 30 s, gets twice the time under the wall
1989        let pdf = Plan { doc: Some("pdf"), keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) };
1990        let ran = |gone: u64| {
1991            let now = Instant::now();
1992            let plain = Hop { end: now.checked_sub(S(gone - 10)), ms: 10_000, ..hop(Plain, "blocked_403") };
1993            vec![plain, Hop { end: Some(now), ms: (gone - 10) * 1000, ..hop(Oxy, "provider_timeout") }]
1994        };
1995        assert_eq!(pdf.timeout_of(Oxy, &[hop(Oxy, "provider_timeout")]), S(60), "with twice the time");
1996        // plain 10 s + oxy 30 s: 50 s of the 90 s one-key wall left ≥ the 30 s oxy had: the retry gets the 50 s
1997        assert_eq!((next(&pdf, &ran(40), &[]), pdf.timeout_of(Oxy, &ran(40))), (Start(Oxy), S(50)));
1998        // plain 10 s + oxy 60 s: 20 s of the wall left < the 60 s oxy had: no retry (a shorter retry serves
1999        // nothing: one key on 20 hard pages, 5 retries after a 60 s cut got 23.9-30 s under the wall and served 0)
2000        assert_eq!(next(&pdf, &ran(70), &[]), Stop, "20 s left < the 60 s oxy had: the run ends here");
2001        let capped = Plan { timeout: Some(S(30)), keys: vec![Plain, Bd], ..plan(Mode::Auto) };
2002        assert_eq!(capped.timeout_of(Bd, &bd("provider_timeout")).as_secs(), 30, "timeout:30 stays 30");
2003        // `timeout:` is a hard budget, no retry under it: bd-only `timeout:60` = plain 10 s
2004        // + bd 60 s, then the end (was a 60 s retry: ~130 s, past the 90 s wall)
2005        let sixty = Plan { timeout: Some(S(60)), keys: vec![Plain, Bd], ..plan(Mode::Auto) };
2006        assert_eq!(sixty.timeout_of(Bd, &[hop(Plain, "blocked_403")]), S(60));
2007        // plain keeps its 10 s under a longer `timeout:` and gets the agent's time under a shorter one (`timeout:2`
2008        // on a 12 s page ran 12 s)
2009        let two = Plan { timeout: Some(S(2)), keys: vec![Plain, Bd], ..plan(Mode::Auto) };
2010        assert_eq!((sixty.timeout_of(Plain, &[]), two.timeout_of(Plain, &[])), (S(10), S(2)));
2011        assert_eq!(next(&sixty, &bd("provider_timeout"), &[]), Stop, "timeout: set: no retry");
2012        let pdf60 = Plan {
2013            timeout: Some(S(60)),
2014            ..Plan { doc: Some("pdf"), keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) }
2015        };
2016        assert_eq!(next(&pdf60, &ran(30), &[]), Stop, "not even with the wall far off");
2017        // an oxy-only Joomla site: plain's JS challenge skips oxy no-JS (0/33 after a JS
2018        // challenge or shell), plain's 403 or captcha keeps it (11/26)
2019        let oxy = Plan { keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) };
2020        for (wall, first) in [("cloudflare_wall", OxyJs), ("js_shell", OxyJs), ("serp_empty", OxyJs)] {
2021            assert_eq!(next(&oxy, &[hop(Plain, wall)], &[]), Start(first), "{wall}");
2022        }
2023        for wall in ["blocked_403", "captcha_wall"] {
2024            assert_eq!(next(&oxy, &[hop(Plain, wall)], &[]), Start(Oxy), "{wall}");
2025        }
2026        // a provider's own refusal served 0/7 on a retry, our cut 3/9 (a refusal is final)
2027        assert_eq!(next(&nooxy, &bd("provider_error"), &[]), Stop, "bd 5xx: its answer");
2028        assert_eq!(next(&nooxy, &bd("captcha_wall"), &[]), Stop, "a wall: never again");
2029        assert_eq!(next(&nooxy, &bd("js_shell"), &[]), Stop, "a shell: never again");
2030        // the site's own 5xx is its answer: a bd-only listings site bought
2031        // `brightdata http_502` twice for the same failure; a wall served as 503 is a wall
2032        for (code, status) in [("http_502", 502), ("http_500", 500), ("cloudflare_wall", 503)] {
2033            let site = vec![hop(Plain, "captcha_wall"), Hop { status, ..hop(Bd, code) }];
2034            assert_eq!(next(&nooxy, &site, &[]), Stop, "{code} {status}: the site answered");
2035        }
2036        let twice: Vec<Hop> = bd("net_error").into_iter().chain([hop(Bd, "net_error")]).collect();
2037        assert_eq!(next(&nooxy, &twice, &[]), Stop, "one retry only");
2038        let tight = Plan { cap: 0.002, ..Plan { keys: vec![Plain, Bd], ..plan(Mode::Auto) } };
2039        assert_eq!(next(&tight, &bd("net_error"), &[]), Stop, "the retry is inside cost:");
2040        let both_failed: Vec<Hop> =
2041            bd("provider_timeout").into_iter().chain([hop(OxyJs, "provider_timeout")]).collect();
2042        assert_eq!(next(&auto, &both_failed, &[]), Stop, "two keys: the other provider was the retry");
2043        // Bd refused the URL (`europa.eu`, no gov label): Oxylabs is the one provider left, its failure gets the retry
2044        let refused = vec![hop(Plain, "js_shell"), hop(Oxy, "x"), hop(Bd, "provider_refused"), hop(OxyJs, "net_error")];
2045        assert_eq!(next(&auto, &refused, &[]), Start(OxyJs), "a refused owner covers no failure");
2046        let no_key = vec![hop(Plain, "js_shell"), hop(Oxy, "x"), hop(Bd, "bad_key"), hop(OxyJs, "net_error")];
2047        assert_eq!(next(&auto, &no_key, &[]), Start(OxyJs), "nor does a refused key");
2048    }
2049
2050    /// A PDF run: plain → oxy no-JS (given the slow timeout) → bd, each waiting for the last one's verdict, never
2051    /// oxyjs; the URL's suffix says so, or an answer does (magic, content type); a missing file stays missing. A
2052    /// `/pdf/` path (`/doi/pdf/…` holds it) is only a hint: the page ladder, with oxy's file timeout.
2053    #[test]
2054    fn pdf_ladder() {
2055        use Step::*;
2056        use Tier::*;
2057        let doc = |u: &str| {
2058            let p = Plan::new(u, Mode::Auto, false, COST_CAP, None);
2059            (p.doc, p.hint)
2060        };
2061        assert_eq!(doc("https://arxiv.org/pdf/2405.15793"), (None, true), "a /pdf/ segment: a hint");
2062        assert_eq!(doc("https://dl.acm.org/doi/pdf/10.1145/3290605.3300233"), (None, true));
2063        assert_eq!(doc("https://x.org/docs/pdf/merge.html"), (None, false), "a page under /pdf/");
2064        assert_eq!(doc("https://x.org/pdf/a.pdf"), (Some("pdf"), false));
2065        assert_eq!(doc("https://x.org/A.PDF?dl=1"), (Some("pdf"), false));
2066        assert_eq!(doc("https://static.zara.net/static/pdfs/ES/a.html"), (None, false), "`pdfs` is not `pdf`");
2067        assert_eq!(doc("https://x.org/report.docx"), (Some("zip"), false));
2068        let hint = Plan::new("https://arxiv.org/pdf/2405.15793", Mode::Auto, false, COST_CAP, None);
2069        assert_eq!(hint.ladder(&[]), [Plain, Oxy, Decodo, Bd, OxyJs, DecodoJs], "the page ladder");
2070        assert_eq!(next(&hint, &[hop(Plain, "js_shell")], &[(Oxy, S(9))]), Wait(S(26)), "oxy has 30 s");
2071        let pdf = Plan { doc: Some("pdf"), ..plan(Mode::Auto) };
2072        let p403 = || hop(Plain, "blocked_403");
2073        assert_eq!(route(&pdf), (vec![(Plain, None), (Oxy, None), (Bd, None)], 0.0025));
2074        assert_eq!(next(&pdf, &[p403()], &[]), Start(Oxy));
2075        assert_eq!(next(&pdf, &[p403()], &[(Oxy, S(9))]), Wait(S(26)), "oxy has 30 s for a file");
2076        assert_eq!(next(&pdf, &[p403(), hop(Oxy, "not_pdf")], &[]), Start(Bd));
2077        assert_eq!(next(&pdf, &[p403(), hop(Oxy, "not_pdf")], &[(Bd, S(9))]), Wait(S(36)), "no oxyjs beside bd");
2078        assert_eq!(next(&pdf, &[p403(), hop(Oxy, "x"), hop(Bd, "pdf_truncated")], &[]), Stop);
2079        assert_eq!(next(&pdf, &[hop(Plain, "not_found")], &[]), Stop);
2080        assert_eq!(Plan { js: true, ..Plan { doc: Some("pdf"), ..plan(Mode::Auto) } }.ladder(&[]), [Plain, Oxy, Bd]);
2081        assert_eq!(Plan { gov: true, ..Plan { doc: Some("pdf"), ..plan(Mode::Auto) } }.ladder(&[]), [Plain, Oxy]);
2082        assert_eq!(Plan { doc: Some("pdf"), ..plan(Mode::Only(Oxy)) }.ladder(&[]), [Oxy]);
2083        // no `.pdf` in the URL: plain's failed answer says PDF (content type), so the run becomes one
2084        let page = plan(Mode::Auto);
2085        let said = Hop { kind: "pdf", ..p403() };
2086        assert_eq!(next(&page, &[said], &[]), Start(Oxy));
2087        let said = || Hop { kind: "pdf", ..p403() };
2088        assert_eq!(next(&page, &[said(), hop(Oxy, "provider_error"), hop(Bd, "x")], &[]), Stop, "no oxyjs");
2089        let rows =
2090            skipped(&Plan { keys: vec![Plain, Oxy], ..plan(Mode::Auto) }, &[said(), hop(Oxy, "x")], "u1", "u1", "");
2091        assert!(rows.len() == 1 && rows[0].starts_with("u1 ! no_key bd · "), "bd's PDF bytes, no oxyjs row: {rows:?}");
2092        // the driver tells each call it is a PDF run once an answer said so
2093        let seen = std::sync::Mutex::new(Vec::new());
2094        let call = |t: Tier, done: &[Hop]| -> Call {
2095            seen.lock().expect("lock").push((t, page.pdf_run(done)));
2096            let h = match t {
2097                Plain => Hop { kind: "pdf", ..hop(Plain, "blocked_403") },
2098                Oxy => hop(Oxy, "not_pdf"),
2099                _ => hop(t, "ok"),
2100            };
2101            Box::pin(async move { h })
2102        };
2103        let path: Vec<(Tier, bool)> = drive(&page, &call, Vec::new(), &drop).iter().map(|h| (h.tier, h.ok)).collect();
2104        assert_eq!(path, [(Plain, false), (Oxy, false), (Bd, true)]);
2105        assert_eq!(seen.into_inner().expect("lock"), [(Plain, false), (Oxy, true), (Bd, true)]);
2106    }
2107
2108    /// DETECT by magic on every body: a PDF is read in `judge` (whole, an end-of-file line short, cut through a
2109    /// page), a zip is a document, a provider's page in a PDF run is `not_pdf`, an Oxylabs copy whose offsets moved
2110    /// is `pdf_mangled`; the best failed copy is the cut PDF.
2111    #[test]
2112    fn judge_reads_documents() {
2113        let pdf: &[u8] = include_bytes!("../tests/fixtures/three-pages.pdf");
2114        let mid = pdf.windows(7).position(|w| w == b"5 0 obj").expect("page 2") + 40;
2115        let raw = |b: &[u8], ct: &str| Raw { status: 200, body: b.to_vec(), ctype: ct.into(), ..Raw::default() };
2116        let at = |t: Tier, b: &[u8], ct: &str, pdf: bool| {
2117            let h = judge(t, raw(b, ct), "https://a.example/x.pdf", false, pdf);
2118            (h.ok, h.code.clone(), h.kind, h.doc.as_ref().map(|d| d.sections.len()))
2119        };
2120        let page = b"<html><head><title>Sign in</title></head><body>Sign in</body></html>";
2121        assert_eq!(at(Tier::Oxy, pdf, "", true), (true, "ok".into(), "pdf", Some(3)));
2122        assert_eq!(at(Tier::Oxy, &pdf[..pdf.len() - 6], "", true), (true, "ok".into(), "pdf", Some(3)));
2123        assert_eq!(at(Tier::Bd, &pdf[..mid], "", true), (false, "pdf_truncated".into(), "pdf", Some(3)));
2124        assert_eq!(at(Tier::Oxy, page, "", true), (false, "not_pdf".into(), "html", None));
2125        let gone = judge(Tier::Bd, Raw { status: 404, ..raw(page, "") }, "https://a.example/x.pdf", false, true);
2126        assert_eq!(gone.code, "not_found", "the site said 404: the file is missing, not walled");
2127        assert_eq!(at(Tier::Plain, page, "application/pdf", false), (false, "not_pdf".into(), "pdf", None));
2128        assert_eq!(at(Tier::Plain, b"PK\x03\x04rest", "", false), (true, "ok".into(), "zip", None));
2129        // a text document is served as it is, from any tier; in a PDF run it is not the file
2130        assert_eq!(at(Tier::Plain, b"a\nb", "text/plain", false), (true, "ok".into(), "text", Some(1)));
2131        assert_eq!(at(Tier::Bd, b"{\"a\":1}", "", false), (true, "ok".into(), "json", Some(1)));
2132        assert_eq!(at(Tier::Plain, b"a", "text/plain", true).1, "not_pdf");
2133        let gone = judge(
2134            Tier::Plain,
2135            Raw { status: 500, ..raw(b"{}", "application/json") },
2136            "https://a.example/x",
2137            false,
2138            false,
2139        );
2140        assert_eq!(
2141            (gone.ok, gone.code.as_str(), gone.kind),
2142            (false, "http_500", "json"),
2143            "a site's error is no document"
2144        );
2145        assert_eq!(at(Tier::Oxy, pdf, "", false).1, "ok", "a PDF found by magic outside a PDF run");
2146        let lit: &[u8] = include_bytes!("../tests/fixtures/literal-escape.pdf");
2147        let i = lit.windows(4).position(|w| w == b"\\x9c").expect("literal");
2148        let moved = [&lit[..i], &[0x9c], &lit[i + 4..]].concat();
2149        assert_eq!(at(Tier::Oxy, &moved, "", true), (false, "pdf_mangled".into(), "pdf", Some(3)));
2150        assert_eq!(at(Tier::Plain, &moved, "", true).1, "ok", "plain's bytes are the server's own");
2151        let check = b"<html><head><title>Voight-Kampff Browser Test</title></head><body><h1>Voight-Kampff Browser \
2152                      Test</h1><p>Checking your browser before you reach the file.</p><p>This takes a few seconds; the \
2153                      download starts by itself once the test is done.</p></body></html>";
2154        assert_eq!(at(Tier::Plain, check, "text/html", false).1, "ok", "as a page it passes");
2155        assert_eq!(at(Tier::Plain, check, "text/html", true).1, "not_pdf", "in a PDF run it is not the file");
2156        let mut hops = vec![
2157            judge(Tier::Plain, Raw { status: 403, ..raw(page, "text/html") }, "https://a.example/x.pdf", false, true),
2158            judge(Tier::Oxy, raw(&pdf[..mid], ""), "https://a.example/x.pdf", false, true),
2159            judge(Tier::Bd, raw(page, ""), "https://a.example/x.pdf", false, true),
2160        ];
2161        let o = outcome("https://a.example/x.pdf", &mut hops, 1);
2162        assert_eq!(
2163            (o.meta.code.as_str(), o.meta.kind.as_str(), o.meta.provider.as_str()),
2164            ("pdf_truncated", "pdf", "oxylabs")
2165        );
2166        assert_eq!((o.file.map(|f| f.0), o.doc.map(|d| d.mode)), (Some("raw.pdf".into()), Some("pdf".into())));
2167    }
2168
2169    /// A Reddit thread (its meta.json as saved): bd's copy was thin, the hint said `js:true`, and
2170    /// `js:true` went to bd for the same copy. The render that sent the shown copy is never asked again while the
2171    /// other provider's render has a key.
2172    #[test]
2173    fn a_render_is_not_bought_twice_for_the_same_copy() {
2174        let m: Meta = serde_json::from_str(
2175            r#"{"url":"https://www.reddit.com/r/rust/comments/63wts9/x/","provider":"brightdata","ok":true,"code":"ok",
2176            "hops":[{"provider":"plain","code":"captcha_wall"},{"provider":"brightdata","code":"ok","cost":0.0015}]}"#,
2177        )
2178        .unwrap_or_default();
2179        let mut p = Plan { js: true, ..plan(Mode::Auto) };
2180        p.avoid = rendered(&m, &p.keys);
2181        assert_eq!(p.ladder(&[]), [Tier::OxyJs, Tier::DecodoJs], "the other renders only");
2182        assert_eq!(rendered(&m, &[Tier::Plain, Tier::Bd]), None, "one key: bd is still the only render");
2183    }
2184
2185    /// No kept run takes a tier off the ladder or its retry (nothing keeps runs): every cross-run skip policy lost
2186    /// 2–4 of 17 oxy no-JS serves to save ~2 s. Oxy-only: oxy no-JS timed out on r/rust, oxyjs ran after it,
2187    /// and the failed run names the missing keys whose renders could still serve it.
2188    #[test]
2189    fn no_kept_run_wears_a_tier() {
2190        use Tier::*;
2191        let oxy = Plan { keys: vec![Plain, Oxy, OxyJs], ..plan(Mode::Auto) };
2192        let hops = [hop(Plain, "cloudflare_wall"), hop(Oxy, "provider_timeout"), hop(OxyJs, "x")];
2193        assert_eq!(route(&oxy).0.iter().map(|r| r.0).collect::<Vec<_>>(), [Plain, Oxy, OxyJs]);
2194        let rows = skipped(&oxy, &hops, "", "u1", "");
2195        assert!(rows.len() == 2 && rows[0].starts_with("! no_key bd · would try "), "{rows:?}");
2196    }
2197
2198    /// With a fake transport: `js:true` calls exactly ONE provider when it answers, however slow (past the 5 s
2199    /// hedge, scaled to 200 ms); the second only after a failure; an `auto` ladder still hedges
2200    /// (`slow_first_provider_is_hedged`).
2201    #[test]
2202    fn paid_ask_runs_one_provider() {
2203        let p = Plan { js: true, hedge: Duration::from_millis(50), ..plan(Mode::Auto) };
2204        for (first, want) in
2205            [("ok", vec![(Tier::Bd, "ok")]), ("js_shell", vec![(Tier::Bd, "js_shell"), (Tier::OxyJs, "ok")])]
2206        {
2207            // bd answers past the hedge (200 ms), oxyjs at once
2208            let (ms, code) =
2209                (|t| if t == Tier::Bd { 200 } else { 5 }, move |t| if t == Tier::Bd { first } else { "ok" });
2210            let call = move |t: Tier, _: &[Hop]| -> Call {
2211                Box::pin(async move {
2212                    tokio::time::sleep(Duration::from_millis(ms(t))).await;
2213                    hop(t, code(t))
2214                })
2215            };
2216            let hops = drive(&p, &call, Vec::new(), &drop);
2217            let path: Vec<(Tier, &str)> = hops.iter().map(|h| (h.tier, h.code.as_str())).collect();
2218            assert_eq!(path, want, "bd {first}");
2219        }
2220    }
2221
2222    #[test]
2223    fn site_is_the_registrable_domain() {
2224        for (url, want) in [
2225            ("https://m.youtube.com/watch?v=1", "youtube.com"),
2226            ("https://www.bbc.co.uk/news", "bbc.co.uk"),
2227            ("https://data.gov.uk/x", "data.gov.uk"),
2228            ("https://www.bundestag.de/portal", "bundestag.de"),
2229            ("https://www.tripadvisor.ca/", "tripadvisor.ca"),
2230            ("https://ex.com/ok", "ex.com"),
2231            ("http://10.0.0.7:8080/", "10.0.0.7"),
2232            ("http://localhost/", "localhost"),
2233            ("https://co.uk/", "co.uk"),
2234            ("https://alice.github.io/blog/", "alice.github.io"),
2235            ("https://a.b.github.io/", "b.github.io"),
2236            ("https://leapcell.medium.com/x", "medium.com"),
2237            ("https://medium.com/@bob/x", "medium.com"),
2238            ("https://www.medium.com/x", "medium.com"),
2239            ("https://my-app.vercel.app/", "my-app.vercel.app"),
2240            ("https://github.io/", "github.io"),
2241        ] {
2242            assert_eq!(site(url), want, "{url}");
2243        }
2244    }
2245
2246    /// A government host by its labels, no host list: the last label, or the one before a two-letter
2247    /// country code with a host under it (`go.pl` is a site, `www.gov.uk` is not). `europa.eu` and `bundestag.de` left
2248    /// with the list (BD refused 3 of 6 sampled gov hosts the labels catch; a miss costs one $0 hop).
2249    #[test]
2250    fn gov_is_a_label_rule() {
2251        let yes = ["https://www.sec.gov/x", "https://apps.dtic.mil/", "https://data.gov.uk/x", "https://www.gov.pl/"];
2252        let more = ["https://x.gouv.fr/", "https://dof.gob.mx/", "https://www.go.jp/", "https://ird.govt.nz/"];
2253        assert!(yes.iter().chain(&more).chain(&["https://www.gv.at/"]).all(|u| gov(u)));
2254        for no in
2255            ["https://go.pl/", "https://eur-lex.europa.eu/x", "https://www.bundestag.de/", "https://gov.example.com/"]
2256        {
2257            assert!(!gov(no), "{no}");
2258        }
2259        assert!(Plan::new("https://get.data.gov.uk/a", Mode::Auto, false, 1.0, None).gov);
2260    }
2261
2262    /// Plain failed (no JS shell, so a shell from bd is no app page): bd and oxyjs are next.
2263    fn both() -> Vec<Hop> {
2264        vec![hop(Tier::Plain, "blocked_403")]
2265    }
2266
2267    fn and(more: Vec<Hop>) -> Vec<Hop> {
2268        both().into_iter().chain(more).collect()
2269    }
2270
2271    #[test]
2272    fn dry_route_and_skip_rows() {
2273        let all = vec![(Tier::Plain, None), (Tier::Oxy, None), (Tier::Bd, None), (Tier::OxyJs, Some(HEDGE))];
2274        assert_eq!(route(&plan(Mode::Auto)), (all, 0.004), "oxy no-JS after plain's captcha, the worst case");
2275        // Both keys, oxy no-JS after a captcha only; after a shell the page needs JS
2276        let after = |code| plan(Mode::Auto).ladder(&[hop(Tier::Plain, code)]);
2277        let renders = [Tier::Bd, Tier::OxyJs, Tier::DecodoJs];
2278        assert_eq!(after("js_shell")[1..], renders, "a shell: plain → bd ∥ oxyjs (→ decodojs with its key)");
2279        assert_eq!(after("captcha_wall")[..2], [Tier::Plain, Tier::Oxy], "plain → oxy → decodo → bd ∥ oxyjs");
2280        let race = Plan { hedge: Duration::ZERO, ..plan(Mode::Auto) };
2281        assert_eq!(route(&race).0[3], (Tier::OxyJs, Some(Duration::ZERO)));
2282        // bd is given up on (1 s + grace) before a 60 s hedge: oxyjs follows it instead of racing it
2283        let late = Plan { hedge: Duration::from_secs(60), timeout: Some(Duration::from_secs(1)), ..plan(Mode::Auto) };
2284        assert_eq!(route(&late).0[3], (Tier::OxyJs, None));
2285        let nokey = Plan { keys: vec![Tier::Plain], ..plan(Mode::Auto) };
2286        assert_eq!(route(&nokey).0, vec![(Tier::Plain, None)]);
2287        let rows = skipped(&nokey, &[hop(Tier::Plain, "blocked_403")], "u1", "u1", "");
2288        assert_eq!(rows.len(), 3, "one row per missing key, the cheapest first: {rows:?}");
2289        let oxy = "u1 ! no_key oxy · would try no-JS fetch + JS render ≤$0.0025 → ";
2290        assert!(rows[1].starts_with(oxy) && rows[0].starts_with("u1 ! no_key bd · would try unblock+JS"), "{rows:?}");
2291        assert!(rows[2].contains("no_key decodo · would try no-JS fetch + JS render ≤$0.0025"));
2292        // after a JS shell oxy no-JS served 0/15, so a key would buy the render only
2293        let rows = skipped(&nokey, &[hop(Tier::Plain, "js_shell")], "u1", "u1", "");
2294        assert!(rows[1].starts_with("u1 ! no_key oxy · would try JS render ≤$0.0015 → "), "{rows:?}");
2295        assert!(skipped(&nokey, &[hop(Tier::Plain, "not_found")], "u1", "u1", "").is_empty());
2296        let poor = Plan { cap: 0.001, ..plan(Mode::Auto) };
2297        let walled = [hop(Tier::Plain, "captcha_wall"), hop(Tier::Oxy, "x")];
2298        let rows = skipped(&poor, &walled, "u1", "u1", "");
2299        let want = format!(
2300            "u1 ! budget_hit bd oxyjs not tried · $0.0040 > cost:0.001 → {} u1 fresh:true cost:0.004 ≤$0.0040",
2301            crate::lang::bin()
2302        );
2303        let decodo = "u1 ! no_key decodo · would try no-JS fetch + JS render ≤$0.0025";
2304        assert!(rows[0].starts_with(decodo) && rows[1..] == [want], "decodo's key could still serve it: {rows:?}");
2305        // three renders are $0.0045, never the float sum's $0.0046
2306        let renders = Plan { keys: vec![Tier::Plain, Tier::Bd, Tier::OxyJs, Tier::DecodoJs], ..poor.clone() };
2307        let rows = skipped(&renders, &[hop(Tier::Plain, "js_shell")], "u1", "u1", "");
2308        assert!(rows.iter().any(|r| r.contains(" not tried · $0.0045 > cost:0.001 ")), "{rows:?}");
2309        // Priced for the URL's own plan, as its `dry:true` (a .gov page: no bd, `up to $0.0025`)
2310        let gov = skipped(&poor, &walled, "u1", "u1", "https://www.usa.gov/x");
2311        assert!(gov[1].ends_with(" cost:0.004 ≤$0.0025"), "{gov:?}");
2312        // The words after the binary heading the arrow, never after its name further in
2313        let arrow = |head: &str| worst(&format!("{head}{} u1 fresh:true", crate::lang::bin()), "");
2314        assert!(arrow("").is_some_and(|r| r.1 > 0.0 && r.0[0].0 == Tier::Plain), "{:?}", arrow(""));
2315        assert!(arrow("x").is_none() && arrow("top up, then ").is_none());
2316        assert!(skipped(&poor, &[hop(Tier::Plain, "too_big")], "u1", "u1", "").is_empty());
2317        let mobile = Ask { mobile: true, url: "https://a.example/".into(), ..Ask::default() };
2318        let row = ignored(&mobile, &[hop(Tier::Plain, "js_shell"), hop(Tier::Bd, "ok")], "u1");
2319        let want = "u1 ! ignored device bd · Bright Data has no device setting: desktop page → {b} u1 fresh:true \
2320                    provider:oxy device:mobile ≤$0.0025";
2321        assert_eq!(row, [want.replace("{b}", crate::lang::bin())]);
2322        assert!(ignored(&mobile, &[hop(Tier::Oxy, "ok")], "u1").is_empty());
2323        assert!(ignored(&Ask::default(), &[hop(Tier::Bd, "ok")], "u1").is_empty());
2324    }
2325
2326    /// Geo copies (`<html lang>`, title and first lines of the saved bytes, hand-trimmed): Reddit in
2327    /// Italian and in Arabic, Booking in pt-BR (oxyjs). The expected language is the page's own
2328    /// (`country:`, its URL's locale, plain's copy when plain held the page), never a guess. Behind plain's wall
2329    /// (what live runs get) only the URL can name it; where plain held the English page, they are flagged; bd's
2330    /// English Reddit is not; a Spanish `/es/es/` page on a `.com` is not.
2331    #[test]
2332    fn a_geo_copy_is_flagged() {
2333        use Tier::*;
2334        let page = |t: Tier, html: &str, url: &str, status: u16| {
2335            let body = html.as_bytes().to_vec();
2336            judge(t, Raw { status, ctype: "text/html".into(), body, ..Raw::default() }, url, t == OxyJs, false)
2337        };
2338        let reddit = "https://www.reddit.com/r/rust/comments/63wts9/why_are_there_so_many_linear_algebra_crates/";
2339        let ask = |url: &str| Ask { url: url.into(), ..Ask::default() };
2340        let why = |h: Hop, url: &str, done: &[Hop]| geo(h, &langs(&ask(url), done)).why;
2341        let en = include_str!("../tests/fixtures/geo-reddit-en.html");
2342        let held = page(Plain, en, reddit, 200);
2343        assert_eq!((held.ok, held.lang.as_str()), (true, "en"), "plain held the English page");
2344        let odd =
2345            |lang: &str| page(Plain, &en.replacen("<html", &format!("<html lang=\"{lang}\" x"), 1), reddit, 200).lang;
2346        assert_eq!([odd(&"a".repeat(10_000)), odd("e1-US"), odd(" pt-BR ")], ["", "", "pt"], "bounded");
2347        let it = || page(OxyJs, include_str!("../tests/fixtures/geo-reddit-it.html"), reddit, 200);
2348        assert!(it().ok, "the Italian copy passes every content check");
2349        // the path real runs take: plain gets a wall (plain held Reddit 0 of 29, Booking 0 of 14), whose
2350        // `lang` is not the site's, at any status; the expectation is then the URL's alone (ccTLD, `xx.`, first
2351        // segment), and a `.com` with none is no flag: the copy's language cannot be judged
2352        let wall =
2353            |url: &str, status: u16| page(Plain, include_str!("../tests/fixtures/js-challenge.html"), url, status);
2354        for status in [200, 403] {
2355            let w = wall(reddit, status);
2356            assert_eq!((w.ok, w.code.ends_with("_wall"), w.lang.as_str()), (false, true, ""), "{status}");
2357        }
2358        assert_eq!(why(it(), reddit, &[wall(reddit, 200)]), "", "a walled .com: no expectation, no flag");
2359        assert_eq!(why(it(), reddit, &[]), "", "no plain copy (js:true): no expectation, no flag");
2360        let eu = "https://www.reddit.com/r/europe/comments/1tb1ts5/vorstellungsgesprach_beim_energieversorger/";
2361        let ar = || page(OxyJs, include_str!("../tests/fixtures/geo-reddit-ar.html"), eu, 200);
2362        assert_eq!(why(ar(), eu, &[wall(eu, 403)]), "");
2363        let booking = "https://www.booking.com/hotel/fr/example-hotel.html";
2364        let pt = || page(OxyJs, include_str!("../tests/fixtures/geo-booking-ptbr.html"), booking, 200);
2365        assert_eq!(why(pt(), booking, &[wall(booking, 403)]), "", "/hotel/fr/ names no language");
2366        for url in ["https://www.reddit.fr/r/x", "https://it.example.org/x", "https://ex.com/it/x"] {
2367            assert_eq!(why(ar(), url, &[wall(url, 403)]), "lang:ar", "walled, the URL names it: {url}");
2368        }
2369        // Zara-class: plain held the English page, so its `lang` is the site's own
2370        assert_eq!(why(it(), reddit, std::slice::from_ref(&held)), "lang:it");
2371        assert_eq!(why(ar(), eu, &[page(Plain, en, eu, 200)]), "lang:ar");
2372        assert_eq!(why(pt(), booking, &[page(Plain, en, booking, 200)]), "lang:pt");
2373        // only the FIRST path segment names a locale: Booking's `/hotel/fr/` is the hotel's country (in a replay
2374        // 10 of 16 flags were Booking's English copies flagged `lang:en`)
2375        assert_eq!(why(page(Oxy, en, booking, 200), booking, &[]), "", "/hotel/fr/ in English: no flag");
2376        assert_eq!(why(page(Bd, en, reddit, 200), reddit, &[held]), "", "the English control");
2377        let zara = "https://www.zara.com/es/es/x.html";
2378        let es_page = include_str!("../tests/fixtures/geo-zara-es.html");
2379        assert_eq!(why(page(Oxy, es_page, zara, 200), zara, &[]), "", "/es/es/ names es: the page asked for");
2380        let en_zara = page(Oxy, en, zara, 200);
2381        assert_eq!(why(en_zara, zara, &[]), "lang:en", "/es/es/ in English is a geo copy");
2382        for (url, want) in [
2383            ("https://www.zara.es/x", ""),
2384            ("https://de.example.org/wiki/x", "lang:es"),
2385            ("https://en-gb.example.org/x", "lang:es"),
2386            ("https://ex.com/pt-br/x", "lang:es"),
2387            ("https://ex.com/shop/pt-br/x", ""),
2388            ("https://ex.com/go/es-page", ""),
2389        ] {
2390            assert_eq!(why(page(Oxy, es_page, url, 200), url, &[]), want, "{url}");
2391        }
2392        let cc = Ask { country: Some("it".into()), ..ask(reddit) };
2393        assert_eq!(geo(it(), &langs(&cc, &[])).why, "", "country:it names it");
2394    }
2395
2396    /// A URL naming no locale, fetched with no country sent (bd at home US), expects `en`; an
2397    /// Oxylabs call sends US, a query value or `country:` names one: no expectation (`a_geo_copy_is_flagged`).
2398    #[test]
2399    fn a_no_locale_copy_sent_none_expects_english() {
2400        use Tier::*;
2401        let booking = "https://www.booking.com/hotel/fr/example-hotel.html";
2402        let page = |t: Tier, html: &str, url: &str| {
2403            let (body, final_url) = (html.as_bytes().to_vec(), url.into());
2404            let raw = Raw { status: 200, ctype: "text/html".into(), body, final_url, ..Raw::default() };
2405            judge(t, raw, url, t == OxyJs, false)
2406        };
2407        let why = |h: Hop, url: &str, country: Option<&str>| {
2408            geo(h, &langs(&Ask { url: url.into(), country: country.map(Into::into), ..Ask::default() }, &[])).why
2409        };
2410        let es = |t: Tier, url: &str| page(t, include_str!("../tests/fixtures/geo-booking-es.html"), url);
2411        assert_eq!(why(es(Bd, booking), booking, None), "lang:es", "bd sent none");
2412        let en = page(Bd, include_str!("../tests/fixtures/geo-reddit-en.html"), booking);
2413        assert_eq!(why(en, booking, None), "", "bd in English");
2414        assert_eq!(why(es(OxyJs, booking), booking, None), "", "oxyjs sent US");
2415        let hl = "https://www.booking.com/hotel/fr/example-hotel.html?lang=es-es";
2416        assert_eq!(why(es(Bd, hl), hl, None), "", "the query names es");
2417        assert_eq!(why(es(Bd, booking), booking, Some("es")), "", "country:es");
2418        // a page whose canonical link is the URL asked is the site's own, in its own language: no flag, no paid
2419        // fix, an `own:` trace; a geo copy names its language's URL or no canonical at all (above), and stays
2420        // flagged
2421        for (file, url, want) in [
2422            (
2423                include_str!("../tests/fixtures/geo-own-es.html"),
2424                "https://www.pisos.example/alquiler/madrid/?orden=precio",
2425                "own:es",
2426            ),
2427            (
2428                include_str!("../tests/fixtures/geo-own-de.html"),
2429                "https://shop.example.com/produkt/kaffeemuehle-42",
2430                "own:de",
2431            ),
2432            (
2433                include_str!("../tests/fixtures/geo-copy-es.html"),
2434                "https://www.hotels.example/hotel/fr/example-hotel.html",
2435                "lang:es",
2436            ),
2437            (
2438                include_str!("../tests/fixtures/geo-own-es.html"),
2439                "https://www.pisos.example/alquiler/madrid/",
2440                "lang:es",
2441            ),
2442        ] {
2443            assert_eq!(why(page(Bd, file, url), url, None), want, "{url}");
2444        }
2445        let own = page(
2446            Bd,
2447            include_str!("../tests/fixtures/geo-own-es.html"),
2448            "https://www.pisos.example/alquiler/madrid/?orden=precio",
2449        );
2450        assert_eq!((own.ok, own.lang.as_str()), (true, "es"), "a served Spanish page");
2451    }
2452
2453    /// The driver with a fake transport: plain fails, oxy without JS too (one try after a captcha), bd is slow; oxyjs
2454    /// starts when the hedge runs out (5 s in `next`, scaled to 200 ms here), wins, and bd is cancelled, its list price
2455    /// unverified.
2456    #[test]
2457    fn slow_first_provider_is_hedged() {
2458        let p = Plan { hedge: Duration::from_millis(200), ..plan(Mode::Auto) };
2459        let started = std::sync::Mutex::new(Vec::new());
2460        let t0 = Instant::now();
2461        let call = |t: Tier, _: &[Hop]| -> Call {
2462            started.lock().expect("lock").push((t, t0.elapsed()));
2463            Box::pin(async move {
2464                let wait = if t == Tier::Bd { 5_000 } else { 5 };
2465                tokio::time::sleep(Duration::from_millis(wait)).await;
2466                hop(t, ["captcha_wall", "", "provider_error", "ok"][t as usize])
2467            })
2468        };
2469        let hops = drive(&p, &call, Vec::new(), &drop);
2470        let path: Vec<(Tier, &str)> = hops.iter().map(|h| (h.tier, h.code.as_str())).collect();
2471        let want = [
2472            (Tier::Plain, "captcha_wall"),
2473            (Tier::Oxy, "provider_error"),
2474            (Tier::OxyJs, "ok"),
2475            (Tier::Bd, "abandoned"),
2476        ];
2477        assert_eq!(path, want);
2478        let started = started.into_inner().expect("lock");
2479        let at = |t: Tier| started.iter().find(|s| s.0 == t).map(|s| s.1).unwrap_or_default();
2480        assert!(at(Tier::OxyJs) >= at(Tier::Bd) + Duration::from_millis(200), "oxyjs waited the hedge: {started:?}");
2481        assert!(t0.elapsed() < Duration::from_secs(1), "the loser was not awaited");
2482        assert!(at(Tier::Oxy) < at(Tier::Bd), "oxy no-JS before the renders after a captcha: {started:?}");
2483        // The cancelled loser may be finished and billed by the provider: its price is unverified, not spent
2484        assert_eq!((hops[3].cost, hops[3].upto), (0.0, 0.0015), "the cancelled call: unverified");
2485        let mut hops = hops;
2486        let o = outcome("https://a.example/", &mut hops, 9);
2487        let tried = "plain:captcha_wall✗ oxy:provider_error✗$0.0010 oxyjs✓ bd:abandoned✗≤$0.0015 (unverified)";
2488        assert_eq!((o.meta.cost, o.meta.tried().as_str(), o.meta.render), (0.0025, tried, Some(true)));
2489    }
2490
2491    /// With the free fetch off (plain not keyed) there is no free verdict to wait for: oxy without JS, its 10 s row, is
2492    /// the first rung, then bd ∥ oxyjs as after plain's captcha; a no-JS answer ends the run before a render starts.
2493    /// A page both renders cut at 60 s served without JS in 6.4 s.
2494    #[test]
2495    fn free_off_starts_at_the_no_js_rung() {
2496        use Tier::*;
2497        let off = Plan { keys: vec![Bd, Oxy, OxyJs], ..plan(Mode::Auto) };
2498        assert_eq!((next(&off, &[], &[]), off.timeout_of(Oxy, &[])), (Step::Start(Oxy), S(10)));
2499        assert_eq!(next(&off, &[], &[(Oxy, S(1))]), Step::Wait(S(14)), "a gate: its verdict first");
2500        assert_eq!(next(&off, &[hop(Oxy, "captcha_wall")], &[]), Step::Start(Bd));
2501        assert_eq!(next(&off, &[hop(Oxy, "provider_timeout")], &[]), Step::Start(Bd), "cut: the renders");
2502        assert_eq!(next(&off, &[hop(Oxy, "js_shell")], &[(Bd, S(5))]), Step::Start(OxyJs), "then the hedge");
2503        let all = vec![(Oxy, None), (Bd, None), (OxyJs, Some(HEDGE))];
2504        assert_eq!(route(&off), (all.clone(), 0.004));
2505        assert_eq!(crate::cli::path_of(&all), "oxy → bd ∥ oxyjs after 5s", "dry:true and config");
2506        let one = Plan { keys: vec![Oxy, OxyJs], ..plan(Mode::Auto) };
2507        assert_eq!(route(&one).0, [(Oxy, None), (OxyJs, None)], "one key: unchanged");
2508        let started = std::sync::Mutex::new(Vec::new());
2509        let call = |t: Tier, _: &[Hop]| -> Call {
2510            started.lock().expect("lock").push(t);
2511            Box::pin(async move { hop(t, "ok") })
2512        };
2513        let hops = drive(&off, &call, Vec::new(), &drop);
2514        assert_eq!(hops.iter().map(|h| (h.tier, h.ok)).collect::<Vec<_>>(), [(Oxy, true)]);
2515        assert_eq!(started.into_inner().expect("lock"), [Oxy], "no render started");
2516    }
2517
2518    /// THE billing rule for both providers: an answer is billed, a call WE cut (no status: our timeout, `wait:`,
2519    /// abandoned) is unverified at list price, the provider's own refusal, 408 or 5xx envelope is $0 (bd
2520    /// billed 15 s search cuts that `fats` printed `$0 (not charged)`).
2521    #[test]
2522    fn a_cut_is_unverified_a_refusal_is_free() {
2523        let at = |bill: bool, code: &str, status: u16| {
2524            let h = billed(
2525                Instant::now(),
2526                bill,
2527                0.0015,
2528                Hop { tier: Tier::Bd, code: code.into(), status, ..Hop::default() },
2529            );
2530            (h.cost, h.upto)
2531        };
2532        assert_eq!(at(true, "ok", 200), (0.0015, 0.0));
2533        for code in ["provider_timeout", "abandoned"] {
2534            assert_eq!(at(false, code, 0), (0.0, 0.0015), "{code}: we cut it");
2535        }
2536        assert_eq!(at(false, "provider_timeout", 408), (0.0, 0.0), "the provider's own 408");
2537        assert_eq!(at(false, "provider_error", 500), (0.0, 0.0), "its error envelope");
2538        assert_eq!(at(false, "http_502", 502), (0.0, 0.0), "bd's inner 5xx");
2539        let cut = Hop { upto: 0.0015, cost: 0.0, ..hop(Tier::Bd, "provider_timeout") };
2540        let m = Meta { hops: vec![cut.row()], ..Meta::default() };
2541        assert_eq!((m.tried().as_str(), m.upto()), ("bd:provider_timeout✗≤$0.0015 (unverified)", 0.0015));
2542        assert_eq!(crate::provider::bill(0.0225, 0.006), "$0.0225 + ≤$0.0060 unverified");
2543    }
2544
2545    /// A timeout's fix is a render while one is left to try; a render that ran out its time with none left is the
2546    /// end (no arrow), the agent's own `timeout:` cut the default time; shells from two providers are
2547    /// `no_copy` with no paid next step.
2548    #[test]
2549    fn timeout_fix_never_repeats_a_render() {
2550        use Tier::*;
2551        let b = crate::lang::bin();
2552        let (js, retry) = (format!("{b} u1 fresh:true js:true ≤$0.0030"), format!("{b} u1 fresh:true ≤$0.0040"));
2553        let free = format!("{retry} · last try not charged");
2554        let none = "nothing left to try · open https://a.example/ in a browser";
2555        let (bd, oxy) = (
2556            format!("{b} u1 fresh:true provider:bd ≤$0.0015"),
2557            format!("{b} u1 fresh:true provider:oxy js:true ≤$0.0015"),
2558        );
2559        type Path<'a> = &'a [(Tier, &'a str)];
2560        let rows: &[(Path, &str, &str)] = &[
2561            (&[(Plain, "provider_timeout")], "provider_timeout", &js),
2562            // one provider's timeout on a shell is that provider's failure: a render is left
2563            (&[(Plain, "js_shell"), (Oxy, "provider_timeout")], "provider_timeout", &js),
2564            (&[(Plain, "x"), (Oxy, "x"), (Bd, "provider_timeout")], "provider_timeout", &js),
2565            (&[(Plain, "js_shell"), (Oxy, "x"), (Bd, "x"), (OxyJs, "provider_timeout")], "provider_timeout", ""),
2566            (&[(Plain, "js_shell"), (Oxy, "js_shell")], "js_shell", &oxy),
2567            // shells from two providers: an app page
2568            (&[(Plain, "js_shell"), (Bd, "js_shell"), (OxyJs, "js_shell")], "no_copy", none),
2569            (
2570                &[(Plain, "js_shell"), (Oxy, "js_shell"), (Bd, "provider_timeout"), (OxyJs, "abandoned")],
2571                "no_copy",
2572                none,
2573            ),
2574            (&[(Plain, "provider_timeout"), (Bd, "js_shell")], "js_shell", &oxy),
2575            (&[(Plain, "provider_timeout"), (Oxy, "provider_error")], "provider_error", &free),
2576            // oxy-only Joomla: the wall plain met heads, not oxyjs's timeout after it
2577            (
2578                &[(Plain, "cloudflare_wall"), (OxyJs, "provider_error"), (OxyJs, "provider_timeout")],
2579                "cloudflare_wall",
2580                &bd,
2581            ),
2582        ];
2583        for (path, code, want) in rows {
2584            let mut hops: Vec<Hop> = path.iter().map(|(t, c)| hop(*t, c)).collect();
2585            let m = outcome("https://a.example/", &mut hops, 1).meta;
2586            let done = spent(&m, &[], &KEYED);
2587            let at = |arg| crate::lang::At { id: "u1", url: &m.url, arg, done: &done };
2588            let fix = fix_arg(&m, &[]).map_or(String::new(), |a| crate::lang::fix(move_code(&m), &at(a)));
2589            assert_eq!((m.code.as_str(), fix.as_str()), (*code, *want), "{path:?}");
2590        }
2591        // `timeout:8` once said "nothing left to try": the agent's cut → the default time; a tier's own cut row
2592        let p = Plan { timeout: Some(S(8)), ..plan(Mode::Auto) };
2593        let cut = |s: u64| cut_why(&p, Hop { timeout_s: s, ..hop(Bd, "provider_timeout") });
2594        assert_eq!((cut(8).why.as_str(), cut(40).why.as_str()), ("timeout:8s", "took > 40 s here"));
2595        let mut hops = vec![hop(Plain, "blocked_403"), hop(Oxy, "x"), cut(8), Hop { tier: OxyJs, ..cut(8) }];
2596        let m = outcome("https://a.example/", &mut hops, 1).meta;
2597        let at = crate::lang::At {
2598            id: "u1",
2599            url: &m.url,
2600            arg: fix_arg(&m, &[]).unwrap_or_default(),
2601            done: &spent(&m, &[], &KEYED),
2602        };
2603        assert_eq!(crate::lang::fix(&m.code, &at), retry, "after `timeout:8`: fresh:true, never nothing left");
2604        let mut hops = vec![hop(Plain, "blocked_403"), hop(OxyJs, "x"), cut(40)];
2605        let m = outcome("https://a.example/", &mut hops, 1).meta;
2606        // Read as `cut at 40 s (5m ago)`, its age from the copy's time; none under a minute
2607        assert_eq!(fail_detail(&m, "").0, "bd cut at 40 s");
2608        let old = Meta { t: m.t - 300.0, ..m.clone() };
2609        assert_eq!(fail_detail(&old, "").0, "bd cut at 40 s (5m ago)");
2610        assert_eq!(fix_arg(&m, &[]), Some("js:true"), "oxy no-JS left: `lang::fix` names it");
2611    }
2612
2613    /// No longer call follows our cut: a render cut at 40 s (or at the agent's `timeout:150`) with no
2614    /// keyed tier left is the run's end, a count with no arrow; the row names the cut.
2615    #[test]
2616    fn a_cut_render_is_the_end() {
2617        use Tier::*;
2618        let p = |s: u64| Plan { timeout: (s == 150).then_some(S(s)), ..plan(Mode::Auto) };
2619        let cut = |s: u64| cut_why(&p(s), Hop { timeout_s: s, ..hop(Bd, "provider_timeout") });
2620        for (s, why) in [(40, "bd cut at 40 s"), (150, "bd timeout:150s")] {
2621            let m = outcome("https://a.example/", &mut [hop(Plain, "js_shell"), hop(OxyJs, "x"), cut(s)], 1).meta;
2622            assert_eq!((fix_arg(&m, &[]), fail_detail(&m, "").0.as_str()), (None, why));
2623        }
2624    }
2625
2626    /// Spotify: the provider refused the render (its 4xx) or gave up (`faulted`): settled, never asked again by
2627    /// name or by an arrow's own dry (`fail_row`'s gate); the keyed tier left by name, else a count; a bare
2628    /// 5xx is a flake. eBay: bd's rate limit is a wait, so with oxyjs settled bd is the move, never `provider:oxy`
2629    /// (its dry plans oxyjs). Another copy's 4xx settles this one only for `url`, a 404 or the same country.
2630    #[test]
2631    fn a_settled_tier_is_spent() {
2632        use Tier::*;
2633        let b = crate::lang::bin();
2634        let erred = |why: &str| Hop { why: why.into(), country: "US".into(), ..hop(OxyJs, "provider_error") };
2635        let m = |why: &str| outcome("https://a.example/", &mut [hop(Plain, "js_shell"), erred(why)], 1).meta;
2636        let row = |m: &Meta, others: &[Meta]| {
2637            let r = fail_row(m, others, "", "u1", false);
2638            (r.2.unwrap_or_default(), r.1)
2639        };
2640        let bd = outcome("https://a.example/", &mut [hop(Bd, "js_shell")], 1).meta;
2641        let to_bd = format!("{b} u1 fresh:true provider:bd ≤$0.0015");
2642        for why in ["400 url: value not supported", "404", "500 faulted: request failed after too many retries"] {
2643            assert_eq!(row(&m(why), &[]).0, to_bd, "{why}");
2644            assert_eq!(row(&m(why), std::slice::from_ref(&bd)), (String::new(), " · failed 1/2 here".into()), "{why}");
2645            assert!(spent(&m(why), &[], &KEYED).contains(&"oxyjs"), "{why}");
2646        }
2647        assert_eq!(fix_arg(&m("500"), &[bd.hops[0].clone()]), Some("provider:oxy js:true"), "a flake: the named retry");
2648        assert_eq!(fail_detail(&m("400 url: value not supported"), "").0, "oxyjs 400 url: value not supported");
2649        let ebay = |why: &str| {
2650            let mut hops = [hop(Bd, "rate_limited"), erred(why)];
2651            outcome("https://a.example/", &mut hops, 1).meta
2652        };
2653        assert_eq!(row(&ebay("500 faulted: request failed"), &[]).0, to_bd, "a rate limit is a wait");
2654        // another copy's 400 on another field, sent FR, settles nothing for an arrow whose request sends another
2655        // country (`fresh:true` may plan oxyjs), but does for one sending FR (`provider::sent`); one naming the url,
2656        // a 404 or a give-up settles every copy: its dry may not plan it
2657        let fr = |why: &str| Hop { country: "FR".into(), ..erred(why) }.row();
2658        let geo = |why: &str| Meta { url: "http://a.example/".into(), hops: vec![fr(why)], ..m("x") };
2659        let reset = outcome("http://a.example/", &mut [hop(Plain, "connect_failed")], 1).meta;
2660        let arrow = |why: &str| row(&reset, &[geo(why)]).0;
2661        // a `location` error refuses the country sent, never the URL (a provider_error, not provider_refused)
2662        for why in ["400 geo_location: not supported", "400 location: value should be in zip/postal codes"] {
2663            assert_eq!(arrow(why), format!("{b} u1 fresh:true ≤$0.0040"), "scoped: {why}");
2664            let cut = [geo(why)];
2665            assert!(!clear(&format!("{b} u1 fresh:true country:fr"), &reset, &cut), "the refused country: {why}");
2666            assert!(clear(&format!("{b} u1 fresh:true country:de"), &reset, &cut), "another country: {why}");
2667        }
2668        assert_eq!(arrow("400 url: value not supported"), to_bd.as_str(), "every copy");
2669        assert_eq!(arrow("404"), to_bd.as_str(), "every copy");
2670    }
2671
2672    /// 4-hop walks on two sites: the 150 s call failing as the 60 s call did is the same
2673    /// failure: a count, no second `fresh:true`; another tier or country is another way.
2674    #[test]
2675    fn the_longer_call_failing_the_same_way_is_a_count() {
2676        use Tier::*;
2677        let meta = |s: u64, cc: &str| {
2678            let bd = Hop { timeout_s: s, country: cc.into(), ..hop(Bd, "http_502") };
2679            outcome("https://a.example/", &mut [hop(Plain, "captcha_wall"), bd], 1).meta
2680        };
2681        let (u1, u3) = (meta(60, "FR"), meta(150, "FR"));
2682        assert_eq!(fix_arg(&u3, &[]), Some(""));
2683        assert_eq!(fail_count(&u3, [&u1].into_iter(), Some("")).as_deref(), Some(" · failed 2/2 here"));
2684        assert_eq!(fail_count(&u3, [&meta(60, "US")].into_iter(), Some("")), None, "another country");
2685    }
2686
2687    /// A tier whose only signal was OUR cut (`upto`) casts no app-page vote, but it is tried: with nothing else
2688    /// left the run ends (TikTok: bd cut at 60 s; both renders cut), another keyed tier is the move (a Reddit
2689    /// thread: oxy no-JS cut at 10 s → oxyjs, then oxy no-JS after the renders' captchas).
2690    #[test]
2691    fn a_cut_tier_is_tried() {
2692        use Tier::*;
2693        let b = crate::lang::bin();
2694        let ours = |t: Tier, s: u64| Hop { upto: t.spec().price, timeout_s: s, ..hop(t, "provider_timeout") };
2695        let fix = |m: &Meta, cuts: &[HopRow]| {
2696            let arg = fix_arg(m, cuts);
2697            let at =
2698                crate::lang::At { id: "u1", url: &m.url, arg: arg.unwrap_or_default(), done: &spent(m, &[], &KEYED) };
2699            arg.map(|_| crate::lang::fix(&m.code, &at))
2700        };
2701        let mut tiktok = [hop(Plain, "js_shell"), hop(OxyJs, "js_shell"), ours(Bd, 60)];
2702        let m = outcome("https://a.example/", &mut tiktok, 1).meta;
2703        assert_eq!((m.code.as_str(), fix(&m, &[])), ("provider_timeout", None), "not no_copy: the end");
2704        let mut reddit =
2705            [hop(Plain, "blocked_403"), ours(Oxy, 10), hop(Bd, "captcha_wall"), hop(OxyJs, "captcha_wall")];
2706        let m = outcome("https://a.example/", &mut reddit, 1).meta;
2707        assert_eq!(fix(&m, &[]), Some(format!("{b} u1 fresh:true provider:oxy ≤$0.0025")), "oxy, then oxyjs");
2708        // 8 saved copies: both renders cut at 60 s = both tried, the end, never js:true
2709        let mut both = [hop(Plain, "js_shell"), ours(Bd, 60), ours(OxyJs, 60)];
2710        let m = outcome("https://a.example/", &mut both, 1).meta;
2711        assert_eq!(fix(&m, &[]), None, "never js:true");
2712        let again = outcome("https://a.example/", &mut [ours(Oxy, 10)], 1).meta;
2713        let cuts: Vec<HopRow> = m.hops.clone();
2714        assert_eq!(fix(&again, &cuts), None, "the renders another copy cut: a count");
2715        assert_eq!(fix(&again, &[]).as_deref(), Some(format!("{b} u1 fresh:true js:true ≤$0.0030").as_str()));
2716    }
2717
2718    /// A Joomla copy with only `meta.code` changed: a wall at plain then OUR cut on the paid tier
2719    /// prints the same reason and move whatever code heads the row: the cut tier decides, never the head.
2720    #[test]
2721    fn a_wall_headed_cut_keeps_the_timeout_move() {
2722        use Tier::*;
2723        let b = crate::lang::bin();
2724        let ours =
2725            || Hop { upto: 0.0015, timeout_s: 40, why: "took > 40 s here".into(), ..hop(OxyJs, "provider_timeout") };
2726        let row = |m: &Meta| {
2727            let done = spent(m, &[], &KEYED);
2728            let at = |arg| crate::lang::At { id: "u1", url: &m.url, arg, done: &done };
2729            (fail_detail(m, "").0, fix_arg(m, &[]).map_or(String::new(), |a| crate::lang::fix(move_code(m), &at(a))))
2730        };
2731        let paid = Hop { cost: 0.0015, ..hop(Bd, "captcha_wall") };
2732        let bd = format!("{b} u1 fresh:true provider:bd ≤$0.0015");
2733        for (mut hops, want) in [
2734            (vec![hop(Plain, "cloudflare_wall"), ours()], bd),
2735            (vec![hop(Plain, "cloudflare_wall"), paid, ours()], String::new()),
2736        ] {
2737            let wall = outcome("https://a.example/", &mut hops, 1).meta;
2738            let cut = Meta { code: "provider_timeout".into(), ..wall.clone() };
2739            assert!(wall.code.ends_with("_wall"), "the wall heads it: {}", wall.code);
2740            let (why, fix) = row(&wall);
2741            assert!(why == "oxyjs cut at 40 s" && fix == want, "{}: {why} {fix}", wall.tried());
2742            assert_eq!(row(&wall), row(&cut), "the same row apart from the code word");
2743        }
2744        // behind a sign-in gate (`one_render`) the run is the gate's only when its render met it too: a cut or
2745        // refused render names the run, so its own move (the other provider, the end) survives
2746        for (last, want) in
2747            [("js_shell", "login_wall"), ("provider_timeout", "provider_timeout"), ("provider_error", "provider_error")]
2748        {
2749            let mut hops = vec![hop(Plain, "login_wall"), hop(Bd, last)];
2750            assert_eq!(outcome("https://a.example/a/all", &mut hops, 1).meta.code, want, "{last}");
2751        }
2752    }
2753
2754    /// ONE render behind a sign-in gate whoever met it, plain or a render (plain's 403, then bd on the gate, once
2755    /// rendered twice); a render the provider refused rendered nothing, so the next one may try.
2756    #[test]
2757    fn a_sign_in_gate_gets_one_render() {
2758        use Tier::*;
2759        let p = Plan { keys: Tier::ALL.to_vec(), ..plan(Mode::Auto) };
2760        let rest = |mut hops: Vec<Hop>| {
2761            while let Step::Start(t) = next(&p, &hops, &[]) {
2762                hops.push(hop(t, "js_shell"));
2763            }
2764            hops.iter().filter(|h| h.tier.can("js")).map(|h| h.tier).collect::<Vec<_>>()
2765        };
2766        assert_eq!(rest(vec![hop(Plain, "login_wall")]), [Bd], "plain's gate");
2767        assert_eq!(rest(vec![hop(Plain, "blocked_403"), hop(Bd, "login_wall")]), [Bd], "bd met the gate");
2768        assert_eq!(rest(vec![hop(Plain, "login_wall"), hop(Bd, "provider_refused")]), [Bd, OxyJs], "bd refused");
2769    }
2770
2771    /// 16 saved Akamai pages, 534-536 B, were `js_shell` before: a short page that loads no JavaScript and
2772    /// shows none of its own words is the site refusing this provider (no phrase list, any language; 1,323 saved
2773    /// bodies: 0 verdicts move); the fix is the other keyed provider, else a count.
2774    #[test]
2775    fn an_error_page_is_no_shell() {
2776        use Tier::*;
2777        let akamai = "<html><head><title>Site Maintenance</title></head><body><h1>Oops! Something went wrong.</h1>\
2778                      <p>Reference #18.5f3c1102.1760500000.1a2b3c</p></body></html>";
2779        assert_eq!(
2780            check(akamai, 200, "", "", "https://www.tiktok.com/@example_creator/video/7000000000000000002").1,
2781            "error_page"
2782        );
2783        let bare = "<html><head><title>Preise und Angebote</title></head><body><h1>Entschuldigung</h1>\
2784                    <p>Die Website ist vorübergehend nicht erreichbar.</p></body></html>";
2785        assert_eq!(check(bare, 200, "", "", "").1, "error_page", "any language");
2786        let moved = bare.replace("<body>", r#"<body><meta http-equiv="Refresh" content="0; url=/k">"#);
2787        assert_eq!(check(&moved, 200, "", "", "").1, "js_shell", "a refresh moves on");
2788        let post = "<h1>Something went wrong with my build</h1><p>The error code was E0502, borrow twice.</p>\
2789                <p>It builds on stable but not on beta; the borrow checker rejects the second loop.</p>";
2790        let own =
2791            format!("<html><head><title>Something went wrong with my build</title></head><body>{post}</body></html>");
2792        assert_eq!(check(&own, 200, "", "", "https://a.example/").1, "ok", "a page about an error shows its own words");
2793        let b = crate::lang::bin();
2794        let fix = |hops: &mut [Hop]| {
2795            let m = outcome("https://a.example/", hops, 1).meta;
2796            let arg = fix_arg(&m, &[]);
2797            let at =
2798                crate::lang::At { id: "u1", url: &m.url, arg: arg.unwrap_or_default(), done: &spent(&m, &[], &KEYED) };
2799            (fail_detail(&m, "").0, arg.map(|_| crate::lang::fix(&m.code, &at)))
2800        };
2801        let one = fix(&mut [
2802            hop(Plain, "js_shell"),
2803            Hop { why: "refused here (error page)".into(), ..hop(OxyJs, "error_page") },
2804        ]);
2805        let want =
2806            ("oxy refused here (error page)".to_string(), Some(format!("{b} u1 fresh:true provider:bd ≤$0.0015")));
2807        assert_eq!(one, want);
2808        assert_eq!(
2809            fix(&mut [hop(Plain, "js_shell"), hop(Bd, "error_page"), hop(OxyJs, "error_page")]).1,
2810            None,
2811            "a count"
2812        );
2813    }
2814
2815    fn check(h: &str, status: u16, headers: &str, fin: &str, url: &str) -> (bool, String, usize, bool) {
2816        let r = Raw { status, headers: headers.into(), final_url: fin.into(), ..Raw::default() };
2817        super::check(&crate::html::parse(h), h, &r, url)
2818    }
2819
2820    /// No phrase, no host: a short copy whose visible text is under `title_ratio` × its
2821    /// title's chars says only its own name, a state page ("Post isn't available"): `error_page`, so `spent` bars
2822    /// that provider. A short real page (example.com: two paragraphs under a 14-char title) stays served.
2823    #[test]
2824    fn a_title_only_copy_is_an_error_page() {
2825        let state = include_str!("../tests/fixtures/state-page.html");
2826        let url = "https://photos.example/p/DW3NZXxDJvB/";
2827        assert_eq!(check(state, 200, "", url, url).1, "error_page");
2828        let example = "<html><head><title>Example Domain</title></head><body><div><h1>Example Domain</h1>\
2829                       <p>This domain is for use in illustrative examples in documents. You may use this domain in \
2830                       literature without prior coordination or asking for permission.</p><p><a \
2831                       href=\"https://www.iana.org/domains/example\">More information...</a></p></div></body></html>";
2832        assert_eq!(check(example, 200, "", "https://example.com/", "https://example.com/").1, "ok");
2833        // a short page that serves its own title is the page, whatever script it loads; at 4xx the marker walls it
2834        let pin = "<html><head><title>Hubble Sees the Eye | Pins</title><script src=/a.js></script></head><body>\
2835                   <h1>Hubble Sees the Eye</h1><p>A spiral galaxy seen face-on by the Hubble Space Telescope, its \
2836                   arms full of young blue stars.</p><script src=/challenge.js></script></body></html>";
2837        assert_eq!(check(pin, 200, "", "", "").1, "ok", "a served copy is not a wall");
2838        assert_eq!(check(pin, 403, "", "", "").1, "captcha_wall", "a 4xx with the marker is");
2839    }
2840
2841    /// No wall path is named (LinkedIn's `/authwall` row gone): a copy that landed where the asked id (8+ letters or
2842    /// digits) is gone and shows none of its own words is `redirected`; one that shows them is served (the outline
2843    /// flags it), and a short id or a kept one is no redirect. A sign-in gate hands the asked path back in its query
2844    /// and names a sign-in: `login_wall` before `redirected`, whatever the id; a landing that only lost the page,
2845    /// or a bounce that names no sign-in or hands back another site's page, is no gate.
2846    #[test]
2847    fn a_lost_id_is_redirected() {
2848        let url = "https://www.linkedin.com/company/example-data-insights/";
2849        let wall = "<html><head><title>تسجيل | LinkedIn</title></head><body><h1>انضم</h1><script src=/a.js></script></body></html>";
2850        let fin = "https://www.linkedin.com/authwall?trk=bf&sessionRedirect=https%3A%2F%2Fwww.linkedin.com%2Fcompany";
2851        assert_eq!(check(wall, 200, "", fin, url).1, "redirected");
2852        let own = "<html><head><title>Example Data Insights | LinkedIn</title></head><body><h1>Example Data Insights</h1><p>Data analytics and business intelligence consulting in Lyon, France.</p><p>IT services · 51-200 employees · Lyon · 1,204 followers</p></body></html>";
2853        assert_eq!(check(own, 200, "", fin, url).1, "ok", "its own words: the page, wherever it landed");
2854        assert_eq!(
2855            check(wall, 200, "", fin, "https://x.com/company/abc/").1,
2856            "js_shell",
2857            "a 3-char id, not handed back"
2858        );
2859        let gate = "https://x.com/i/jf/onboarding/web?redirect_after_login=%2Fsomeone%2Fall&mode=login";
2860        assert_eq!(check(wall, 200, "", gate, "https://x.com/someone/all").1, "login_wall", "the path handed back");
2861        let back =
2862            "https://www.linkedin.com/uas/authenticate?r=https%3A%2F%2Flinkedin.com%2Fcompany%2Fexample-data-insights";
2863        assert_eq!(check(wall, 200, "", back, url).1, "login_wall", "before `redirected`, a full URL handed back");
2864        // live copies once misread as `redirected`: an index page's root, a renamed slug, a dropped sub-tab, a short
2865        // link's shell
2866        for (fin, asked) in [
2867            ("https://docs.ex.com/", "https://docs.ex.com/index.html"),
2868            ("https://ex.com/p/new-name-of-it?ref=old", "https://ex.com/p/oldnameofthething"),
2869            ("https://ex.com/u/someone", "https://ex.com/u/someone/likes"),
2870            ("https://ex.com/a/b?utm=x", "https://ex.link/xyz"),
2871            // bounces that hand the page back and name no sign-in, and a sign-in that hands back another site's
2872            ("https://ex.com/notfound?from=%2Fp%2Fthing-that-moved", "https://ex.com/p/thing-that-moved"),
2873            ("https://ex.com/choose-country?return=%2Fitem%2Fabcdefghij", "https://ex.com/item/abcdefghij"),
2874            ("https://ex.com/consent?continue=https%3A%2F%2Fex.com%2Fwatch", "https://ex.com/watch"),
2875            ("https://ex.com/p?next_login=https%3A%2F%2Fother.org%2Fwatch", "https://ex.com/watch"),
2876        ] {
2877            assert_ne!(check(wall, 200, "", fin, asked).1, "login_wall", "{asked} → {fin}");
2878        }
2879        assert_eq!(check(wall, 200, "", url, url).1, "js_shell", "the id kept");
2880    }
2881
2882    /// The sign-in words are whole words of the landing's path or its query key, never a piece of one, and a
2883    /// compound is named by its last word: docs about authentication, an author's page, a page on designing, a
2884    /// consent page offering a login-free mode, a signing guide. The asked path itself is no landing.
2885    #[test]
2886    fn a_sign_in_is_a_whole_word() {
2887        for (fin, asked) in [
2888            (
2889                "https://ex.com/docs/authentication?from=%2Fdocs%2Fapi%2Foauth-tokens",
2890                "https://ex.com/docs/api/oauth-tokens",
2891            ),
2892            ("https://ex.com/authors/jane?ref=%2Fblog%2Fx", "https://ex.com/blog/x"),
2893            ("https://ex.com/designing?from=%2Fguide%2Fdesigning-apis", "https://ex.com/guide/designing-apis"),
2894            ("https://ex.com/consent/login-free?continue=https%3A%2F%2Fex.com%2Fwatch", "https://ex.com/watch"),
2895            ("https://ex.com/account?next=%2Fwatch", "https://ex.com/watch"),
2896            ("https://ex.com/signing-guide?from=%2Fwatch", "https://ex.com/watch"),
2897            ("https://ex.com/doc/login-best-practices", "https://ex.com/doc/login-best-practices"),
2898        ] {
2899            assert!(!sign_in_gate(asked, fin), "{asked} → {fin}");
2900        }
2901        for (fin, asked) in [
2902            ("https://ex.com/users/sign_in?redirect=%2Fwatch", "https://ex.com/watch"),
2903            ("https://ex.com/i/flow?redirect_after_login=%2Fwatch", "https://ex.com/watch"),
2904            ("https://ex.com/oauth/authorize?return_to=%2Fwatch", "https://ex.com/watch"),
2905            ("https://ex.com/sso?r=https%3A%2F%2Fex.com%2Fwatch", "https://ex.com/watch"),
2906            ("https://ex.com/customer-login?redirect=%2Fwatch", "https://ex.com/watch"),
2907            ("https://ex.com/en/signin.php", "https://ex.com/watch"),
2908            ("https://ex.com/sso?continue=https%3A%2F%2Fother.org%2Fwatch", "https://ex.com/watch"),
2909        ] {
2910            assert!(sign_in_gate(asked, fin), "{asked} → {fin}");
2911        }
2912    }
2913
2914    /// No consent host is named; the landing alone is no wall.
2915    #[test]
2916    fn consent_is_a_notice() {
2917        let page =
2918            |title: &str, body: &str| format!("<html><head><title>{title}</title></head><body>{body}</body></html>");
2919        let long = "Lorem ipsum dolor sit amet. ".repeat(40);
2920        let ok = page("Preise und Angebote | Shop", &format!("<h1>Preise und Angebote</h1><p>{long}</p>"));
2921        assert_eq!(check(&ok, 200, "", "https://consent.youtube.com/m?continue=x", "").1, "ok");
2922        // the interstitial titled "Before you continue to YouTube" with ~3.1k chars of cookie text (3/3 saved copies
2923        // the url row caught): its title is no page word, so the notice walls it under 4000 chars
2924        let terms = "<p>We use cookies and data to deliver and maintain Google services and measure audiences.</p>";
2925        let interstitial = page(
2926            "Before you continue to YouTube",
2927            &format!("<h1>Before you continue to YouTube</h1>{}", terms.repeat(36)),
2928        );
2929        let wall = check(&interstitial, 200, "", "https://consent.youtube.com/m", "https://www.youtube.com/@Brian");
2930        assert_eq!((wall.1.as_str(), wall.2 > 3000), ("consent_wall", true));
2931    }
2932
2933    #[test]
2934    fn content_check() {
2935        let page = |title: &str, body: &str| {
2936            format!("<html><head><title>{title}</title><script src=/a.js></script></head><body>{body}</body></html>")
2937        };
2938        let long = "Lorem ipsum dolor sit amet. ".repeat(40);
2939        let ok = page("Preise und Angebote | Shop", &format!("<h1>Preise und Angebote</h1><p>{long}</p>"));
2940        assert_eq!(check(&ok, 200, "", "https://a.example/", "").1, "ok");
2941        let shell = page("Preise und Angebote", &format!("<div id=app></div><noscript>{long}</noscript>"));
2942        assert_eq!(check(&shell, 200, "", "", "").1, "js_shell", "title words only in <head>");
2943        let cf = page("Just a moment...", "<div class=cf-chl-widget></div>");
2944        assert_eq!(check(&cf, 403, "", "", "").1, "cloudflare_wall");
2945        assert_eq!(check(&ok, 403, "cf-mitigated: challenge\n", "", "").1, "cloudflare_wall");
2946        assert_eq!(check(&page("Etsy", "<p>Blocked</p>"), 403, "x-datadome: protected\n", "", "").1, "captcha_wall");
2947        let big = page("Preise und Angebote", &format!("<h1>Preise und Angebote</h1>{}", long.repeat(2)));
2948        assert_eq!(check(&big, 200, "x-datadome: protected\n", "", "").1, "ok", "a protected site that answered");
2949        // a challenge is a wall, never a shell: the ladder goes on past it (Reddit's no-JS copy is a
2950        // hidden solver form, its rendered copy "Prove your humanity"); a shell that only loads a captcha script stays
2951        // a shell (Facebook, Instagram: the two-shell stop)
2952        let challenge = include_str!("../tests/fixtures/js-challenge.html");
2953        assert_eq!(check(challenge, 200, "", "", "").1, "captcha_wall", "the no-JS challenge form");
2954        for words in ["Prove your humanity", "Please enable JavaScript and cookies to continue"] {
2955            assert_eq!(check(&page("Reddit", &format!("<p>{words}</p>")), 200, "", "", "").1, "captcha_wall");
2956        }
2957        let app = page("Instagram", "<div id=app></div><script src=/rsrc/recaptcha.js></script>");
2958        assert_eq!(check(&app, 200, "", "", "").1, "js_shell", "a captcha script is no wall");
2959        let robot = page("Fehler", "<p>Are you a robot?</p>");
2960        assert_eq!(check(&robot, 200, "", "", "").1, "captcha_wall", "folded marker");
2961        assert_eq!(check(&ok, 403, "", "", "").1, "blocked_403");
2962        assert_eq!(check(&ok, 404, "", "", "").1, "not_found");
2963        let login = "https://x.com/login?next=/";
2964        assert_eq!(check(&shell, 200, "", login, "https://x.com/watch").1, "login_wall", "a moved landing");
2965        assert_eq!(check(&ok, 200, "", login, "https://x.com/watch").1, "ok", "a served page is no sign-in");
2966        // the wall rows run in file order before the sign-in, consent by a short notice (`consent_is_a_notice`)
2967        assert_eq!(check(&shell, 403, "", login, "https://x.com/watch").1, "blocked_403");
2968        let notice = page("YouTube", "<p>Before you continue to YouTube</p>");
2969        assert_eq!(check(&notice, 200, "", "", "").1, "consent_wall");
2970        assert_eq!(
2971            check(&page("Preise und Angebote", "<p>Before you continue</p>"), 200, "", "", "").1,
2972            "consent_wall"
2973        );
2974        assert_eq!(title_head("Preise – Shop | Brand"), "Preise");
2975        // the two no-JS bodies Google serves (Maps, Search): the title words are visible, the content is not
2976        let maps = page("Google Maps", "<noscript>Enable JavaScript to see Google Maps.</noscript>");
2977        assert_eq!(check(&maps, 200, "", "", "").1, "js_shell");
2978        let stub = page("Google Search", "If you're having trouble accessing Google Search, please click here");
2979        let q = "https://www.google.fr/search?q=lyon";
2980        assert_eq!(check(&stub, 200, "", "", q).1, "serp_empty", "a SERP is judged by its results");
2981        let hits: String =
2982            (0..5).map(|i| format!("<a href=\"/url?q=https%3A%2F%2Fsite{i}.fr%2F\">Lyon old town {i}</a>")).collect();
2983        assert_eq!(check(&page("lyon - Google Search", &hits), 200, "", "", q).1, "ok");
2984        let nav: String =
2985            (0..5).map(|i| format!("<a href=\"/p{i}\">Home</a><a href=\"#r{i}\">jump to result {i}</a>")).collect();
2986        assert_eq!(check(&page("lyon - Google Search", &nav), 200, "", "", q).1, "serp_empty", "no result rows");
2987        let bsky = page(
2988            "@mariaa.bsky.social on Bluesky",
2989            "<p>Maria mariaa.bsky.social wrote a post.</p><p>The lake froze overnight for the first time in years; we went skating at dawn.</p>\
2990             <noscript>JavaScript is required.</noscript>",
2991        );
2992        assert_eq!(check(&bsky, 200, "", "", "").1, "ok", "the post is there despite the notice");
2993        let real = page(
2994            "Preise und Angebote",
2995            &format!("<noscript>Enable JavaScript</noscript><h1>Preise und Angebote</h1>{long}"),
2996        );
2997        assert_eq!(check(&real, 200, "", "", "").1, "ok", "a notice on a long page is not a shell");
2998    }
2999
3000    /// A would-be shell (two title words, or under 800 visible chars) whose title words are not shown is a JS shell
3001    /// whatever text sits around them: nav and footer rows, a `<noscript>` notice, a footer's address, a cookie
3002    /// banner over an h1, a `role=contentinfo` footer, a `div.legal`, "requires JavaScript" beside a nav link,
3003    /// "activate scripting", "Loading Acme…".
3004    #[test]
3005    fn shell_fixtures_are_shells() {
3006        let shells = [
3007            include_str!("../tests/fixtures/shell-nav-footer.html"),
3008            include_str!("../tests/fixtures/shell-noscript.html"),
3009            include_str!("../tests/fixtures/shell-footer.html"),
3010            include_str!("../tests/fixtures/shell-blocks.html"),
3011            include_str!("../tests/fixtures/shell-notices.html"),
3012        ];
3013        let pages = shells.iter().flat_map(|f| f.split("<!-- page -->"));
3014        let codes: Vec<String> = pages.map(|h| check(h, 200, "", "", "https://acme.example/app").1).collect();
3015        assert_eq!(codes, ["js_shell"; 9]);
3016    }
3017
3018    /// A short copy with one script whose title words are not on screen (a one-word title head, a site's label) is
3019    /// the page when it shows a text of its own: one text of ≥ `paragraph_words` words outside noscript, nav,
3020    /// header, footer and aside that asks nothing of JavaScript, in ≥ `thin_chars` visible chars. One word less
3021    /// and it stays a shell. The thin net after `check` keeps the thread served (446 pruned chars).
3022    #[test]
3023    fn a_text_of_its_own_is_the_page() {
3024        let thread = include_str!("../tests/fixtures/thread-short.html");
3025        let url = "https://forum.example/item?id=1";
3026        assert_eq!(check(thread, 200, "", "", url).1, "ok", "a 16-word comment under a one-word title");
3027        let h = judge(Tier::Plain, Raw { status: 200, body: thread.into(), ..Raw::default() }, url, false, false);
3028        assert_eq!((h.ok, h.code.as_str()), (true, "ok"), "the thin net keeps it");
3029        let rows = "<li>posted in the town square by a neighbour</li>".repeat(6);
3030        let page = |text: &str| {
3031            let nav = "<nav>home new past ask show submit login</nav>";
3032            let head = "<title>Zephyr | Board</title><script src=board.js></script>";
3033            format!("<html><head>{head}</head><body>{nav}<ul>{rows}</ul><p>{text}</p></body></html>")
3034        };
3035        let twelve = "the ferry runs twice a day from the old pier in summer";
3036        let (ok, code, chars, _) = check(&page(twelve), 200, "", "", url);
3037        assert_eq!((ok, code.as_str()), (true, "ok"), "12 words, {chars} chars");
3038        let eleven = "the ferry runs twice a day from the old pier in";
3039        assert_eq!(check(&page(eleven), 200, "", "", url).1, "js_shell", "11 words: no text of its own");
3040        let chrome = page("").replace("<nav>", &format!("<nav>{twelve} "));
3041        assert_eq!(check(&chrome, 200, "", "", url).1, "js_shell", "12 words in the nav are chrome");
3042    }
3043
3044    /// On trimmed saved copies: a copy holding the page is served whatever its status or the wall
3045    /// scripts it loads; a search page by its result rows, whatever the engine's markup.
3046    #[test]
3047    fn a_copy_holding_the_page_is_served() {
3048        let so = include_str!("../tests/fixtures/served-403.html");
3049        let q = "https://qa.example.com/questions/1000/package-with-both-a-library-and-a-binary";
3050        assert_eq!(check(so, 403, "", "", q).1, "ok", "the Q&A under a 403 (was blocked_403)");
3051        let h = judge(Tier::OxyJs, Raw { status: 403, body: so.into(), ..Raw::default() }, q, false, false);
3052        assert_eq!((h.ok, h.row().why.as_str()), (true, "403"), "the status stays in the tier path");
3053        let denied = format!(
3054            "<html><head><title>Access Denied</title></head><body>Access Denied {}</body></html>",
3055            "x ".repeat(900)
3056        );
3057        assert_eq!(check(&denied, 403, "", "", "").1, "blocked_403", "1 title word is no page");
3058        let yt = include_str!("../tests/fixtures/serp-links.html");
3059        let serp = "https://www.youtube.com/results?search_query=rust+in+100+seconds";
3060        assert_eq!(check(yt, 200, "", "", serp).1, "ok", "6 result rows (was serp_empty)");
3061        let post = include_str!("../tests/fixtures/slug-served.html");
3062        let thread =
3063            "https://www.reddit.com/r/europe/comments/1tb1ts5/vorstellungsgespr%C3%A4ch_beim_energieversorger/";
3064        assert_eq!(check(post, 200, "", "", thread).1, "ok", "a site-wide title, the URL's words shown");
3065        assert_eq!(check(post, 200, "", "", "https://www.reddit.com/r/europe/").1, "cloudflare_wall");
3066        assert_eq!(check(post, 403, "", "", thread).1, "cloudflare_wall", "a short 4xx copy");
3067        // Wikipedia's missing article (saved 404, trimmed) echoes the URL's words, longer
3068        // outside its h1 (2,034 chars) than the 403 Q&A (1,767): a 404 is final, never the page
3069        let wiki = include_str!("../tests/fixtures/missing-404.html");
3070        let missing = "https://en.wikipedia.org/wiki/Rust_html_markdown_crate_zzqx";
3071        assert_eq!(check(wiki, 404, "", "", missing).1, "not_found");
3072        assert_eq!(check(wiki, 410, "", "", missing).1, "not_found");
3073    }
3074
3075    /// A tiny complete page is ok; a long nav around an empty body is thin (one title word proves nothing).
3076    #[test]
3077    fn short_pages_and_thin_bodies() {
3078        let raw = |h: String| Raw { status: 200, body: h.into_bytes(), ..Raw::default() };
3079        let tiny = "<html><head><title>Example Domain</title></head><body><p>This domain is for use in documentation \
3080                    examples without needing permission.</p></body></html>";
3081        let parses = crate::html::PARSES.with(|n| n.get());
3082        let h = judge(Tier::Plain, raw(tiny.into()), "https://example.com/", false, false);
3083        assert_eq!((h.ok, h.code.as_str()), (true, "ok"));
3084        assert_eq!(crate::html::PARSES.with(|n| n.get()) - parses, 1, "the check and the cleaner share one parse");
3085        // the real page (a league game report): 1.4k visible chars of menus, 71 chars of body
3086        let nav: String = (0..45).map(|i| format!("<li><a href=/n{i}>menu item {i}</a></li>")).collect();
3087        let shell = format!(
3088            "<html><head><title>Home - Away - League</title></head><body><nav><ul>{nav}</ul></nav>\
3089             <p>Home 81:77</p><footer><ul>{nav}</ul></footer></body></html>"
3090        );
3091        let h = judge(Tier::Plain, raw(shell), "https://league.example/g/1", false, false);
3092        assert_eq!(h.code, "thin_content", "vis {}", h.vis);
3093        // a failed answer is stored as the best copy: cleaned from the check's parse, not parsed again
3094        let parses = crate::html::PARSES.with(|n| n.get());
3095        let wall = "<html><head><title>Just a moment...</title></head><body><p>checking</p></body></html>";
3096        let mut hops = vec![judge(Tier::Plain, raw(wall.into()), "https://a.example/", false, false)];
3097        let o = outcome("https://a.example/", &mut hops, 1);
3098        assert_eq!((o.meta.code.as_str(), o.doc.is_some()), ("cloudflare_wall", true));
3099        assert_eq!(crate::html::PARSES.with(|n| n.get()) - parses, 1, "one parse for the check and the stored copy");
3100    }
3101
3102    /// A run killed between its reserve and its give-back (`pooled`) holds no floor (its lock let go,
3103    /// `cache::run_at`); its hold stays (a call it started may be billed), and the next page gets its rung. A live
3104    /// run's floor holds; a queued page's too (its lane's lock). Floors over the cap are even shares (`seed`).
3105    #[test]
3106    fn a_dead_runs_floor_goes_back() {
3107        let dir = std::env::temp_dir().join(format!("fats-pool-{}", std::process::id()));
3108        std::fs::create_dir_all(&dir).ok();
3109        let at = dir.join("u1.pool.json");
3110        let pool = Pool::from([(1, [0.0015, 0.0]), (2, [0.0015, 0.0]), (3, [0.0015, 0.001]), (4, [0.0015, 0.0])]);
3111        crate::cache::edit(&at, |p: &mut Pool| *p = pool).ok();
3112        let run = |n: usize, by: usize| {
3113            crate::cache::jsave(&dir.join(format!("u{n}.json")), &crate::cache::Detached { by, ..<_>::default() })
3114        };
3115        assert!([(1, 0), (2, 0), (3, 0), (4, 1)].iter().all(|&(n, by)| run(n, by).is_ok()));
3116        let lock = |n: usize| std::fs::File::create(dir.join(format!("u{n}.lock"))).and_then(|f| f.lock().map(|()| f));
3117        let mine = lock(1).ok();
3118        let claims_of =
3119            || claims(&at, &crate::cache::edit(&at, |p: &mut Pool| p.clone()).unwrap_or_default(), 1, false);
3120        assert_eq!(claims_of(), [(3, 0.001, ""), (4, 0.0015, " held")], "u2 and u3 died, u4 waits in u1's lane");
3121        let p = Plan { pool: Some((at.clone(), 1)), cap: 0.004, ..plan(Mode::Auto) };
3122        assert_eq!(pooled(&p, &[hop(Tier::Plain, "blocked_403")], &[]), Step::Start(Tier::Bd), "u2's floor went back");
3123        let held = lock(2).ok();
3124        let live = claims_of();
3125        assert!(live.iter().any(|c| c == &(2, 0.0015, " held")), "a live run keeps its floor: {live:?}");
3126        drop((mine, held));
3127        // 2 × $0.0015 over a $0.002 cap: an even share each, never the first page's whole floor and none for the next
3128        assert!(seed(&at, [(1, plan(Mode::Auto)), (2, plan(Mode::Auto))].into_iter(), 0.002).is_ok());
3129        let pool = crate::cache::edit(&at, |p: &mut Pool| p.clone()).unwrap_or_default();
3130        assert_eq!(pool, Pool::from([(1, [0.001, 0.0]), (2, [0.001, 0.0])]));
3131        std::fs::remove_dir_all(&dir).ok();
3132    }
3133}