Skip to main content

bsv_overlay_engine/
gasp.rs

1//! GASP — Graph Aware Sync Protocol.
2//!
3//! Defines the `GASPStorage` and `GASPRemote` traits, plus the `GASP` orchestrator
4//! that synchronizes overlay UTXOs between peers.
5//!
6//! Ported from:
7//! - `~/bsv/gasp-core/src/GASP.ts` (1,557 lines)
8//! - `~/bsv/overlay-services/src/GASP/OverlayGASPStorage.ts` (388 lines)
9//! - `~/bsv/overlay-services/src/GASP/OverlayGASPRemote.ts` (108 lines)
10
11use async_trait::async_trait;
12use tracing::{debug, error, info, warn};
13
14use crate::types::{
15    GASPInitialReply, GASPInitialRequest, GASPInitialResponse, GASPNode, GASPNodeResponse,
16    GASPOutput,
17};
18
19/// Current GASP protocol version.
20pub const GASP_VERSION: u32 = 1;
21
22/// Default sync limit per page.
23pub const DEFAULT_GASP_SYNC_LIMIT: u64 = 10000;
24
25/// Pull 100 outputs per request under the Worker's 30-second peer budget.
26/// Reference: overlay-services@480d77a src/Engine.ts:29,895 requests 10,000
27/// through src/GASP/OverlayGASPRemote.ts. Smaller requests bound each reply
28/// and allow a slow peer's completed prefix to persist across ticks.
29/// The responder's default stays unchanged for wire compatibility.
30pub const ENGINE_GASP_SYNC_PAGE_LIMIT: u64 = 100;
31
32// ============================================================================
33// Per-peer sync budgets + dead-peer quarantine (bsv-low#302)
34// ============================================================================
35
36/// PURE (bsv-low#257/#302): race `fut` against `deadline`; `None` = the
37/// deadline won and `fut` was DROPPED (its in-flight work cancelled).
38/// Injectable deadline so the control flow is natively unit-tested — the
39/// house idiom generalized out of `overlay-cloudflare`'s scheduled handler
40/// (which passes its platform `sleep_ms`) so the ENGINE's per-peer GASP
41/// budget can reuse it.
42pub async fn race_or_deadline<F, D, T>(fut: F, deadline: D) -> Option<T>
43where
44    F: std::future::Future<Output = T>,
45    D: std::future::Future<Output = ()>,
46{
47    let mut fut = std::pin::pin!(fut);
48    let mut deadline = std::pin::pin!(deadline);
49    std::future::poll_fn(move |cx| {
50        if let std::task::Poll::Ready(v) = fut.as_mut().poll(cx) {
51            return std::task::Poll::Ready(Some(v));
52        }
53        if deadline.as_mut().poll(cx).is_ready() {
54            return std::task::Poll::Ready(None);
55        }
56        std::task::Poll::Pending
57    })
58    .await
59}
60
61/// `deadline`, LATCHED: once it fell due it answers `Ready` on every poll and
62/// its inner future is never polled again (bsv-low #555, found by the
63/// delta-2 fold). The worker's sleeps are `async fn` futures, which PANIC
64/// when polled after they completed, and a per-graph deadline is polled
65/// again after it fell due (the shared resume deadline, kept for the next
66/// record; the half deadline of D2-L1).
67pub fn latched(deadline: crate::engine::SleepFuture) -> crate::engine::SleepFuture {
68    let mut inner = Some(deadline);
69    Box::pin(std::future::poll_fn(move |cx| {
70        let Some(deadline) = inner.as_mut() else {
71            return std::task::Poll::Ready(());
72        };
73        if deadline.as_mut().poll(cx).is_ready() {
74            inner = None;
75            return std::task::Poll::Ready(());
76        }
77        std::task::Poll::Pending
78    }))
79}
80
81/// What makes a deadline COOPERATIVE around a write (bsv-low #552, the lens
82/// fold's HIGH-1). `Engine::submit` is several storage writes (mark spent,
83/// delete the stale coin, insert the outputs, notify, record applied), each
84/// an await on D1, and a future dropped between two of them leaves a head
85/// chain with NO head: the old one deleted, the new one never inserted, and
86/// no applied row to say so.
87///
88/// The writer opens a [`WriteSection`] around ONE transaction's submit and
89/// asks [`SubmitGate::stop_if_due`] between two of them.
90/// [`race_or_deadline_guarded`] does not drop its future while a section is
91/// open: it notes the deadline as due and keeps polling until the section
92/// closes, so the wait is bounded by the writes of one transaction. What the
93/// deadline leaves is then a prefix of whole transactions, never part of one.
94/// The race does not bound a write that never answers: the writer does
95/// (bsv-low #559, `Engine::set_finalize_submit_budget`: the engine bounds
96/// each storage call and hook inside the section, and a call that never
97/// answers is that call's fault; the submit itself is never dropped).
98#[derive(Debug, Default)]
99pub struct SubmitGate {
100    writing: std::cell::Cell<u32>,
101    due: std::cell::Cell<bool>,
102}
103
104impl SubmitGate {
105    /// Open a section no guarded race may drop. Closed when the returned
106    /// value is dropped.
107    pub fn write_section(&self) -> WriteSection<'_> {
108        self.writing.set(self.writing.get() + 1);
109        WriteSection(self)
110    }
111
112    /// Whether a guarded race's deadline fell due while a section was open:
113    /// the race is waiting for the writer to stop.
114    pub fn deadline_is_due(&self) -> bool {
115        self.due.get()
116    }
117
118    /// The writer's question at a transaction boundary, with NO section open.
119    /// If a deadline is due this never returns: it hands the future back to
120    /// the race, which drops it on this very poll (only a guarded race sets
121    /// the flag, and it clears it when it ends).
122    pub async fn stop_if_due(&self) {
123        if self.due.get() {
124            std::future::pending::<()>().await;
125        }
126    }
127}
128
129/// An open write section of a [`SubmitGate`].
130#[must_use = "the section closes when this is dropped"]
131pub struct WriteSection<'g>(&'g SubmitGate);
132
133impl Drop for WriteSection<'_> {
134    fn drop(&mut self) {
135        self.0.writing.set(self.0.writing.get().saturating_sub(1));
136    }
137}
138
139/// [`race_or_deadline`] that never drops `fut` inside a [`WriteSection`] of
140/// `gate`. A deadline that falls due while a section is open is remembered
141/// (and shown to the writer, [`SubmitGate::deadline_is_due`]); `fut` is
142/// polled on, by its own wakers, and dropped at its first pending point
143/// outside a section. `None` then means what it meant: the deadline won.
144pub async fn race_or_deadline_guarded<F, D, T>(fut: F, deadline: D, gate: &SubmitGate) -> Option<T>
145where
146    F: std::future::Future<Output = T>,
147    D: std::future::Future<Output = ()>,
148{
149    // The flag never outlives the race that set it, however the race ends
150    // (an outer drop included): a stale one would park the next writer.
151    struct ClearDue<'g>(&'g SubmitGate);
152    impl Drop for ClearDue<'_> {
153        fn drop(&mut self) {
154            self.0.due.set(false);
155        }
156    }
157    let _clear = ClearDue(gate);
158    let mut fut = std::pin::pin!(fut);
159    let mut deadline = std::pin::pin!(deadline);
160    let mut due = false;
161    std::future::poll_fn(move |cx| {
162        if let std::task::Poll::Ready(v) = fut.as_mut().poll(cx) {
163            return std::task::Poll::Ready(Some(v));
164        }
165        if !due && deadline.as_mut().poll(cx).is_ready() {
166            due = true;
167        }
168        if due {
169            if gate.writing.get() == 0 {
170                return std::task::Poll::Ready(None);
171            }
172            // `fut` is parked inside a write: its own waker brings us back.
173            gate.due.set(true);
174        }
175        std::task::Poll::Pending
176    })
177    .await
178}
179
180/// Consecutive all-failure syncs after which a peer is QUARANTINED
181/// (bsv-low#302). At the production `*/15` cron cadence 8 consecutive
182/// failures ≈ 2 hours of unbroken unreachability — comfortably past any
183/// transient blip (deploy, restart, brief network fault, one bad tick),
184/// while still cutting a genuinely dead peer's budget burn off the same
185/// day it dies.
186pub const PEER_QUARANTINE_THRESHOLD: u64 = 8;
187
188/// Re-probe interval for a quarantined peer, seconds (6 h ≈ every 24 cron
189/// ticks). Quarantine is NEVER a deletion: once `secs_since_last_attempt`
190/// reaches this age the peer gets exactly ONE fresh sync attempt — success
191/// resets its failure count to 0 (full re-admission), failure re-arms the
192/// quarantine for another window. A peer that died transiently therefore
193/// re-admits itself automatically on the first re-probe after it recovers.
194pub const PEER_QUARANTINE_REPROBE_SECS: u64 = 6 * 3600;
195
196/// Consecutive YIELDLESS syncs of a (peer, topic) allowed before each further
197/// one is a FAILED attempt for the quarantine (bsv-low #555, the delta fold's
198/// D-M2). A sync is yieldless when the peer served it work it did not hold
199/// ([`GASPSync::graphs_attempted`] > 0) and it finalized no graph and moved no
200/// cursor; it then counts a success only because a walk PROGRESSED (a node
201/// appended), and a node is the peer's word: a hostile peer that lists one
202/// fresh fabricated UTXO a tick, serves its root and hangs on its input kept
203/// its slice for ever. Past this many in a row such a sync is a failure, so
204/// that peer is quarantined after this many plus
205/// [`PEER_QUARANTINE_THRESHOLD`] syncs (20, 5 h at `*/15`) and gets one probe
206/// per [`PEER_QUARANTINE_REPROBE_SECS`] after that. A sync that finalized a
207/// graph or moved the cursor resets the count; a quiet one leaves it.
208/// A quarantined peer is re-admitted only by such a yield (the delta-4
209/// fold's D4-L2): its sync that did not fail and yielded nothing, an empty
210/// listing at its probe included, is not recorded, so its failures stay and
211/// it is attended on each tick until it yields or fails again.
212///
213/// The bound is in SYNCS AND in TIME (the delta-2 fold's D2-M1): a yieldless
214/// sync is a failure only when the streak holds more than this many syncs
215/// AND began at least [`PEER_YIELDLESS_SECS_ALLOWED`] ago
216/// ([`yieldless_sync_failed`]). Counted in syncs alone, 12 was three hours at
217/// `*/15` and twelve minutes at LOW's one tick a minute, under the tail of a
218/// block interval: an honest peer whose only new work was #582's unproven
219/// head was quarantined while it waited for its block.
220///
221/// Why 12 and 3 h: an honest deep graph converges well inside both. The
222/// measured one (#582) is an UNPROVEN head over unproven ancestry: its root
223/// is re-asked at each resume and the pass after its block lands restarts the
224/// walk from a proven root and completes it (`root_proven`), one or two passes
225/// after a block that comes in ~10 min on average (past 3 h about once in
226/// 10^8 blocks by the exponential model, at any cadence). Walked to its end
227/// instead, 12 passes are about 150 nodes on the Cloudflare worker (15 s a
228/// pass at 1.2 s a request) and 600 on LOW's node (60 s). Applied only with a
229/// per-graph budget (`Engine::set_graph_budget`): without one no walk is
230/// deferred and the quarantine is the one of #302.
231pub const PEER_YIELDLESS_SYNCS_ALLOWED: u64 = 12;
232
233/// The AGE a yieldless streak must reach, seconds since its first yieldless
234/// sync, before a yieldless sync is a failure (3 h; the delta-2 fold's
235/// D2-M1, see [`PEER_YIELDLESS_SYNCS_ALLOWED`]). The storage keeps the
236/// streak's start ([`crate::storage::PeerYieldStreak`]) on its own clock.
237pub const PEER_YIELDLESS_SECS_ALLOWED: u64 = 3 * 3600;
238
239/// The DECAY of a yieldless streak (the delta-2 fold's D2-M1): a yieldless
240/// sync more than this long (6 h, [`PEER_QUARANTINE_REPROBE_SECS`]) after the
241/// streak's LAST yieldless sync starts a new streak (count 1, its start now)
242/// instead of adding to the old one. Quiet syncs in between leave the streak
243/// as it is (a quiet sync is not a yield), so an honest peer whose rare
244/// graphs that never land are hours apart is not counted across days. The
245/// cost, stated: a peer yieldless for 3 h, quiet for 6 h, and so on, keeps
246/// its slice during the yieldless hours (a third of its ticks at most), as
247/// #302's own accepted residual of one success in every eight.
248///
249/// Only for a peer that is NOT failed (`consecutive_failures` 0; the delta-3
250/// fold's D3-M1). This window equals the reprobe's, so the probe of a peer
251/// quarantined by this bound always came more than 6 h after its last
252/// yieldless sync: it started a fresh streak (count 1, not failed), the sync
253/// "progressed", the failures went to 0 and the quarantine lifted at every
254/// probe (half the ticks at `*/15`). The probe of a failed peer continues
255/// its streak and fails, so it gets one probe per reprobe window.
256pub const PEER_YIELDLESS_DECAY_SECS: u64 = PEER_QUARANTINE_REPROBE_SECS;
257
258/// PURE rule of the yieldless bound (bsv-low #555, the delta-2 fold's
259/// D2-M1): a yieldless sync is a FAILED attempt IFF its streak holds more
260/// than [`PEER_YIELDLESS_SYNCS_ALLOWED`] syncs AND is at least
261/// [`PEER_YIELDLESS_SECS_ALLOWED`] old. A streak of unknown age (a backend
262/// with no clock) is never past (fail-safe, as #302's unknown attempt age).
263pub fn yieldless_sync_failed(streak: &crate::storage::PeerYieldStreak) -> bool {
264    streak.yieldless_syncs > PEER_YIELDLESS_SYNCS_ALLOWED
265        && streak
266            .secs_since_first
267            .is_some_and(|secs| secs >= PEER_YIELDLESS_SECS_ALLOWED)
268}
269
270/// The NORMALIZED ORIGIN of a peer URL (bsv-low #555, the delta-2 fold's
271/// D2-M2): its host, lowercased, with no scheme, user, port, path, query or
272/// fragment, and no trailing dot. The key of a peer's quarantine and
273/// yieldless streak (the engine passes it to the three peer-health methods
274/// of [`crate::storage::Storage`]) and of its share of a storage's deferred
275/// graph ceiling (the worker's `origin` column): keyed on the URL string, one
276/// server was eight "hosts" for eight adverts (`?1`, `:8443`, a trailing
277/// slash, `#x`), each with its own share and a fresh streak. A subdomain is
278/// another host still (no public suffix list here): stated. The cursor and
279/// the deferred records stay keyed by the URL the peer is synced at.
280pub fn peer_origin(url: &str) -> String {
281    peer_authority(url).1
282}
283
284/// `(scheme, host, port)` of a peer URL: the scheme lowercased (`https`
285/// when absent), the host as [`peer_origin`] gives it, the port as written
286/// (`None` when absent, empty, or the scheme's default: `443` for `https`,
287/// `80` for `http`).
288fn peer_authority(url: &str) -> (String, String, Option<String>) {
289    let url = url.trim();
290    let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
291    let scheme = scheme.to_ascii_lowercase();
292    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
293    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
294    let (host, port) = match host_port.strip_prefix('[') {
295        // `[::1]:8443`: the bracketed address, brackets kept.
296        Some(v6) => match v6.split_once(']') {
297            Some((addr, after)) => (format!("[{addr}]"), after.strip_prefix(':')),
298            None => (host_port.to_string(), None),
299        },
300        None => match host_port.split_once(':') {
301            Some((host, port)) => (host.to_string(), Some(port)),
302            None => (host_port.to_string(), None),
303        },
304    };
305    let default_port = match scheme.as_str() {
306        "https" => "443",
307        "http" => "80",
308        _ => "",
309    };
310    let port = port.filter(|p| !p.is_empty() && *p != default_port);
311    (
312        scheme,
313        host.trim_end_matches('.').to_ascii_lowercase(),
314        port.map(str::to_string),
315    )
316}
317
318/// The peers of a SHIP-discovered topic, ONE per [`peer_origin`] (bsv-low
319/// #555, the delta-2 fold's D2-M2; restored by the delta-4 fold, D4-M1): each
320/// advertised domain is canonicalized to `scheme://host[:port]` (the scheme
321/// and host lowercased; path, query, fragment, user, a trailing dot and the
322/// scheme's default port dropped), and of the spellings of one origin the
323/// first by `https`, then no explicit port, then the string is kept. So
324/// eight adverts of one server (`/?1`, `/?2`, `/#x`, `:8443`, ...) are one
325/// peer synced once a tick, and a stranger's spelling of an honest host (a
326/// query, a dead port) cannot stand beside that host's own advert under its
327/// quarantine key. The delta-3 fold kept one peer per `scheme://host[:port]`
328/// while the failures stayed on one row per origin (D4-M1): eight adverts of
329/// dead ports of an honest host's name quarantined the honest peer, and
330/// seven were never quarantined, a slice each on every tick. The LIMIT,
331/// stated (the delta-3 lens's D3-L1): two overlays of one host on two ports,
332/// on one SHIP topic, are one peer (the default port's), so a stranger's
333/// default-port spelling displaces an honest overlay that serves only on
334/// another port. Sorted, for a stable order.
335pub fn ship_peers_by_origin<I: IntoIterator<Item = String>>(domains: I) -> Vec<String> {
336    type Rank = (bool, bool, String);
337    let mut by_origin: std::collections::BTreeMap<String, (Rank, String)> =
338        std::collections::BTreeMap::new();
339    for domain in domains {
340        let (scheme, origin, port) = peer_authority(&domain);
341        if origin.is_empty() {
342            continue;
343        }
344        let canonical = match &port {
345            Some(port) => format!("{scheme}://{origin}:{port}"),
346            None => format!("{scheme}://{origin}"),
347        };
348        let candidate = (scheme != "https", port.is_some(), canonical.clone());
349        match by_origin.get(&origin) {
350            Some((kept, _)) if *kept <= candidate => {}
351            _ => {
352                by_origin.insert(origin, (candidate, canonical));
353            }
354        }
355    }
356    let mut peers: Vec<String> = by_origin.into_values().map(|(_, url)| url).collect();
357    peers.sort();
358    peers
359}
360
361/// PURE quarantine rule (bsv-low#302): a peer is skipped IFF it has hit
362/// [`PEER_QUARANTINE_THRESHOLD`] consecutive failures AND its last attempt
363/// is younger than [`PEER_QUARANTINE_REPROBE_SECS`]. A peer with no
364/// recorded attempt (`secs_since_last_attempt == None` — pristine, or a
365/// backend without peer-health tracking) is NEVER quarantined, and an old
366/// enough last attempt always re-opens one probe — fail-safe in the
367/// "attempt more, never strand a peer forever" direction.
368///
369/// ACCEPTED RESIDUAL (bsv-low#304 gate M-3, documented — not built): a
370/// peer that ALTERNATES one success into every window of ≤7 failures
371/// resets its streak each time and is never quarantined, burning up to one
372/// per-peer budget slice (30 s) per (host, topic) per tick forever. Why
373/// accepted: (a) the burn is bounded by the per-peer budget times the
374/// configured peer set, all inside the 240 s outer step belt — the #257
375/// unbounded-hang class cannot recur; (b) sustaining it requires the peer
376/// to actually COMPLETE a real sync every few ticks, i.e. behave as a
377/// (slow) live peer — indistinguishable in principle from a genuinely
378/// flaky honest peer, which the rule must never strand; (c) LOW's money
379/// topics do not GASP-sync at all (no `sync_configuration` peers in prod),
380/// so the exposure is cron-budget noise, not a money surface. A
381/// streak-decay or success-ratio rule could narrow it later if a real
382/// abuser appears.
383pub fn peer_sync_quarantined(health: &crate::storage::PeerSyncHealth) -> bool {
384    health.consecutive_failures >= PEER_QUARANTINE_THRESHOLD
385        && health
386            .secs_since_last_attempt
387            .is_some_and(|secs| secs < PEER_QUARANTINE_REPROBE_SECS)
388}
389
390// ============================================================================
391// Deferred graphs (bsv-low #555)
392// ============================================================================
393
394/// Default per-GRAPH call budget (bsv-low #555): requests to the peer, or
395/// chain fetches, that ONE graph's walk may make in one pass before it is
396/// deferred. With [`DEFAULT_GRAPH_BUDGET_MS`]: at the 1.2 s per request
397/// measured on beta (2026-10-09, #582) 100 calls take about 120 s, so on a
398/// slow peer the time binds first (about 50 nodes a pass) and on a fast one
399/// the calls do, which also bounds how much a record grows per pass.
400pub const DEFAULT_GRAPH_BUDGET_CALLS: u32 = 100;
401
402/// Default per-GRAPH time budget, ms (bsv-low #555): half of the 120 s
403/// topic slice of LOW's node (one peer), so a deep graph takes at most half
404/// of its topic's slice and the UTXOs after it keep the other half. A caller
405/// keeps it BELOW its per-peer budget (`Engine::set_peer_sync_budget`); a
406/// graph the per-peer deadline cuts first is deferred all the same.
407pub const DEFAULT_GRAPH_BUDGET_MS: u64 = 60_000;
408
409/// Default per-GRAPH bytes budget (bsv-low #586): the bytes of the nodes ONE
410/// graph's walk may be SERVED in one pass before it is deferred, counted as
411/// the peer serves them and as a record keeps them (the hex of each node's
412/// raw transaction and of its proof, every answer counted, a repeat too).
413/// A BUDGET PER PASS, not a limit: the walk makes at least one request a
414/// pass whatever its size, and what the pass leaves is resumed.
415///
416/// 917,504 bytes: a budget per pass and nothing else (bsv-low #585). It was
417/// derived from a 1 MiB cap on a record (seven eighths of it, the lens fold's
418/// E586-L1) so that the pass it cut left a record that fitted; a record has
419/// no cap since #585 (the storage keeps one of any size, the worker in
420/// chunks), so the figure is kept for what it measures, 18 heads of 26 KB a
421/// fresh pass, and no longer sits "under" anything. A consumer may set any
422/// other ([`GraphBudget::max_bytes_fetched`]).
423pub const DEFAULT_GRAPH_BUDGET_BYTES: u64 = 917_504;
424
425/// Default per-GRAPH node budget (bsv-low #586): the nodes ONE graph's walk
426/// may APPEND in one pass before it is deferred (five times the 12 of
427/// Zanaadu's largest legitimate graph). As [`DEFAULT_GRAPH_BUDGET_BYTES`], a
428/// budget per pass that resumes; it also bounds the JSON a pass adds to a
429/// record around its nodes' hex, which the bytes limb does not count.
430pub const DEFAULT_GRAPH_BUDGET_NODES: u32 = 64;
431
432/// Reset a partial walk after this many passes (`max_passes`). If its cursor
433/// could have passed, keep a root retry obligation in the same bounded slot.
434/// One hour at a one-minute cadence, fifteen at `*/15`.
435pub const DEFERRED_GRAPH_MAX_PASSES: u32 = 60;
436
437/// The most records one (peer, topic) may hold. A new deferral past it is
438/// not saved (reason `too_many`) and its walk goes on under the per-peer
439/// budget alone, as before #555 (the lens fold's L4): a peer that serves many
440/// deep graphs costs at most 16 records. A storage may refuse a record at a
441/// ceiling of its own ([`DeferredGraphSave::AtCeiling`]), counted `too_many`
442/// too (the worker's global ceiling, the lens fold's M3). A record has NO
443/// byte bound (bsv-low #585: it had 1 MiB, `too_big`): a graph of any size
444/// is deferred and resumed whole, and the storage's ceiling is a BUDGET of
445/// room, under which a RESUMED walk keeps the record it holds.
446pub const DEFERRED_GRAPHS_PER_PEER_TOPIC: usize = 16;
447
448/// Reset a resumed partial walk after this many consecutive idle faults.
449/// Keep the root retry obligation if the cursor could have passed it. These
450/// attempts remain yieldless and count toward peer quarantine.
451pub const DEFERRED_GRAPH_MAX_IDLE_FAULTS: u32 = 3;
452
453/// Three consecutive cuts by the graph's OWN deadline (`time`) distinguish a
454/// repeatedly stalled root from a single slow response. Keep a bounded retry
455/// record meanwhile; only the third cut permits the cursor to pass a root
456/// with no fetched node. The per-PEER deadline (`peer_deadline`) is not the
457/// graph's: the graph in flight when the peer's slice ends is held at once
458/// (see [`GASPSync::defer_in_flight`]).
459pub const DEADLINE_STALL_DEFERRAL_RUNS: u32 = 3;
460
461/// How long a backend remembers an outpoint the walk refused as expired,
462/// past `max(expiry, refusal)`: seven days (engine 0.1.8). A peer keeps
463/// listing a dead advert while it is unspent there, so without the memo
464/// every run fetched its node to refuse it again (fact 3 of the 0.1.8
465/// brief: about 470 node fetches, most of a 30 s slice). With it, one fetch
466/// a week per dead outpoint; the sweep bounds the table by age.
467pub const EXPIRED_OUTPOINT_MEMO_SECS: u64 = 7 * 24 * 3600;
468
469/// The most expired roots a backend remembers for one topic: about nine
470/// times the 2,282 dead adverts of the old overlay's UHRP history. Past it
471/// the oldest rows go; a forgotten one costs one node fetch again.
472pub const EXPIRED_OUTPOINT_MEMO_MAX_ROWS: usize = 20_000;
473
474/// A root whose walk is dropped by a FAULT (not a deadline, not a bound) in
475/// this many consecutive runs is recorded unanchorable (engine 0.1.9): a
476/// record `unanchorable:<class>` the cursor passes, re-walked on the long
477/// backoff [`UNANCHORABLE_RETRY_SECS`]. Three, the deadline rule's number
478/// ([`DEADLINE_STALL_DEFERRAL_RUNS`]): one fault is the moment's (a 5xx, a
479/// rung's rate limit, a courier budget earlier graphs spent); a fault that
480/// survives three runs, each with a fresh peer slice and a fresh courier
481/// budget and each walking this root ahead of the pages, is the graph's own.
482/// Before 0.1.9 such a root held the cursor below it for ever (the 0.1.4
483/// rule) and every later output waited on a captain's hand. A held record
484/// whose RESUMED pass is dropped by such a fault counts the same runs on its
485/// own slot (engine 0.1.11): on 0.1.10 a root retry obligation whose parent
486/// no rung served was dropped and saved again as it was on every run, never
487/// struck (fact 3 of the 0.1.11 brief).
488pub const UNANCHORABLE_AFTER_FAULTED_RUNS: u32 = 3;
489
490/// How long an unanchorable root waits before its next walk: six hours. What
491/// it lacks lands on that scale or not at all: an ancestor a rung indexes
492/// once mined (minutes to an hour), a peer that gains the history, a proof.
493/// Four walks a day of each of at most [`DEFERRED_GRAPHS_PER_PEER_TOPIC`]
494/// records is 64 walks a day for a (peer, topic) at worst, against 1,440
495/// ticks a day at a one-minute cadence. A later success admits it as any
496/// root and clears the record; nothing is admitted unanchored (T2).
497pub const UNANCHORABLE_RETRY_SECS: u64 = 6 * 3600;
498
499/// Four retries, six hours apart, cover one day after an unanchorable verdict.
500/// A spent allowance is a durable fact until a new score or operator reset.
501pub const UNANCHORABLE_RETRIES: u32 = 4;
502pub const DEAD_REASON: &str = "dead:";
503
504/// The least time between two counted absences of one root (engine 0.1.15,
505/// bsv-overlay-cloudflare #56): an absence is the advertising peer's word
506/// ([`fault_class::NOT_FOUND`]), and three of them strike the root
507/// `unanchorable:not_found` only when they were asked on three runs with a
508/// gap. Sixty seconds: two of the stack's 30 s per-peer slices
509/// (`GASP_PEER_SYNC_BUDGET_MS`), one tick at its one-minute cadence, so a
510/// backfill call walking slice after slice cannot count one root three
511/// times in one breath. Until it passes the root's record costs no request
512/// and the cursor holds below it, as for any fault under the threshold.
513pub const ABSENCE_GAP_SECS: u64 = 60;
514
515/// A held (passable) record resumed this many CONSECUTIVE passes with no
516/// node appended goes to the long backoff (engine 0.1.10): it is not resumed
517/// again until [`IDLE_RESUME_RETRY_SECS`] have passed, so the resumes' shared
518/// budget goes to records that progress and the peer's slice to its page.
519/// Three, the deadline rule's number ([`DEADLINE_STALL_DEFERRAL_RUNS`]) and
520/// the idle-fault rule's ([`DEFERRED_GRAPH_MAX_IDLE_FAULTS`]): one empty
521/// pass is the moment's (a slow peer, a budget the earlier resumes spent),
522/// three in a row, each with a fresh slice, are the record's own. On 0.1.9 a
523/// root retry obligation the peer no longer serves (fact 3 of the 0.1.10
524/// brief: 14 of them, `nodes 0`, `not_held` on every run) was resumed on
525/// every tick for ever, and they took the slice the page's fresh roots
526/// needed. A resume that appends a node resets the count; one past the
527/// backoff that appends nothing goes back to it at once.
528pub const IDLE_RESUMES_BEFORE_BACKOFF: u32 = 3;
529
530/// How long a record sent to the long backoff waits before its next resume:
531/// [`UNANCHORABLE_RETRY_SECS`] (six hours), as an unanchorable root does, for
532/// the same reason: what it lacks (a peer that serves the root again, a
533/// proof, an ancestor) lands on that scale or not at all. The record is
534/// kept (bsv-low #555's resume: its cursor may have passed it) and costs
535/// four resumes a day instead of 1,440.
536pub const IDLE_RESUME_RETRY_SECS: u64 = UNANCHORABLE_RETRY_SECS;
537
538/// The share of the per-PEER sync budget the resumes of one pass may take
539/// together, in percent (engine 0.1.11): the held records are walked ahead
540/// of the page, so without a share of its own the page got what they left.
541/// The rest of the slice is the page's.
542///
543/// 33: on the stack's worker the per-peer budget is 30,000 ms
544/// (`GASP_PEER_SYNC_BUDGET_MS`) and one graph's own budget 15,000 ms
545/// (`GASP_GRAPH_BUDGET_MS`), which was the resumes' shared deadline (the lens
546/// fold's M1) and started at the opening resume, so the reads and writes of
547/// the storage between resumes (a record read, its save or drop, the
548/// settled read: about five a record) came on top of it, outside any race.
549/// The share is [`resume_share_ms`]: `min(30,000 * 33 / 100, 15,000)` =
550/// 9,900 ms, started when the held loop starts, so those storage calls are
551/// inside it. The page keeps 20,100 ms: one fresh graph's whole 15,000 ms
552/// budget and 5,100 ms for its listing pages, the finalize submits and the
553/// storage. The courier's rungs (bitails, woc, bananablocks, asked in turn)
554/// have no timeout of their own (the worker's `http_get` sets none): a rung
555/// is cut only by the deadline its step races, which inside the held loop is
556/// this share. The worker sizes a courier attempt at 500 ms
557/// (`GASP_PROOF_FETCH_BUDGET`, a planning figure, not a measurement), so the
558/// share holds about 20 attempts: about 6 resumes of fact 3's shape (a root
559/// request, a root proof ask and an ancestor's three rungs), the rest held
560/// back to the next run. A record held back by the share is not resumed, not
561/// a failed UTXO, not a stalled walk and not an idle resume.
562pub const RESUMES_SHARE_OF_PEER_BUDGET_PERCENT: u64 = 33;
563
564/// The resumes' share of a pass, ms (engine 0.1.11): the
565/// [`RESUMES_SHARE_OF_PEER_BUDGET_PERCENT`] of the per-peer budget, never
566/// more than one graph's own budget (the shared deadline before 0.1.11).
567pub fn resume_share_ms(peer_budget_ms: u64, graph_budget_ms: u64) -> u64 {
568    (peer_budget_ms.saturating_mul(RESUMES_SHARE_OF_PEER_BUDGET_PERCENT) / 100).min(graph_budget_ms)
569}
570
571/// The reason prefix of a root's record while its fault streak is under
572/// [`UNANCHORABLE_AFTER_FAULTED_RUNS`]: not passable, the cursor holds.
573pub const FAULT_RETRY_REASON: &str = "retry:fault:";
574
575/// The reason prefix of an unanchorable root's record: passable.
576pub const UNANCHORABLE_REASON: &str = "unanchorable:";
577
578/// The fault classes a dropped root is named with (engine 0.1.9).
579pub mod fault_class {
580    /// The courier (the chain ancestor fetcher, its rungs) faulted or could
581    /// not serve an ancestor.
582    pub const COURIER: &str = "courier";
583    /// Absence (engine 0.1.15, bsv-overlay-cloudflare #56): the advertising
584    /// peer answered it does not hold the root, or a transaction an
585    /// UNPROVEN node of the graph needs (`NodeNotFound`), so nothing can
586    /// anchor; or, beside it, every configured raw rung answered absent
587    /// (`DefinitiveNotFound`). One run counts once whoever said it. The
588    /// peers' word decides: a rung, when one is configured, fetches and
589    /// never strikes by itself (on 0.1.12 to 0.1.14 the rungs' absence
590    /// struck `unanchorable:not_found` at once). Three runs at least
591    /// [`super::ABSENCE_GAP_SECS`] apart strike it, as any striking class.
592    pub const NOT_FOUND: &str = "not_found";
593    /// The class a peer's `NodeNotFound` carried on 0.1.9 to 0.1.14. Kept
594    /// so the records written then read as they were; a peer's word of
595    /// absence is [`NOT_FOUND`] since 0.1.15.
596    pub const NOT_SERVED: &str = "not_served";
597    /// The peer faulted serving a node (a transport fault, a 5xx, a body
598    /// that does not parse). Named, never a strike: a peer that answers
599    /// with faults is the quarantine's to judge (bsv-low #302, #555's D-M1:
600    /// a 5xx keeps no record), not a reason to pass the roots it lists.
601    pub const PEER: &str = "peer";
602    /// A served node was refused when appended to the graph (it does not
603    /// parse or verify as the graph needs it).
604    pub const VERIFICATION: &str = "verification";
605    /// Any other failure (a storage fault of ours, a bound): named, never a
606    /// strike against the root.
607    pub const OTHER: &str = "other";
608    /// The route to the peer faulted before the peer was reached (engine
609    /// 0.2.0, #57; `GASPError::RouteFault`): named, never a strike, as it
610    /// says nothing of the root or of the peer.
611    pub const ROUTE: &str = "route";
612
613    /// Whether a fault of `class` counts a faulted run of its root: the
614    /// three of the 0.1.9 brief (the courier, an input nobody served, a
615    /// verification refusal), never a peer's fault of the moment.
616    pub fn strikes(class: &str) -> bool {
617        matches!(class, COURIER | NOT_SERVED | VERIFICATION | NOT_FOUND)
618    }
619}
620
621/// One root a sync dropped, named with why (engine 0.1.9): what the sync's
622/// accounting and the tick's summary line carry, once per (peer, root) per
623/// run.
624#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
625pub struct FaultedRoot {
626    /// The peer, filled by the engine (empty inside one `GASPSync`).
627    #[serde(default)]
628    pub peer: String,
629    /// The root outpoint.
630    pub outpoint: String,
631    /// Its class, one of [`fault_class`].
632    pub class: String,
633    /// The consecutive faulted runs its record counts (0: not recorded).
634    pub faults: u32,
635    /// Whether it is recorded unanchorable (the cursor passes it).
636    pub unanchorable: bool,
637    /// The error, cut to 160 characters.
638    pub error: String,
639    /// Why its strike was refused: `no_room` at the storage's own ceiling,
640    /// or `store_fault`; empty when written or no strike was due.
641    #[serde(default, skip_serializing_if = "String::is_empty")]
642    pub refused: String,
643}
644
645/// Why a strike was refused (engine 0.1.10), as [`FaultedRoot::refused`]
646/// names it.
647pub mod strike_refused {
648    /// No room at the storage's own ceiling. Memo eviction is not a refusal.
649    pub const NO_ROOM: &str = "no_room";
650    /// The storage faulted writing the record.
651    pub const STORE_FAULT: &str = "store_fault";
652}
653
654/// The per-graph budget of a [`GASPSync`] (bsv-low #555,
655/// `Engine::set_graph_budget`). Setting one turns deferral ON for that sync.
656pub struct GraphBudget<'a> {
657    /// Calls one graph may make in one pass ([`DEFAULT_GRAPH_BUDGET_CALLS`]).
658    pub max_calls: u32,
659    /// Bytes one graph may be served in one pass
660    /// ([`DEFAULT_GRAPH_BUDGET_BYTES`], bsv-low #586). Reached, the graph is
661    /// DEFERRED as at `max_calls` (reason `bytes`): never dropped, never
662    /// refused.
663    pub max_bytes_fetched: u64,
664    /// Nodes one graph may append in one pass
665    /// ([`DEFAULT_GRAPH_BUDGET_NODES`], bsv-low #586). Reached, the graph is
666    /// deferred (reason `nodes`).
667    pub max_nodes: u32,
668    /// A fresh deadline for ONE graph's pass ([`DEFAULT_GRAPH_BUDGET_MS`]).
669    pub deadline: Box<dyn Fn() -> crate::engine::SleepFuture + 'a>,
670    /// A fresh deadline for HALF of it (the delta-2 fold's D2-L1): a FRESH
671    /// walk that faults once this fell due, or after half its calls, has
672    /// paid for a record and keeps one. `None`: the calls alone decide.
673    pub half_deadline: Option<Box<dyn Fn() -> crate::engine::SleepFuture + 'a>>,
674}
675
676impl GraphBudget<'_> {
677    /// What one pass of one graph may spend.
678    fn pass(&self) -> PassCap {
679        PassCap {
680            calls: self.max_calls,
681            bytes: self.max_bytes_fetched,
682            nodes: self.max_nodes,
683        }
684    }
685}
686
687/// What one pass of a graph's walk may still spend of the per-graph budget's
688/// three counted limbs (its time is a deadline): calls made, bytes served,
689/// nodes appended.
690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
691struct PassCap {
692    calls: u32,
693    bytes: u64,
694    nodes: u32,
695}
696
697impl PassCap {
698    /// No bound: a sync with no per-graph budget, or a walk that goes on
699    /// under the per-peer budget alone (L4).
700    const NONE: PassCap = PassCap {
701        calls: u32::MAX,
702        bytes: u64::MAX,
703        nodes: u32::MAX,
704    };
705
706    /// Whether a limb is spent to nothing.
707    fn spent(self) -> bool {
708        self.calls == 0 || self.bytes == 0 || self.nodes == 0
709    }
710}
711
712/// The key of one held record (bsv-low #555): what a sync loads up front.
713/// The records resume independently of the peer's listing, one at a time
714/// ([`GASPStorage::get_deferred_graph`]), so at most one record is in memory
715/// at a time (the lens fold's L3: the up-front load held up to 16 of them).
716#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
717#[serde(rename_all = "camelCase")]
718pub struct DeferredGraphKey {
719    /// The root UTXO, `txid.outputIndex`.
720    pub outpoint: String,
721    /// The root UTXO's score at the peer.
722    pub score: u64,
723}
724
725/// What a storage did with a record it was asked to save (bsv-low #555).
726#[derive(Debug, Clone, Copy, PartialEq, Eq)]
727pub enum DeferredGraphSave {
728    /// Saved (replaced).
729    Saved,
730    /// Refused at a ceiling of the storage's own (the worker's global count
731    /// and byte bounds, the lens fold's M3): counted `too_many`, and the walk
732    /// goes on under the per-peer budget alone, as before #555. A BUDGET
733    /// signal, never the loss of a walk (bsv-low #585): the storage must
734    /// leave the record it HELD under that key as it was, and the engine
735    /// keeps it, so a resumed graph refused room resumes from that record at
736    /// the next pass and never walks from its root again.
737    AtCeiling,
738}
739
740/// One node a deferred walk has fetched and appended, in append order.
741#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
742#[serde(rename_all = "camelCase")]
743pub struct WalkedNode {
744    /// The node as it was appended (the root's proof hydrated, if it was).
745    pub node: GASPNode,
746    /// `txid.outputIndex` of the node that spends it; `None` for the root.
747    pub spent_by: Option<String>,
748}
749
750/// One input a deferred walk has still to ask for.
751#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
752#[serde(rename_all = "camelCase")]
753pub struct PendingInput {
754    /// `txid.outputIndex` of the input (for the root, the UTXO itself).
755    pub outpoint: String,
756    /// The graph id the request carries (the root's outpoint).
757    pub graph_id: String,
758    /// Whether the input's metadata is asked for.
759    pub metadata: bool,
760    /// `txid.outputIndex` of the node that needs it; `None` for the root.
761    pub spent_by: Option<String>,
762    /// Whether that node is PROVEN: a named input the peer does not hold is
763    /// then pruned (the D8 rule), else it fails the graph.
764    pub parent_proven: bool,
765}
766
767/// The persisted partial walk of ONE graph (bsv-low #555): one record per
768/// (peer, topic, root outpoint), REPLACED on every deferral, never appended.
769#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
770#[serde(rename_all = "camelCase")]
771pub struct DeferredGraph {
772    /// The peer the graph is walked from.
773    pub peer: String,
774    /// The topic.
775    pub topic: String,
776    /// The root UTXO, `txid.outputIndex`.
777    pub outpoint: String,
778    /// The root UTXO's score at the peer.
779    pub score: u64,
780    /// The nodes fetched so far, with their proofs, in append order.
781    pub nodes: Vec<WalkedNode>,
782    /// The inputs still to ask for, a stack (the last is asked next).
783    pub pending: Vec<PendingInput>,
784    /// Calls spent on this graph over every pass.
785    pub calls: u64,
786    /// Passes that deferred it (its age, in passes).
787    pub passes: u32,
788    /// Why it was last deferred: `calls`, `time`, `bytes`, `nodes`, `fault`,
789    /// `anchor_unavailable`, `anchor_walk_held` (the E592 lens fold: the
790    /// anchor's walk past the budget, held until the root is served proven),
791    /// `not_landed` or `peer_deadline`; for a root whose walk faulted
792    /// (engine 0.1.9) `retry:fault:<class>` under
793    /// [`UNANCHORABLE_AFTER_FAULTED_RUNS`] runs, `unanchorable:<class>` at it.
794    pub reason: String,
795    /// Whether the peer is a CONFIGURED one (`SyncTarget::Peers`), not one
796    /// `ls_ship` discovered (bsv-low #555, the delta-2 fold's D2-M2): a
797    /// storage reserves part of its ceiling for these (the worker: records
798    /// of discovered peers hold at most half of it). Set by the storage
799    /// adapter on every save; `false` in a record saved before the fold.
800    #[serde(default)]
801    pub configured: bool,
802    /// Consecutive RESUMED passes that faulted having appended no node
803    /// (the delta-2 fold's D2-M2): the record is dropped (`idle_faults`)
804    /// when it reaches [`DEFERRED_GRAPH_MAX_IDLE_FAULTS`]; a pass that
805    /// appends a node resets it.
806    #[serde(default)]
807    pub idle_faults: u32,
808    /// The cursor may pass this durable obligation. A false value also reads
809    /// records written before independent resume support.
810    #[serde(default)]
811    pub cursor_passable: bool,
812    /// Consecutive runs whose walk of this root faulted (engine 0.1.9): a
813    /// record `retry:fault:<class>` under [`UNANCHORABLE_AFTER_FAULTED_RUNS`],
814    /// `unanchorable:<class>` at it. 0 in every other record (and not
815    /// written, so their JSON is unchanged).
816    #[serde(default, skip_serializing_if = "is_zero_u32")]
817    pub faults: u32,
818    /// Unix seconds before which an unanchorable root is not walked again
819    /// ([`UNANCHORABLE_RETRY_SECS`]); 0 otherwise.
820    #[serde(default, skip_serializing_if = "is_zero_u64")]
821    pub retry_at: u64,
822    /// Consecutive passes that RESUMED this held record and appended no node
823    /// (engine 0.1.10): at [`IDLE_RESUMES_BEFORE_BACKOFF`] the record waits
824    /// [`IDLE_RESUME_RETRY_SECS`] (its `retry_at`) before its next resume; a
825    /// pass that appends a node resets it. 0 in every other record (and not
826    /// written, so their JSON is unchanged).
827    #[serde(default, skip_serializing_if = "is_zero_u32")]
828    pub idle_resumes: u32,
829    /// Retry reservations made after the unanchorable verdict, including cuts.
830    #[serde(default, skip_serializing_if = "is_zero_u32")]
831    pub unanchorable_retries: u32,
832    /// Advert expiry read by the topic manager from the content-addressed root.
833    #[serde(default, skip_serializing_if = "Option::is_none")]
834    pub expiry: Option<u64>,
835}
836
837// serde's `skip_serializing_if` passes the field by reference.
838#[allow(clippy::trivially_copy_pass_by_ref)]
839fn is_zero_u32(n: &u32) -> bool {
840    *n == 0
841}
842
843#[allow(clippy::trivially_copy_pass_by_ref)]
844fn is_zero_u64(n: &u64) -> bool {
845    *n == 0
846}
847
848impl DeferredGraph {
849    /// Whether this record counts a root's faulted runs (engine 0.1.9).
850    pub fn is_struck(&self) -> bool {
851        self.faults > 0
852            && (self.reason.starts_with(FAULT_RETRY_REASON)
853                || self.reason.starts_with(UNANCHORABLE_REASON)
854                || self.reason.starts_with(DEAD_REASON))
855    }
856
857    /// Whether this record holds an unanchorable root (passable).
858    pub fn is_unanchorable(&self) -> bool {
859        self.is_struck() && self.reason.starts_with(UNANCHORABLE_REASON)
860    }
861
862    pub fn is_dead(&self) -> bool {
863        self.is_struck() && self.reason.starts_with(DEAD_REASON)
864    }
865
866    /// Whether this held record waits out the long backoff of its idle
867    /// resumes at `now` (engine 0.1.10): not resumed, the cursor passes it.
868    /// A fault record keeps its own backoff, a record that holds the cursor
869    /// is never backed off.
870    pub fn waits_idle(&self, now: u64) -> bool {
871        !self.is_struck() && self.cursor_passable && now < self.retry_at
872    }
873
874    /// The fault class the record names, if it counts faulted runs.
875    pub fn fault_class(&self) -> Option<&str> {
876        if !self.is_struck() {
877            return None;
878        }
879        self.reason
880            .strip_prefix(DEAD_REASON)
881            .or_else(|| self.reason.strip_prefix(UNANCHORABLE_REASON))
882            .or_else(|| self.reason.strip_prefix(FAULT_RETRY_REASON))
883    }
884
885    /// The record's size as stored (its JSON): what the deferral's log line
886    /// and a storage's byte budget read. Nothing refuses a record for it
887    /// (bsv-low #585).
888    pub fn byte_size(&self) -> usize {
889        serde_json::to_vec(self).map_or(usize::MAX, |b| b.len())
890    }
891}
892
893/// Why a deferred graph's record was deleted without converging.
894#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
895#[serde(rename_all = "snake_case")]
896pub enum DropReason {
897    /// Deferred [`DEFERRED_GRAPH_MAX_PASSES`] times; the UTXO fails.
898    MaxPasses,
899    /// Past [`DEFERRED_GRAPHS_PER_PEER_TOPIC`] or the storage's ceiling: a
900    /// walk the budget cut goes on under the per-peer budget alone (L4),
901    /// else the UTXO fails. A RESUMED walk's held record is KEPT (bsv-low
902    /// #585): the count is of the pass that found no room, not of a record.
903    TooMany,
904    /// The record could not be written; as [`Self::TooMany`] (D-L2).
905    StoreFault,
906    /// A sync that ran to its end was not served the UTXO (spent at the peer).
907    NotServed,
908    /// The node already holds the UTXO (it landed another way).
909    Held,
910    /// The peer answered it does not hold an input an UNPROVEN node needs;
911    /// the UTXO fails, as in the reference.
912    NotHeld,
913    /// The root came back PROVEN: the walk restarts from it, shorter.
914    RootProven,
915    /// The anchor check refused the graph (a final verdict, the cursor moves).
916    Refused,
917    /// A resumed record whose pass ended still holding no node (a record
918    /// saved before the lens fold's H1, which saves none such); the UTXO
919    /// fails.
920    NoProgress,
921    /// [`DEFERRED_GRAPH_MAX_IDLE_FAULTS`] resumed passes in a row faulted
922    /// having appended no node (the delta-2 fold's D2-M2); the UTXO fails.
923    IdleFaults,
924}
925
926impl DropReason {
927    /// Every reason, for a caller that serves a counter per reason.
928    pub const ALL: [DropReason; 10] = [
929        Self::MaxPasses,
930        Self::TooMany,
931        Self::StoreFault,
932        Self::NotServed,
933        Self::Held,
934        Self::NotHeld,
935        Self::RootProven,
936        Self::Refused,
937        Self::NoProgress,
938        Self::IdleFaults,
939    ];
940
941    /// The reason's name, as logged and counted.
942    pub fn as_str(self) -> &'static str {
943        match self {
944            Self::MaxPasses => "max_passes",
945            Self::TooMany => "too_many",
946            Self::StoreFault => "store_fault",
947            Self::NotServed => "not_served",
948            Self::Held => "held",
949            Self::NotHeld => "not_held",
950            Self::RootProven => "root_proven",
951            Self::Refused => "refused",
952            Self::NoProgress => "no_progress",
953            Self::IdleFaults => "idle_faults",
954        }
955    }
956}
957
958/// One record dropped in a sync.
959#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
960pub struct DroppedGraph {
961    /// The root outpoint.
962    pub outpoint: String,
963    /// Why.
964    pub reason: DropReason,
965}
966
967/// What a sync did with deferred graphs (bsv-low #555).
968#[derive(Debug, Clone, Default, PartialEq)]
969pub struct DeferralStats {
970    /// Per-pass work limits that stopped a root.
971    pub root_bounds: Vec<crate::sync_load::RootBound>,
972    /// Graphs deferred (a new record, or a resumed one deferred again).
973    pub deferred: u64,
974    /// Graphs resumed from a record.
975    pub resumed: u64,
976    /// Resumed graphs that completed and landed (their record deleted).
977    pub converged: u64,
978    /// Partial walks dropped or reset without converging.
979    pub dropped: Vec<DroppedGraph>,
980    /// Walks of the sync that ended unfinished (deferred, or dropped at a
981    /// bound) having appended at least one node in their pass, or that
982    /// completed the graph (the lens fold's H1): the peer answered.
983    pub progressed: u64,
984    /// Walks of the sync that ended unfinished having appended NO node in
985    /// their pass (a hung or failing peer; the lens fold's H1). A sync whose
986    /// only outcome was these is a FAILED attempt for #302's quarantine.
987    pub stalled: u64,
988    /// Records NOT resumed this sync because the resumes of the pass had
989    /// spent their shared budget (the lens fold's M1); held, untouched, for
990    /// the next sync.
991    pub held_back: u64,
992    /// Records sent to the long backoff by this sync (engine 0.1.10): their
993    /// resume appended no node [`IDLE_RESUMES_BEFORE_BACKOFF`] passes in a
994    /// row.
995    pub backed_off: u64,
996    /// Records NOT resumed by this sync because they wait out that backoff
997    /// (no request at all; the cursor passes them).
998    pub waiting: u64,
999    /// Records whose resumed pass this sync counted one idle resume on
1000    /// (engine 0.1.11): it asked and appended nothing it kept, whatever its
1001    /// ending (a save, a drop, an error). A record a strike counted instead
1002    /// is not among them.
1003    pub idle_counted: u64,
1004}
1005
1006impl Walk {
1007    /// The counted limb this pass has spent, if any: its name is the
1008    /// deferral's reason.
1009    fn over(&self) -> Option<&'static str> {
1010        if self.calls_this_pass >= self.cap.calls {
1011            Some("calls")
1012        } else if self.bytes_this_pass >= self.cap.bytes {
1013            Some("bytes")
1014        } else if self.nodes_this_pass >= self.cap.nodes {
1015            Some("nodes")
1016        } else {
1017            None
1018        }
1019    }
1020}
1021
1022/// The walk of the graph in hand: its record (what a deferral saves) and
1023/// the per-pass state. Lives in the [`GASPSync`], OUTSIDE the walk's
1024/// future, so a deadline that drops the future leaves it whole.
1025struct Walk {
1026    record: DeferredGraph,
1027    seen: std::collections::HashSet<String>,
1028    calls_this_pass: u32,
1029    /// Bytes served to this pass (bsv-low #586; see
1030    /// [`DEFAULT_GRAPH_BUDGET_BYTES`] for what is counted).
1031    bytes_this_pass: u64,
1032    /// Nodes this pass appended (bsv-low #586).
1033    nodes_this_pass: u32,
1034    resumed: bool,
1035    /// What this pass may spend: the per-graph budget, or what the resumes
1036    /// of the pass have left of their shared one (M1); [`PassCap::NONE`]
1037    /// once a walk that cannot be kept goes on under the per-peer budget
1038    /// alone (L4).
1039    cap: PassCap,
1040    /// `record.nodes.len()` when the pass started (H1).
1041    nodes_at_start: usize,
1042    /// Whether this pass was already counted progressed or stalled.
1043    counted: bool,
1044    /// The walk could not be kept and GOES ON under the per-peer budget
1045    /// alone (L4): its drop is counted once, when it went on, and it is
1046    /// never saved again in this pass (the delta fold's D-L1: a per-peer
1047    /// deadline that then cut it counted the drop twice and asked the
1048    /// storage a second time).
1049    gone_on: bool,
1050    /// A FRESH walk's half-budget deadline, started with the walk (the
1051    /// delta-2 fold's D2-L1); `None` for a resumed walk or with no
1052    /// [`GraphBudget::half_deadline`].
1053    half: Option<crate::engine::SleepFuture>,
1054    /// The record of a root whose walk faulted in earlier runs (engine
1055    /// 0.1.9), walked again from its root: the walk holds that record's
1056    /// slot, a landing or a verdict deletes it, and a fault counts one more
1057    /// run on it ([`GASPSync::strike`]).
1058    struck: Option<Box<DeferredGraph>>,
1059}
1060
1061/// How a graph's walk ended in this pass.
1062enum WalkEnd {
1063    Expired,
1064    /// Nothing is pending: complete the graph.
1065    Done,
1066    /// Deferred, with this reason.
1067    Deferred(&'static str),
1068}
1069
1070/// What one step of the walk got.
1071enum StepOut {
1072    Expired,
1073    Pruned,
1074    Seen,
1075    Appended {
1076        node_id: String,
1077        walked: Box<WalkedNode>,
1078        children: Vec<PendingInput>,
1079    },
1080}
1081
1082/// How [`GASPSync::ingest_utxo`] ended for a UTXO.
1083enum Ingested {
1084    Retry,
1085    Expired,
1086    Completed,
1087    Deferred,
1088    /// A record not resumed: the pass's resumes spent their shared budget.
1089    HeldBack,
1090    /// An unanchorable root, held (engine 0.1.9): recorded at this walk, or
1091    /// a record whose backoff has not run out. The cursor passes it.
1092    Unanchorable,
1093    /// A held record that waits out the long backoff of its idle resumes
1094    /// (engine 0.1.10): not resumed, no request. The cursor passes it.
1095    Waiting,
1096}
1097
1098/// What a strike did (engine 0.1.10): the record that holds the count
1099/// (its faulted runs, whether it is unanchorable), and why it was refused.
1100#[derive(Debug, Clone, Copy, Default)]
1101struct Strike {
1102    held: Option<(u32, bool)>,
1103    refused: Option<&'static str>,
1104}
1105
1106impl Strike {
1107    /// Whether the root is held unanchorable: the cursor passes it.
1108    fn passable(self) -> bool {
1109        self.held.is_some_and(|(_, unanchorable)| unanchorable)
1110    }
1111}
1112
1113/// What [`GASPSync::save_walk`] did with the walk in hand.
1114enum Saved {
1115    Yes,
1116    Retry,
1117    /// Not kept, for this reason; the walk is handed back so the caller can
1118    /// go on with it (L4) or drop it.
1119    Unkept(DropReason, Box<Walk>),
1120    /// The storage faulted (counted `store_fault`, a held record deleted);
1121    /// the walk is handed back so the caller can go on with it (D-L2).
1122    Fault(GASPError, Box<Walk>),
1123    /// A RESUMED walk the storage had no room for (`AtCeiling`; counted
1124    /// `too_many`): the record it holds is KEPT as it was (bsv-low #585), and
1125    /// the walk is handed back so the caller can go on with it.
1126    Ceiling(Box<Walk>),
1127    /// The walk had already gone on (D-L1): nothing saved, nothing counted.
1128    WentOn,
1129}
1130
1131// ============================================================================
1132// GASPStorage trait
1133// ============================================================================
1134
1135/// Local storage interface for the GASP protocol.
1136///
1137/// Manages known UTXOs, temporary graph construction during sync,
1138/// and graph validation/finalization.
1139#[async_trait(?Send)]
1140pub trait GASPStorage {
1141    /// The root advert's own expiry. The adapter binds the bytes to the
1142    /// requested outpoint before interpreting a topic's expiry field.
1143    fn sync_expiry(&self, _node: &GASPNode, _outpoint: &str) -> Result<Option<u64>, GASPError> {
1144        Ok(None)
1145    }
1146
1147    /// Returns UTXOs known to be unspent since the given score/timestamp.
1148    /// Non-confirmed UTXOs should always be returned regardless of `since`.
1149    async fn find_known_utxos(
1150        &self,
1151        since: u64,
1152        limit: Option<u64>,
1153    ) -> Result<Vec<GASPOutput>, GASPError>;
1154
1155    /// Hydrate a GASP node with transaction data, proof, and optional metadata.
1156    async fn hydrate_gasp_node(
1157        &self,
1158        graph_id: &str,
1159        txid: &str,
1160        output_index: u32,
1161        metadata: bool,
1162    ) -> Result<GASPNode, GASPError>;
1163
1164    /// Determine which input transactions are needed to validate this node.
1165    /// Returns None if no additional inputs are needed.
1166    async fn find_needed_inputs(
1167        &self,
1168        node: &GASPNode,
1169    ) -> Result<Option<GASPNodeResponse>, GASPError>;
1170
1171    /// Append a node to a temporary graph being constructed during sync.
1172    /// `spent_by` is the "txid.outputIndex" of the node that spent this one (if not the root).
1173    async fn append_to_graph(
1174        &self,
1175        node: &GASPNode,
1176        spent_by: Option<&str>,
1177    ) -> Result<(), GASPError>;
1178
1179    /// Validate that the graph's anchor (root) references only proven or known transactions.
1180    async fn validate_graph_anchor(&self, graph_id: &str) -> Result<(), GASPError>;
1181
1182    /// Finalize a graph — commit the synced UTXO and its ancestors to permanent storage.
1183    async fn finalize_graph(&self, graph_id: &str) -> Result<(), GASPError>;
1184
1185    /// Discard a temporary graph that failed validation.
1186    async fn discard_graph(&self, graph_id: &str) -> Result<(), GASPError>;
1187
1188    /// The keys of the deferred graphs of this (peer, topic), lowest score
1189    /// first (bsv-low #555). REQUIRED, as the three below (the lens fold's
1190    /// M2): a storage that keeps no records says so here, by answering none
1191    /// and refusing every save, and its graphs past the budget then fail.
1192    async fn load_deferred_graphs(&self) -> Result<Vec<DeferredGraphKey>, GASPError>;
1193
1194    /// The record of the graph rooted at `outpoint`, if one is held.
1195    async fn get_deferred_graph(&self, outpoint: &str) -> Result<Option<DeferredGraph>, GASPError>;
1196
1197    /// Save (replace) the record of one deferred graph.
1198    async fn save_deferred_graph(
1199        &self,
1200        record: &DeferredGraph,
1201    ) -> Result<DeferredGraphSave, GASPError>;
1202
1203    /// Batched compact facts for a page, or due facts and maintenance with None.
1204    /// Standalone adapters may have no memo; engine adapters must forward it.
1205    async fn read_fault_memos(
1206        &self,
1207        _outpoints: Option<&[String]>,
1208    ) -> Result<crate::fault_memo::FaultMemoBatch, GASPError> {
1209        Ok(crate::fault_memo::FaultMemoBatch::default())
1210    }
1211
1212    /// Atomically claim the next retry. A storage without retry support declines.
1213    async fn reserve_unanchorable_retry(&self, _record: &DeferredGraph) -> Result<bool, GASPError> {
1214        Ok(false)
1215    }
1216
1217    /// Delete the record of the graph rooted at `outpoint`.
1218    async fn delete_deferred_graph(&self, outpoint: &str) -> Result<(), GASPError>;
1219
1220    /// Remember a root refused as expired at `expiry` (engine 0.1.8), so a
1221    /// later sync skips it with no node fetch. Default: nothing kept, the
1222    /// walk fetches and refuses it again (fail-safe).
1223    async fn remember_expired(&self, _outpoint: &str, _expiry: u64) -> Result<(), GASPError> {
1224        Ok(())
1225    }
1226
1227    /// Of `outpoints`, those remembered as expired. Default: none.
1228    async fn remembered_expired(&self, _outpoints: &[String]) -> Result<Vec<String>, GASPError> {
1229        Ok(Vec::new())
1230    }
1231}
1232
1233// ============================================================================
1234// GASPRemote trait
1235// ============================================================================
1236
1237/// Communication interface with a foreign GASP peer.
1238#[async_trait(?Send)]
1239pub trait GASPRemote {
1240    /// Send an initial request and get the peer's initial response.
1241    async fn get_initial_response(
1242        &self,
1243        request: &GASPInitialRequest,
1244    ) -> Result<GASPInitialResponse, GASPError>;
1245
1246    /// Send our initial response and get the peer's reply.
1247    async fn get_initial_reply(
1248        &self,
1249        response: &GASPInitialResponse,
1250    ) -> Result<GASPInitialReply, GASPError>;
1251
1252    /// Request a specific node from the peer.
1253    async fn request_node(
1254        &self,
1255        graph_id: &str,
1256        txid: &str,
1257        output_index: u32,
1258        metadata: bool,
1259    ) -> Result<GASPNode, GASPError>;
1260
1261    /// Submit a node to the peer and get back which inputs they need.
1262    async fn submit_node(&self, node: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError>;
1263}
1264
1265// ============================================================================
1266// GASPRemoteFactory trait
1267// ============================================================================
1268
1269/// Factory for creating `GASPRemote` instances for specific peers.
1270///
1271/// The Engine holds an optional factory. Platform-specific crates (like
1272/// overlay-cloudflare) provide an implementation that creates HTTP-based
1273/// remotes.
1274pub trait GASPRemoteFactory {
1275    /// Create a `GASPRemote` for the given peer URL and topic.
1276    fn create_remote(&self, peer_url: &str, topic: &str) -> Box<dyn GASPRemote>;
1277}
1278
1279// ============================================================================
1280// AncestorFetcher trait (OPT-IN, OFF by default)
1281// ============================================================================
1282
1283/// Optional chain-backed ancestor fetcher for GASP ingest self-healing.
1284///
1285/// **OPT-IN / OFF BY DEFAULT.** When a peer (e.g. legacy TS beta) cannot serve
1286/// a needed ancestor node during graph ingest (it returns HTTP 400 "Incomplete
1287/// SPV data!" because its stored BEEF is minimal), the orchestrator normally
1288/// abandons that graph. If — and ONLY if — an `AncestorFetcher` is configured,
1289/// `process_incoming_node` falls back to fetching the ancestor's raw tx from
1290/// chain (e.g. WhatsOnChain) and synthesizing a no-proof `GASPNode` that the
1291/// existing recursion stitches into the graph.
1292///
1293/// This is a deliberate one-time-migration escape hatch. Production must NOT
1294/// configure a fetcher: when the fetcher is `None` the ingest path is
1295/// byte-identical to today (peer errors propagate / are swallowed upstream).
1296///
1297/// The orchestrator stays platform-agnostic; the concrete WoC/`worker::Fetch`
1298/// implementation lives in the platform crate (e.g. zanaadu `overlay`), never
1299/// in this engine crate (no `reqwest`/`std::time` — must stay wasm-clean).
1300#[async_trait(?Send)]
1301pub trait AncestorFetcher {
1302    /// Reset invocation-local retry caches before a new sync.
1303    fn begin_sync(&self) {}
1304
1305    /// Fetch an ancestor transaction by txid from chain.
1306    ///
1307    /// Returns the raw tx hex plus, when the ancestor is mined, its BUMP merkle
1308    /// proof hex. A proven node ends the walk unless its topic manager names
1309    /// inputs needed for overlay history. Managers naming nothing still stop
1310    /// at the first proven layer. Managers needing history select those inputs
1311    /// instead of walking every funding/fee input back toward coinbase.
1312    ///
1313    /// The transaction DAG (no cycles), `seen` keyed by `txid.outputIndex`,
1314    /// the already-known strip, and the manager naming nothing at genesis
1315    /// bound the walk. There is no node cap, matching the reference's undefined
1316    /// `maxNodesInGraph` in `Engine.startGASPSync`. A per-peer budget drops the
1317    /// sync future at its deadline: the graphs finalized before it stay
1318    /// admitted (bsv-low #552, [`FinalizedGraphHook`]), the graph in flight
1319    /// is lost whole and walked again by the next sync, unless a per-graph
1320    /// budget is set (bsv-low #555, `Engine::set_graph_budget`): then a walk
1321    /// past either budget is deferred with its fetched nodes kept and resumed
1322    /// by the next sync, so ONE graph deeper than a pass converges over
1323    /// passes. Without it such a graph still never completes.
1324    ///
1325    /// The implementation MUST verify that the returned bytes hash to the
1326    /// requested `txid` before returning them (integrity check) so a
1327    /// malicious/garbled response cannot inject a forged ancestor.
1328    async fn fetch_ancestor(&self, txid: &str) -> Result<FetchedAncestor, GASPError>;
1329
1330    /// Fetch (and chaintracks-verify) ONLY the merkle BUMP for `txid`, WITHOUT
1331    /// fetching the raw tx.
1332    ///
1333    /// The proof-completion passes (`complete_missing_proofs`, the LOW pot-store
1334    /// tick) already hold the raw in the stored BEEF, so the raw fetch that
1335    /// [`Self::fetch_ancestor`] performs is a redundant network round-trip there
1336    /// — and a free-tier WhatsOnChain raw fetch 429s (#192/#193). This method is
1337    /// the raw-free path.
1338    ///
1339    /// Default: delegate to `fetch_ancestor` and drop the raw, so a fetcher that
1340    /// only implements `fetch_ancestor` keeps working unchanged. The production
1341    /// `ChainProofFetcher` overrides it to skip the raw fetch entirely. Returns
1342    /// `None` for an unmined/unverifiable tx (fail-closed), never an error.
1343    async fn verified_proof_for(&self, txid: &str) -> Option<String> {
1344        self.fetch_ancestor(txid).await.ok().and_then(|a| a.proof)
1345    }
1346
1347    /// Like [`Self::verified_proof_for`], but a TRANSPORT/READ FAULT stays
1348    /// distinguishable (bsv-low#304 gate M-5): `Err` = the proof source or
1349    /// header source READ failed (e.g. a chaintracks call starved at the
1350    /// invocation's subrequest wall) — retryable, NOT a chain verdict;
1351    /// `Ok(None)` = honestly no verified proof yet. Money-relevant callers
1352    /// (the spend-confirmation chaser) surface + count the fault so a
1353    /// starved tick is visible instead of masquerading as "not mined yet".
1354    /// Default: wrap `verified_proof_for` (which never faults) — existing
1355    /// fetchers keep their semantics unchanged.
1356    async fn verified_proof_for_detailed(&self, txid: &str) -> Result<Option<String>, String> {
1357        Ok(self.verified_proof_for(txid).await)
1358    }
1359
1360    /// bsv-low #451 slice B (2026-09-17): like [`Self::verified_proof_for_detailed`], but the ladder asks EVERY
1361    /// rung — no per-pass short-circuit on the broadcaster's "held unmined" word. The completion passes may stop
1362    /// early (a fresh unmined word from Arcade means no courier holds a proof yet; the next tick asks again), but
1363    /// a caller that ACTS on `Ok(None)` this pass — the reorg re-anchor, which demotes a refuted row it could not
1364    /// re-prove; the unmined-ancestry walk, which treats an unproven ancestor as a branch to keep walking — must
1365    /// hear the couriers too (the delta-verify's LOW-A). Default: the detailed ask (a fetcher with no short-circuit
1366    /// has nothing to skip).
1367    async fn verified_proof_for_exhaustive(&self, txid: &str) -> Result<Option<String>, String> {
1368        self.verified_proof_for_detailed(txid).await
1369    }
1370
1371    /// bsv-low M19B-G1 round 2 (review MED-2): the ladder's REMAINING
1372    /// per-invocation budget, when it keeps one (`None` = unbounded, or not
1373    /// known). A budgeted ladder answers `Ok(None)` to every ask once its
1374    /// budget is spent, which a caller must not read as "no courier serves a
1375    /// proof": it checks this first and leaves the row for a fresh budget.
1376    fn budget_remaining(&self) -> Option<u32> {
1377        None
1378    }
1379
1380    /// Verify that `bump_hex` is a chaintracks-valid merkle proof for `txid`.
1381    ///
1382    /// Used by proof completion to re-check a STORED structural bump before
1383    /// trusting its `has_proof` flag: a structural bump admitted WITHOUT SPV (or
1384    /// forged) must never be latched-proven and trimmed on (#192/#193). Default:
1385    /// fail-closed `false` — a fetcher with no header source can prove nothing.
1386    /// The production `ChainProofFetcher` overrides it against chaintracks.
1387    async fn verify_proof(&self, txid: &str, bump_hex: &str) -> bool {
1388        let _ = (txid, bump_hex);
1389        false
1390    }
1391
1392    /// Which txid spends `txid:vout`, per an EXTERNAL INDEXER — a HINT, never
1393    /// a verdict (bsv-low 2026-08-18, the displaced-spender reconcile). The
1394    /// caller must independently prove the hint before acting on it:
1395    /// [`Self::spender_binding_raw`] (the bytes really spend the outpoint)
1396    /// and [`Self::verified_proof_for_detailed`] (the spender is MINED, root
1397    /// verified against our PoW-anchored headers). An indexer can therefore
1398    /// only ever point at the REAL confirmed spender — pointing anywhere else
1399    /// fails one of the two proofs and changes nothing.
1400    ///
1401    /// Default `Ok(None)` — unknown — so every existing implementation keeps
1402    /// compiling AND keeps today's behavior (no resolution, fail-closed).
1403    async fn resolve_spender(&self, _txid: &str, _vout: u32) -> Result<Option<String>, String> {
1404        Ok(None)
1405    }
1406
1407    /// bsv-low (2026-09-04) — the SCRIPTHASH-HISTORY rung: the txids a
1408    /// courier's script-history index lists for `scripthash_le_hex` OTHER
1409    /// than `funding_txid` (newest first, a few at most). A pot's covenant
1410    /// script is unique to that pot, so its history is exactly
1411    /// `[funding, spender]` and the answer is the spender CANDIDATE; the
1412    /// caller BINDS it with [`spender_binding_raw`] before believing it. This
1413    /// rung survives a provider retiring its per-output spend endpoint
1414    /// (Bitails, pruned mode, 2026-09). `Err` = every rung faulted; an empty
1415    /// `Ok` = the indexes answered and list no other tx. Default: no index.
1416    ///
1417    /// [`spender_binding_raw`]: AncestorFetcher::spender_binding_raw
1418    async fn resolve_spender_by_script(
1419        &self,
1420        _scripthash_le_hex: &str,
1421        _funding_txid: &str,
1422    ) -> Result<Vec<String>, String> {
1423        Ok(Vec::new())
1424    }
1425
1426    /// bsv-low (2026-09-04): an output's LOCKING SCRIPT by outpoint from a
1427    /// courier's output index (BananaBlocks `/txo/{txid}/{vout}`) — the
1428    /// scripthash rung's script source when no BEEF is stored for the row.
1429    /// `Ok(None)` = the index never saw it. Default: no such index.
1430    async fn output_script_hint(&self, _txid: &str, _vout: u32) -> Result<Option<Vec<u8>>, String> {
1431        Ok(None)
1432    }
1433
1434    /// `spender`'s raw tx hex — fetched CONTENT-ADDRESSED (the bytes must
1435    /// hash to `spender`) — returned iff those bytes carry an input spending
1436    /// exactly `txid:vout`. This is the binding that turns
1437    /// [`Self::resolve_spender`]'s hint into a fact, and the caller gets the
1438    /// PROVEN bytes back so it can derive further facts from them (bytes
1439    /// finality, a durable BEEF) without a second fetch. `Ok(None)` = the
1440    /// bytes were read and do NOT bind (a lying or garbled hint — refuse);
1441    /// `Err` = could not read (a fault, never a verdict). Default `Ok(None)`:
1442    /// fail-closed, an unbindable hint is a dead hint.
1443    async fn spender_binding_raw(
1444        &self,
1445        _spender: &str,
1446        _txid: &str,
1447        _vout: u32,
1448    ) -> Result<Option<String>, String> {
1449        Ok(None)
1450    }
1451}
1452
1453/// An ancestor transaction fetched from chain: its raw tx hex plus an optional
1454/// BUMP merkle proof hex (present when the tx is mined).
1455#[derive(Debug, Clone)]
1456pub struct FetchedAncestor {
1457    /// Raw transaction hex.
1458    pub raw_tx: String,
1459    /// BUMP merkle proof hex, if the ancestor is mined. When `Some`, the
1460    /// synthesized node ends the walk unless its topic manager names inputs.
1461    pub proof: Option<String>,
1462}
1463
1464// ============================================================================
1465// FinalizedGraphHook (bsv-low #552)
1466// ============================================================================
1467
1468/// Called by [`GASPSync::sync`] after EVERY incoming UTXO whose graph was
1469/// completed (finalized, or refused by the anchor check and discarded), before
1470/// the next UTXO is asked for.
1471///
1472/// The reference submits inside `finalizeGraph`, so a graph is admitted the
1473/// moment it is finalized. Here `OverlayGASPStorage::finalize_graph` only
1474/// pushes to a sink (it holds a `Storage`, not the engine), and the engine
1475/// used to drain that sink after the WHOLE sync: a sync dropped at its
1476/// per-peer budget admitted nothing. With a hook the engine drains the sink
1477/// per graph, inside the raced future, so what was finalized before the
1478/// deadline stays admitted and the next sync's known-UTXO skip and known-input
1479/// strip resume from it.
1480///
1481/// An `Err` FAILS THAT UTXO, exactly as a failed ingest does: the gap guard
1482/// keeps the cursor below it and the next sync asks for it again. The engine
1483/// answers `Err` when a finalize submit did not land (the lens fold's
1484/// MEDIUM-1). It cannot fail the sync. While the hook runs,
1485/// [`GASPSync::completed_cursor`] still sits BELOW the UTXO just completed,
1486/// so a sync dropped inside the hook asks for that UTXO again.
1487#[async_trait(?Send)]
1488pub trait FinalizedGraphHook {
1489    /// One incoming UTXO's graph was completed; drain what it finalized.
1490    async fn graph_completed(&self) -> Result<(), GASPError>;
1491}
1492
1493// ============================================================================
1494// GASP orchestrator
1495// ============================================================================
1496
1497#[derive(Default)]
1498struct PageProgress {
1499    pages: u64,
1500    advanced: bool,
1501    reached_tip: bool,
1502}
1503
1504/// GASP sync orchestrator.
1505///
1506/// Coordinates between local `GASPStorage` and a `GASPRemote` peer to
1507/// synchronize overlay UTXOs. Supports paginated sync and unidirectional mode.
1508///
1509/// The lifetime `'a` allows the storage and remote to borrow from their
1510/// environment (e.g., `OverlayGASPStorage` borrows from the Engine's storage).
1511pub struct GASPSync<'a> {
1512    expired: std::rc::Rc<std::cell::RefCell<std::collections::HashSet<String>>>,
1513    root_proofs: std::cell::RefCell<std::collections::HashMap<String, bool>>,
1514    roots_proven: std::cell::Cell<u64>,
1515    roots_unproven: std::cell::Cell<u64>,
1516    cursor_held_by: Option<(u64, String)>,
1517    cursor_after_in_flight: u64,
1518    /// The root (score, outpoint) of the graph in flight, kept OUTSIDE the
1519    /// walk's future like [`Walk`], so a per-peer deadline that drops the
1520    /// sync before the walk exists (or after a refusal took it) still names
1521    /// the graph it cut.
1522    in_flight: Option<(u64, String)>,
1523    /// New durable holds this sync saved: see [`Self::graphs_retained`].
1524    retained: std::cell::Cell<u64>,
1525    /// Held graphs this sync resumed that appended a node or converged.
1526    resumed_with_progress: std::cell::Cell<u64>,
1527    cursor_yielded: std::cell::Cell<bool>,
1528    expired_refused: std::cell::Cell<u64>,
1529    /// The expiry `root_expired` last read off a refused root, for the
1530    /// durable memo.
1531    refused_expiry: std::cell::Cell<Option<u64>>,
1532    storage: Box<dyn GASPStorage + 'a>,
1533    remote: Box<dyn GASPRemote + 'a>,
1534    /// Score of last successful interaction with this peer.
1535    pub last_interaction: u64,
1536    /// If true, only pull from remote — don't push local UTXOs.
1537    pub unidirectional: bool,
1538    log_prefix: String,
1539    /// OPT-IN / OFF BY DEFAULT chain-backed ancestor fetcher. When `None`
1540    /// (the default), a peer's `request_node` error propagates and the graph
1541    /// is abandoned upstream, except for an input NAMED by a proven node's
1542    /// topic manager that the peer answers it does not hold
1543    /// (`GASPError::NodeNotFound`), whose branch is pruned (the D8 decoy
1544    /// rule). When `Some`, ancestors come from chain instead of the peer and
1545    /// nothing is pruned: every fetcher error abandons the graph.
1546    ancestor_fetcher: Option<std::rc::Rc<dyn AncestorFetcher + 'a>>,
1547    /// Manager-named inputs whose branch was PRUNED because the peer answered
1548    /// that it does not hold them (zanaadu-v2 #314, D8), keyed
1549    /// `txid.outputIndex`. One entry is one failed round trip: an outpoint in
1550    /// this set is never asked for again in this sync, whichever parent or
1551    /// graph names it. Cleared at the start of each `sync`.
1552    pruned: std::cell::RefCell<std::collections::HashSet<String>>,
1553    /// Distinct outpoints pruned in the last `sync` (the size of `pruned`).
1554    pruned_inputs: std::cell::Cell<u64>,
1555    /// Inputs of UNPROVEN nodes the peer answered it does not hold in this
1556    /// sync (engine 0.1.15), keyed `txid.outputIndex`: needed again by
1557    /// another graph of the sync, the answer is remembered, not asked.
1558    /// Cleared at the start of each `sync`.
1559    absent: std::cell::RefCell<std::collections::HashSet<String>>,
1560    /// Graphs REFUSED by `validate_graph_anchor` and discarded in the last
1561    /// `sync` (bsv-low #551). Cleared at the start of each `sync`.
1562    discarded_graphs: std::cell::Cell<u64>,
1563    /// Graphs whose anchor walk could not run within the budget and were
1564    /// HELD (the E592 lens fold): [`GASPSync::anchor_walk_held`].
1565    anchor_walk_held: std::cell::Cell<u64>,
1566    /// Called after every completed incoming UTXO (bsv-low #552). `None`
1567    /// (the default): nothing is called and `sync` runs as it always did.
1568    finalized_hook: Option<Box<dyn FinalizedGraphHook + 'a>>,
1569    /// See [`Self::completed_cursor`].
1570    completed_cursor: u64,
1571    /// See [`Self::graph_in_flight`].
1572    graph_in_flight: bool,
1573    /// The per-graph budget (bsv-low #555). `None` (the default): no graph
1574    /// is deferred and the walk is the one before #555.
1575    graph_budget: Option<GraphBudget<'a>>,
1576    /// The roots of this (peer, topic)'s records not yet resumed in this
1577    /// sync (keys only; records are read one at a time).
1578    deferred: std::cell::RefCell<std::collections::HashSet<String>>,
1579    /// ONE deadline for every resume of the sync (the lens fold's M1), made
1580    /// at the first resume.
1581    resume_deadline: std::cell::RefCell<Option<crate::engine::SleepFuture>>,
1582    /// What every resume of the sync may still spend together (M1).
1583    resume_left: std::cell::Cell<PassCap>,
1584    /// A fresh deadline for the resumes' share of a pass (engine 0.1.11,
1585    /// [`Self::with_resume_share`]); `None`: the per-graph deadline, made at
1586    /// the resume that opens the pass, as before.
1587    resume_share: Option<Box<dyn Fn() -> crate::engine::SleepFuture + 'a>>,
1588    /// Calls made by the sync's walks so far.
1589    calls_made: std::cell::Cell<u64>,
1590    /// Bytes served to the sync's walks so far (bsv-low #586).
1591    bytes_fetched: std::cell::Cell<u64>,
1592    /// Nodes appended by the sync's walks so far (bsv-low #586).
1593    nodes_appended: std::cell::Cell<u64>,
1594    /// How many records this (peer, topic) holds in storage, its fault
1595    /// records apart (engine 0.1.10: they are counted in `fault_records`).
1596    held_records: std::cell::Cell<usize>,
1597    /// The roots of this (peer, topic)'s FAULT records known in this sync
1598    /// (engine 0.1.14), outside the partial-graph slot count: each
1599    /// held one is known when the sync reads it (every held record is read
1600    /// ahead of the pages), a new one when its strike is written.
1601    fault_records: std::cell::RefCell<std::collections::HashSet<String>>,
1602    /// See [`Self::strikes_refused`].
1603    strikes_refused: std::cell::Cell<u64>,
1604    /// The idle resumes counted on the held record the resume in hand read
1605    /// (engine 0.1.10), and the nodes it held (engine 0.1.11), before its
1606    /// pass: what its pass adds one to when it asks and keeps nothing more.
1607    /// `None` for any other walk.
1608    resume_idle: std::cell::Cell<Option<(u32, usize)>>,
1609    /// The pass in hand saved its own record ([`Self::save_walk`]): that save
1610    /// counted its idle resume, or reset the count on a node appended, so
1611    /// nothing is counted after it.
1612    pass_saved: std::cell::Cell<bool>,
1613    /// The walk of the graph in hand (see [`Walk`]).
1614    walk: std::cell::RefCell<Option<Walk>>,
1615    /// See [`Self::deferral_stats`].
1616    stats: std::cell::RefCell<DeferralStats>,
1617    /// See [`Self::graphs_attempted`].
1618    graphs_attempted: std::cell::Cell<u64>,
1619    /// The fault class of the step that last failed a walk (engine 0.1.9),
1620    /// set where the walk faults and read where its root is dropped;
1621    /// `None` for a failure that is no fault of the graph (a storage fault
1622    /// of ours, a bound).
1623    last_fault: std::cell::Cell<Option<&'static str>>,
1624    /// See [`Self::faulted_roots`].
1625    faulted: std::cell::RefCell<Vec<FaultedRoot>>,
1626    /// See [`Self::unanchorable_recorded`].
1627    unanchorable_recorded: std::cell::Cell<u64>,
1628    /// See [`Self::unanchorable_cleared`].
1629    unanchorable_cleared: std::cell::Cell<u64>,
1630    /// See [`Self::absent_struck`].
1631    absent_struck: std::cell::Cell<u64>,
1632    dead_recorded: std::cell::Cell<u64>,
1633    expired_swept: std::cell::Cell<u64>,
1634    memo_folded: std::cell::Cell<u64>,
1635    root_expiries: std::cell::RefCell<std::collections::HashMap<String, u64>>,
1636    page: PageProgress,
1637    request_stop: Option<std::rc::Rc<dyn Fn() -> bool + 'a>>,
1638}
1639
1640impl<'a> GASPSync<'a> {
1641    /// Create a new GASP sync orchestrator.
1642    ///
1643    /// The ancestor fetcher is OFF by default. Use `with_ancestor_fetcher` to
1644    /// opt in to chain-backed ancestry hydration (one-time-migration only).
1645    pub fn new(
1646        storage: Box<dyn GASPStorage + 'a>,
1647        remote: Box<dyn GASPRemote + 'a>,
1648        last_interaction: u64,
1649        log_prefix: impl Into<String>,
1650        unidirectional: bool,
1651    ) -> Self {
1652        Self {
1653            storage,
1654            remote,
1655            expired: std::rc::Rc::default(),
1656            expired_refused: std::cell::Cell::new(0),
1657            refused_expiry: std::cell::Cell::new(None),
1658            root_proofs: std::cell::RefCell::default(),
1659            roots_proven: std::cell::Cell::new(0),
1660            roots_unproven: std::cell::Cell::new(0),
1661            cursor_held_by: None,
1662            cursor_after_in_flight: last_interaction,
1663            in_flight: None,
1664            retained: std::cell::Cell::new(0),
1665            resumed_with_progress: std::cell::Cell::new(0),
1666            cursor_yielded: std::cell::Cell::new(false),
1667            last_interaction,
1668            unidirectional,
1669            log_prefix: log_prefix.into(),
1670            ancestor_fetcher: None,
1671            pruned: std::cell::RefCell::new(std::collections::HashSet::new()),
1672            pruned_inputs: std::cell::Cell::new(0),
1673            absent: std::cell::RefCell::default(),
1674            discarded_graphs: std::cell::Cell::new(0),
1675            anchor_walk_held: std::cell::Cell::new(0),
1676            finalized_hook: None,
1677            completed_cursor: last_interaction,
1678            graph_in_flight: false,
1679            graph_budget: None,
1680            deferred: std::cell::RefCell::new(std::collections::HashSet::new()),
1681            resume_deadline: std::cell::RefCell::new(None),
1682            resume_left: std::cell::Cell::new(PassCap::NONE),
1683            resume_share: None,
1684            calls_made: std::cell::Cell::new(0),
1685            bytes_fetched: std::cell::Cell::new(0),
1686            nodes_appended: std::cell::Cell::new(0),
1687            held_records: std::cell::Cell::new(0),
1688            fault_records: std::cell::RefCell::default(),
1689            strikes_refused: std::cell::Cell::new(0),
1690            resume_idle: std::cell::Cell::new(None),
1691            pass_saved: std::cell::Cell::new(false),
1692            walk: std::cell::RefCell::new(None),
1693            stats: std::cell::RefCell::new(DeferralStats::default()),
1694            graphs_attempted: std::cell::Cell::new(0),
1695            last_fault: std::cell::Cell::new(None),
1696            faulted: std::cell::RefCell::default(),
1697            unanchorable_recorded: std::cell::Cell::new(0),
1698            unanchorable_cleared: std::cell::Cell::new(0),
1699            absent_struck: std::cell::Cell::new(0),
1700            dead_recorded: std::cell::Cell::new(0),
1701            expired_swept: std::cell::Cell::new(0),
1702            memo_folded: std::cell::Cell::new(0),
1703            root_expiries: std::cell::RefCell::default(),
1704            page: PageProgress::default(),
1705            request_stop: None,
1706        }
1707    }
1708
1709    /// Share expired outpoints across the topic peers of one engine run.
1710    #[must_use]
1711    pub fn with_expired_outpoints(
1712        mut self,
1713        expired: std::rc::Rc<std::cell::RefCell<std::collections::HashSet<String>>>,
1714    ) -> Self {
1715        self.expired = expired;
1716        self
1717    }
1718
1719    /// Backfill slices stop after one page or at a caller-owned request bound.
1720    pub fn with_page_slice(mut self, stop: std::rc::Rc<dyn Fn() -> bool + 'a>) -> Self {
1721        self.request_stop = Some(stop);
1722        self
1723    }
1724    fn request_stopped(&self) -> bool {
1725        self.request_stop.as_ref().is_some_and(|stop| stop())
1726    }
1727    pub fn pages(&self) -> u64 {
1728        self.page.pages
1729    }
1730    pub fn page_advanced(&self) -> bool {
1731        self.page.advanced
1732    }
1733    pub fn reached_tip(&self) -> bool {
1734        self.page.reached_tip
1735    }
1736
1737    pub fn expired_refused(&self) -> u64 {
1738        self.expired_refused.get()
1739    }
1740
1741    pub fn roots_proven(&self) -> u64 {
1742        self.roots_proven.get()
1743    }
1744    pub fn roots_unproven(&self) -> u64 {
1745        self.roots_unproven.get()
1746    }
1747    pub fn cursor_held_by(&self) -> Option<String> {
1748        self.cursor_held_by
1749            .as_ref()
1750            .map(|(_, outpoint)| outpoint.clone())
1751    }
1752
1753    pub fn cursor_yielded(&self) -> bool {
1754        self.cursor_yielded.get()
1755    }
1756
1757    /// New durable holds the last `sync` saved holding at least one node
1758    /// the peer served (a walk past its budget, or the graph in flight at
1759    /// the per-peer deadline): work the cursor may pass because the next
1760    /// sync resumes it. A hold of nothing is not counted: the peer served
1761    /// no node of it (the hung peer of bsv-low #555's H1).
1762    pub fn graphs_retained(&self) -> u64 {
1763        self.retained.get()
1764    }
1765
1766    /// Whether the last `sync` did work beyond finalizing a graph or moving
1767    /// the cursor (engine 0.1.8): it refused an expired root not refused
1768    /// before, retained a graph or resumed one with progress. Such a sync is
1769    /// never a failed attempt. Only the refusal also ends the yieldless
1770    /// streak (see `Engine::start_gasp_sync`).
1771    pub fn did_work(&self) -> bool {
1772        self.expired_refused.get() > 0
1773            || self.retained.get() > 0
1774            || self.resumed_with_progress.get() > 0
1775    }
1776
1777    /// Held graphs the last `sync` resumed that appended at least one node
1778    /// or converged.
1779    pub fn graphs_resumed_with_progress(&self) -> u64 {
1780        self.resumed_with_progress.get()
1781    }
1782
1783    /// The roots the last `sync` dropped, each named once with its fault
1784    /// class (engine 0.1.9): what `cursor_held_by` cannot say.
1785    pub fn faulted_roots(&self) -> Vec<FaultedRoot> {
1786        self.faulted.borrow().clone()
1787    }
1788
1789    /// Roots the last `sync` recorded unanchorable: their walk faulted in
1790    /// [`UNANCHORABLE_AFTER_FAULTED_RUNS`] consecutive runs, and the cursor
1791    /// passes them from now on.
1792    pub fn unanchorable_recorded(&self) -> u64 {
1793        self.unanchorable_recorded.get()
1794    }
1795
1796    /// Roots the last `sync` struck `unanchorable:not_found` (engine 0.1.15):
1797    /// the peers' word of absence counted on [`UNANCHORABLE_AFTER_FAULTED_RUNS`]
1798    /// runs at least [`ABSENCE_GAP_SECS`] apart. Counted in
1799    /// [`Self::unanchorable_recorded`] too.
1800    pub fn absent_struck(&self) -> u64 {
1801        self.absent_struck.get()
1802    }
1803
1804    /// Roots with a fault record (unanchorable or not yet) that the last
1805    /// `sync` walked again and admitted or refused on a verdict: their
1806    /// record cleared.
1807    pub fn dead_recorded(&self) -> u64 {
1808        self.dead_recorded.get()
1809    }
1810
1811    pub fn memo_folded(&self) -> u64 {
1812        self.memo_folded.get()
1813    }
1814
1815    pub fn expired_swept(&self) -> u64 {
1816        self.expired_swept.get()
1817    }
1818
1819    pub fn unanchorable_cleared(&self) -> u64 {
1820        self.unanchorable_cleared.get()
1821    }
1822
1823    /// Strikes the last `sync` could not write at the storage's ceiling
1824    /// or on a storage fault. Each is named in
1825    /// [`Self::faulted_roots`] with its [`FaultedRoot::refused`]; a refused
1826    /// strike of a new root leaves it a gap the cursor holds below.
1827    pub fn strikes_refused(&self) -> u64 {
1828        self.strikes_refused.get()
1829    }
1830
1831    /// Know `outpoint` as a fault record of this (peer, topic) (engine
1832    /// 0.1.10): one counted among the deferred slots moves to the fault
1833    /// records. A no-op for one already known.
1834    fn know_fault_record(&self, outpoint: &str) {
1835        if self.fault_records.borrow_mut().insert(outpoint.to_string()) {
1836            self.held_records
1837                .set(self.held_records.get().saturating_sub(1));
1838        }
1839    }
1840
1841    /// A record of this (peer, topic) read from the storage: a fault record
1842    /// is known as one (engine 0.1.10).
1843    fn read_record(&self, record: Option<&DeferredGraph>) {
1844        if let Some(record) = record.filter(|r| r.is_struck()) {
1845            self.know_fault_record(&record.outpoint);
1846        }
1847    }
1848
1849    /// A record of this (peer, topic) deleted: one fewer fault record, or
1850    /// one fewer deferred slot held.
1851    fn forget_record(&self, outpoint: &str) {
1852        if !self.fault_records.borrow_mut().remove(outpoint) {
1853            self.held_records
1854                .set(self.held_records.get().saturating_sub(1));
1855        }
1856    }
1857
1858    /// Release the cursor's hold on `outpoint`: it is finished or held.
1859    fn release_hold(&mut self, outpoint: &str) {
1860        if self
1861            .cursor_held_by
1862            .as_ref()
1863            .is_some_and(|(_, held)| held == outpoint)
1864        {
1865            self.cursor_held_by = None;
1866        }
1867    }
1868
1869    fn hold_cursor(&mut self, score: u64, outpoint: &str) {
1870        if self
1871            .cursor_held_by
1872            .as_ref()
1873            .is_none_or(|(held, _)| score < *held)
1874        {
1875            self.cursor_held_by = Some((score, outpoint.to_string()));
1876        }
1877    }
1878
1879    fn root_expired(&self, node: &GASPNode, outpoint: &str) -> Result<bool, GASPError> {
1880        let now = (crate::engine::current_timestamp_ms() / 1000.0) as u64;
1881        let expiry = self.storage.sync_expiry(node, outpoint)?;
1882        if let Some(expiry) = expiry {
1883            self.root_expiries
1884                .borrow_mut()
1885                .insert(outpoint.to_string(), expiry);
1886        }
1887        let expiry = expiry.filter(|expiry| *expiry <= now);
1888        if expiry.is_some() {
1889            self.refused_expiry.set(expiry);
1890        }
1891        Ok(expiry.is_some())
1892    }
1893
1894    /// Load the remembered dead among `outpoints` into the run's memo; they
1895    /// are refused with no node fetch and are not counted again. A read
1896    /// fault is fail-safe: they are fetched and refused as before.
1897    async fn load_remembered_expired(&self, outpoints: Vec<String>) {
1898        let outpoints: Vec<String> = {
1899            let memo = self.expired.borrow();
1900            outpoints
1901                .into_iter()
1902                .filter(|o| !memo.contains(o))
1903                .collect()
1904        };
1905        if outpoints.is_empty() {
1906            return;
1907        }
1908        match self.storage.remembered_expired(&outpoints).await {
1909            Ok(dead) => self.expired.borrow_mut().extend(dead),
1910            Err(e) => warn!(
1911                "{} Could not read the remembered expired roots: {}",
1912                self.log_prefix, e
1913            ),
1914        }
1915    }
1916
1917    async fn refuse_expired(&self, outpoint: &str) -> Result<Ingested, GASPError> {
1918        let walk = self.walk.borrow_mut().take();
1919        let expiry = self.refused_expiry.take();
1920        if self.expired.borrow_mut().insert(outpoint.to_string()) {
1921            self.expired_refused.set(self.expired_refused.get() + 1);
1922            // Remembered across runs (0.1.8): the next sync skips it with no
1923            // node fetch. Best effort: a lost row costs one fetch again.
1924            if let Some(expiry) = expiry {
1925                if let Err(e) = self.storage.remember_expired(outpoint, expiry).await {
1926                    warn!(
1927                        "{} Could not remember expired root {}: {}",
1928                        self.log_prefix, outpoint, e
1929                    );
1930                }
1931            }
1932        }
1933        let _ = self
1934            .storage
1935            .discard_graph(&Self::graph_id_of(walk.as_ref(), outpoint))
1936            .await;
1937        if walk
1938            .as_ref()
1939            .is_some_and(|w| w.resumed || w.struck.is_some())
1940            || self.deferred.borrow_mut().remove(outpoint)
1941        {
1942            self.drop_record(outpoint, DropReason::Refused).await;
1943        }
1944        Ok(Ingested::Expired)
1945    }
1946
1947    /// Retire only fault facts whose own advert expired. No remote read.
1948    async fn sweep_expired_record(
1949        &self,
1950        record: Option<&DeferredGraph>,
1951    ) -> Result<bool, GASPError> {
1952        let Some(record) = record.filter(|r| r.is_unanchorable() || r.is_dead()) else {
1953            return Ok(false);
1954        };
1955        let outpoint = record.outpoint.as_str();
1956        self.read_record(Some(record));
1957        if record.expiry.is_none_or(|expiry| expiry > Self::now_secs())
1958            && !self.expired.borrow().contains(outpoint)
1959        {
1960            return Ok(false);
1961        }
1962        // Remember before deletion, so a later page cannot reopen an expired root.
1963        self.storage
1964            .remember_expired(outpoint, record.expiry.unwrap_or(Self::now_secs()))
1965            .await?;
1966        self.storage.delete_deferred_graph(outpoint).await?;
1967        self.forget_record(outpoint);
1968        self.deferred.borrow_mut().remove(outpoint);
1969        self.expired.borrow_mut().insert(outpoint.to_string());
1970        self.expired_swept.set(self.expired_swept.get() + 1);
1971        Ok(true)
1972    }
1973
1974    fn note_dead(&self, record: &DeferredGraph) {
1975        self.dead_recorded.set(self.dead_recorded.get() + 1);
1976        let mut faulted = self.faulted.borrow_mut();
1977        faulted.retain(|f| f.outpoint != record.outpoint);
1978        faulted.push(FaultedRoot {
1979            peer: String::new(),
1980            outpoint: record.outpoint.clone(),
1981            class: record.reason.clone(),
1982            faults: record.faults,
1983            unanchorable: true,
1984            error: format!("retry allowance spent: {}", record.unanchorable_retries),
1985            refused: String::new(),
1986        });
1987        warn!(
1988            "{} Root {} {} after {} retries",
1989            self.log_prefix, record.outpoint, record.reason, record.unanchorable_retries
1990        );
1991    }
1992
1993    async fn keep_unanchorable(&self, record: &DeferredGraph) -> Result<(), GASPError> {
1994        let mut kept = record.clone();
1995        kept.retry_at = Self::now_secs() + UNANCHORABLE_RETRY_SECS;
1996        if kept.unanchorable_retries >= UNANCHORABLE_RETRIES {
1997            kept.reason = format!(
1998                "{DEAD_REASON}{}",
1999                record.fault_class().unwrap_or(fault_class::OTHER)
2000            );
2001            kept.retry_at = 0;
2002        }
2003        if self.storage.save_deferred_graph(&kept).await? != DeferredGraphSave::Saved {
2004            return Err(GASPError::StorageError(
2005                "could not retain retry allowance".into(),
2006            ));
2007        }
2008        self.know_fault_record(&kept.outpoint);
2009        if kept.is_dead() && !record.is_dead() {
2010            self.note_dead(&kept);
2011        }
2012        Ok(())
2013    }
2014
2015    /// Unix seconds now, the clock of an unanchorable root's backoff.
2016    fn now_secs() -> u64 {
2017        (crate::engine::current_timestamp_ms() / 1000.0) as u64
2018    }
2019
2020    /// Mark the walk's failure with its fault class (engine 0.1.9) and hand
2021    /// the error back.
2022    fn faulted(&self, class: &'static str, error: GASPError) -> GASPError {
2023        if !matches!(error, GASPError::StorageError(_)) {
2024            self.last_fault.set(Some(class));
2025        }
2026        error
2027    }
2028
2029    /// The class of a peer's failure to serve a node: its `NodeNotFound`
2030    /// is its word that it does not hold the transaction (engine 0.1.15),
2031    /// any other failure is the moment's.
2032    fn peer_fault_class(error: &GASPError) -> &'static str {
2033        match error {
2034            GASPError::NodeNotFound(_) => fault_class::NOT_FOUND,
2035            GASPError::RouteFault { .. } => fault_class::ROUTE,
2036            _ => fault_class::PEER,
2037        }
2038    }
2039
2040    /// Name a dropped root once in this run's accounting (engine 0.1.9).
2041    fn note_faulted(
2042        &self,
2043        outpoint: &str,
2044        error: &GASPError,
2045        class: Option<&'static str>,
2046        struck: Strike,
2047    ) {
2048        let mut faulted = self.faulted.borrow_mut();
2049        if faulted.iter().any(|f| f.outpoint == outpoint) {
2050            return;
2051        }
2052        let (faults, unanchorable) = struck.held.unwrap_or((0, false));
2053        faulted.push(FaultedRoot {
2054            peer: String::new(),
2055            outpoint: outpoint.to_string(),
2056            class: class.unwrap_or(fault_class::OTHER).to_string(),
2057            faults,
2058            unanchorable,
2059            error: error.to_string().chars().take(160).collect(),
2060            refused: struck.refused.unwrap_or_default().to_string(),
2061        });
2062    }
2063
2064    /// A fresh root dropped in the page walk: count its faulted run when
2065    /// the failure is a fault and the root is the run's lowest gap, and name
2066    /// it either way. Whether it is now unanchorable (the cursor passes it).
2067    async fn strike_fresh(
2068        &self,
2069        score: u64,
2070        outpoint: &str,
2071        error: &GASPError,
2072        lowest: bool,
2073    ) -> bool {
2074        let class = self.last_fault.take();
2075        // Absence counts on every root of the run, not only the lowest
2076        // (0.1.12 for the rungs' word, 0.1.15 for the peer's): it is a
2077        // definite answer, one row of the bounded memo each (0.1.14), so a
2078        // page of absent roots passes together on its third gapped run.
2079        let struck = match class {
2080            Some(class)
2081                if (lowest || class == fault_class::NOT_FOUND)
2082                    && self.graph_budget.is_some()
2083                    && fault_class::strikes(class) =>
2084            {
2085                self.strike(score, outpoint, class, None).await
2086            }
2087            _ => Strike::default(),
2088        };
2089        self.note_faulted(outpoint, error, class, struck);
2090        struck.passable()
2091    }
2092
2093    /// A RESUMED walk of a held record dropped by a fault (engine 0.1.11):
2094    /// a root like any other, so a fault of a striking class
2095    /// ([`fault_class::strikes`]) counts a faulted run on the record's own
2096    /// slot ([`Self::strike`] with the record as `prior`: `faults`, the
2097    /// reason `retry:fault:<class>`, its score and its pass kept), and three
2098    /// make it `unanchorable:<class>`. Named in `faulted` with the count.
2099    /// `None` when no strike was written: no fault of the graph (a peer's
2100    /// fault of the moment, a storage fault, a bound), a pass that did not
2101    /// get the root (the peer no longer serves it: the record's own idle
2102    /// rule, engine 0.1.10), the record unread, or the strike refused
2103    /// (named `no_room` or `store_fault`); the caller then drops the record
2104    /// as before 0.1.11.
2105    async fn strike_resumed(
2106        &self,
2107        outpoint: &str,
2108        walk: Option<&Walk>,
2109        error: &GASPError,
2110    ) -> Option<Strike> {
2111        let class = self.last_fault.get().filter(|c| fault_class::strikes(c))?;
2112        // The root was never served this pass: the peer no longer offers
2113        // it, which says nothing of its graph.
2114        if walk.is_none_or(|w| w.record.nodes.is_empty()) {
2115            return None;
2116        }
2117        let prior = self.storage.get_deferred_graph(outpoint).await.ok()??;
2118        if prior.is_struck() {
2119            return None;
2120        }
2121        self.last_fault.set(None);
2122        let struck = self
2123            .strike(prior.score, outpoint, class, Some(&prior))
2124            .await;
2125        self.note_faulted(outpoint, error, Some(class), struck);
2126        struck.held.map(|_| struck)
2127    }
2128
2129    /// Count one more faulted run of `outpoint` (engine 0.1.9), on its
2130    /// record `prior` or on a new one: `retry:fault:<class>` (the cursor
2131    /// holds) under [`UNANCHORABLE_AFTER_FAULTED_RUNS`], `unanchorable:<class>`
2132    /// (passable, walked again after [`UNANCHORABLE_RETRY_SECS`]) at it. The
2133    /// record holds nothing but the root to ask for: the walk starts again
2134    /// from it. The storage keeps this compact fact in its bounded memo,
2135    /// separate from partial graphs. A strike that is not written (the
2136    /// storage's ceiling, a storage fault) is REFUSED: counted in
2137    /// [`Self::strikes_refused`] and named with why; a new root then stays a
2138    /// gap, a held unanchorable record stays as it was.
2139    async fn strike(
2140        &self,
2141        score: u64,
2142        outpoint: &str,
2143        class: &'static str,
2144        prior: Option<&DeferredGraph>,
2145    ) -> Strike {
2146        let refuse = |why: &'static str| {
2147            self.strikes_refused.set(self.strikes_refused.get() + 1);
2148            warn!(
2149                "{} Root {} faulted ({}): its strike was REFUSED ({}), the cursor holds (engine 0.1.10)",
2150                self.log_prefix, outpoint, class, why
2151            );
2152            Strike {
2153                // A held unanchorable record stays as it was: passable.
2154                held: prior
2155                    .filter(|r| r.is_unanchorable())
2156                    .map(|r| (r.faults, true)),
2157                refused: Some(why),
2158            }
2159        };
2160        let mut record = Self::fresh_walk(score, outpoint, PassCap::NONE).record;
2161        record.faults = prior.map_or(0, |r| r.faults).saturating_add(1);
2162        record.unanchorable_retries = prior.map_or(0, |r| r.unanchorable_retries);
2163        record.expiry = self
2164            .root_expiries
2165            .borrow()
2166            .get(outpoint)
2167            .copied()
2168            .or_else(|| prior.and_then(|r| r.expiry));
2169        // Engine 0.1.15: absence strikes on the three-run rule like every
2170        // class; on 0.1.12 to 0.1.14 the rungs' word struck at once.
2171        let unanchorable = record.faults >= UNANCHORABLE_AFTER_FAULTED_RUNS;
2172        // A record the cursor had passed stays passable (engine 0.1.11): the
2173        // strike counts its faulted runs and never takes the pass back.
2174        record.cursor_passable = unanchorable || prior.is_some_and(|r| r.cursor_passable);
2175        if unanchorable {
2176            record.reason = format!("{UNANCHORABLE_REASON}{class}");
2177            record.retry_at = Self::now_secs() + UNANCHORABLE_RETRY_SECS;
2178        } else {
2179            record.reason = format!("{FAULT_RETRY_REASON}{class}");
2180            // The next absence counts after the gap; until then the record
2181            // costs no request (engine 0.1.15).
2182            if class == fault_class::NOT_FOUND {
2183                record.retry_at = Self::now_secs() + ABSENCE_GAP_SECS;
2184            }
2185        }
2186        if unanchorable && record.unanchorable_retries >= UNANCHORABLE_RETRIES {
2187            record.reason = format!("{DEAD_REASON}{class}");
2188            record.retry_at = 0;
2189        }
2190        match self.storage.save_deferred_graph(&record).await {
2191            Ok(DeferredGraphSave::Saved) => {
2192                if record.is_dead() && !prior.is_some_and(DeferredGraph::is_dead) {
2193                    self.note_dead(&record);
2194                }
2195                // A new key holds a fault record and no deferred slot; a
2196                // held record struck on its own slot frees its deferred
2197                // slot for the fault record (engine 0.1.11); a prior fault
2198                // record was known when it was read.
2199                if prior.is_some() {
2200                    self.know_fault_record(outpoint);
2201                } else {
2202                    self.fault_records.borrow_mut().insert(outpoint.to_string());
2203                }
2204                if unanchorable && !prior.is_some_and(DeferredGraph::is_unanchorable) {
2205                    self.unanchorable_recorded
2206                        .set(self.unanchorable_recorded.get() + 1);
2207                    if class == fault_class::NOT_FOUND {
2208                        self.absent_struck.set(self.absent_struck.get() + 1);
2209                    }
2210                    warn!(
2211                        "{} Root {} UNANCHORABLE ({}): faulted {} runs in a row; the cursor passes it, walked again in {} s (engine 0.1.9)",
2212                        self.log_prefix, outpoint, class, record.faults, UNANCHORABLE_RETRY_SECS
2213                    );
2214                } else {
2215                    warn!(
2216                        "{} Root {} faulted ({}): run {} of {} (engine 0.1.9)",
2217                        self.log_prefix,
2218                        outpoint,
2219                        class,
2220                        record.faults,
2221                        UNANCHORABLE_AFTER_FAULTED_RUNS
2222                    );
2223                }
2224                Strike {
2225                    held: Some((record.faults, unanchorable)),
2226                    refused: None,
2227                }
2228            }
2229            Ok(DeferredGraphSave::AtCeiling) => refuse(strike_refused::NO_ROOM),
2230            Err(_) => refuse(strike_refused::STORE_FAULT),
2231        }
2232    }
2233
2234    /// Walk again the root of a fault record (engine 0.1.9), under this
2235    /// pass's resume allowance. An unanchorable one waits out its backoff
2236    /// (no request at all). The walk is fresh from the root and holds the
2237    /// record's slot: a landing or a verdict clears the record, a budget
2238    /// cut or a deadline replaces it with the hold it earned, and a fault
2239    /// counts one more run on it.
2240    async fn rewalk_struck(
2241        &self,
2242        utxo: &GASPOutput,
2243        outpoint: &str,
2244        mut record: DeferredGraph,
2245        deadline: &mut crate::engine::SleepFuture,
2246        cap: PassCap,
2247    ) -> Result<Ingested, GASPError> {
2248        let score = utxo.score as u64;
2249        let absent = record.fault_class() == Some(fault_class::NOT_FOUND);
2250        if record.is_dead() || (record.is_unanchorable() && Self::now_secs() < record.retry_at) {
2251            // Not asked of the peer: not an attempt for the yieldless
2252            // streak (a quiet peer holding one is never quarantined for it).
2253            self.graphs_attempted
2254                .set(self.graphs_attempted.get().saturating_sub(1));
2255            if absent {
2256                crate::meter::peer_absent_memo_hit();
2257            }
2258            debug!(
2259                "{} Unanchorable root {} waits until {} (engine 0.1.9)",
2260                self.log_prefix, outpoint, record.retry_at
2261            );
2262            return Ok(Ingested::Unanchorable);
2263        }
2264        // Engine 0.1.15: an absence counted less than ABSENCE_GAP_SECS ago
2265        // is not asked again; the run counts nothing and the cursor holds
2266        // below a root it has not passed.
2267        if !record.is_unanchorable() && Self::now_secs() < record.retry_at {
2268            self.graphs_attempted
2269                .set(self.graphs_attempted.get().saturating_sub(1));
2270            if absent {
2271                crate::meter::peer_absent_memo_hit();
2272            }
2273            debug!(
2274                "{} Absent root {} counted {} runs; the next count waits until {} (engine 0.1.15)",
2275                self.log_prefix, outpoint, record.faults, record.retry_at
2276            );
2277            return Ok(if record.cursor_passable {
2278                Ingested::Deferred
2279            } else {
2280                Ingested::Retry
2281            });
2282        }
2283        if record.is_unanchorable() {
2284            if record.unanchorable_retries >= UNANCHORABLE_RETRIES {
2285                self.keep_unanchorable(&record).await?;
2286                self.graphs_attempted
2287                    .set(self.graphs_attempted.get().saturating_sub(1));
2288                return Ok(Ingested::Unanchorable);
2289            }
2290            // Reserve before dispatch: cancellation cannot buy another retry.
2291            record.unanchorable_retries += 1;
2292            record.retry_at = Self::now_secs() + UNANCHORABLE_RETRY_SECS;
2293            if !self.storage.reserve_unanchorable_retry(&record).await? {
2294                self.graphs_attempted
2295                    .set(self.graphs_attempted.get().saturating_sub(1));
2296                return Ok(Ingested::Unanchorable);
2297            }
2298        }
2299        info!(
2300            "{} Walking root {} again after {} faulted runs ({}) (engine 0.1.9)",
2301            self.log_prefix, outpoint, record.faults, record.reason
2302        );
2303        crate::meter::walk_output();
2304        let mut walk = Self::fresh_walk(score, outpoint, cap);
2305        walk.struck = Some(Box::new(record.clone()));
2306        *self.walk.borrow_mut() = Some(walk);
2307        let ended = self.walk_graph(Some(&mut *deadline)).await;
2308        let out = self.finish_pass(outpoint, ended, deadline).await;
2309        match out {
2310            Ok(ingested)
2311                if record.is_unanchorable()
2312                    && !matches!(ingested, Ingested::Completed | Ingested::Expired) =>
2313            {
2314                self.keep_unanchorable(&record).await?;
2315                Ok(Ingested::Unanchorable)
2316            }
2317            // A stall of the graph's own deadline does not undo the record:
2318            // the empty retry `save_walk` wrote is replaced again. So for a
2319            // passable fault record struck on a held record's slot (engine
2320            // 0.1.11): the empty retry would hold the cursor it had passed.
2321            Ok(Ingested::Retry) if record.cursor_passable => {
2322                let unanchorable = record.is_unanchorable();
2323                let kept = record.clone();
2324                if let Ok(DeferredGraphSave::Saved) = self.storage.save_deferred_graph(&kept).await
2325                {
2326                    // A fault record again, not a deferred slot (0.1.10).
2327                    self.know_fault_record(outpoint);
2328                }
2329                Ok(if unanchorable {
2330                    Ingested::Unanchorable
2331                } else {
2332                    Ingested::Deferred
2333                })
2334            }
2335            Ok(ingested) => Ok(ingested),
2336            Err(error) => {
2337                self.walk.borrow_mut().take();
2338                let class = self.last_fault.take();
2339                let Some(class) = class.filter(|c| fault_class::strikes(c)) else {
2340                    // No fault of the graph's: the record stands.
2341                    self.note_faulted(
2342                        outpoint,
2343                        &error,
2344                        class,
2345                        Strike {
2346                            held: Some((record.faults, record.is_unanchorable())),
2347                            refused: None,
2348                        },
2349                    );
2350                    if record.is_unanchorable() {
2351                        self.keep_unanchorable(&record).await?;
2352                        return Ok(Ingested::Unanchorable);
2353                    }
2354                    return Err(error);
2355                };
2356                let struck = self.strike(score, outpoint, class, Some(&record)).await;
2357                self.note_faulted(outpoint, &error, Some(class), struck);
2358                if struck.passable() {
2359                    Ok(Ingested::Unanchorable)
2360                } else {
2361                    Err(error)
2362                }
2363            }
2364        }
2365    }
2366
2367    /// Bound each graph's walk and retain its pending work. A successfully
2368    /// saved hold permits cursor progress; an unsaved graph remains a gap.
2369    /// Bound the resumes of each pass by `share` (engine 0.1.11): ONE
2370    /// deadline for every held record walked ahead of the page, started when
2371    /// the held loop starts, so the page keeps the rest of the per-peer
2372    /// slice (see [`RESUMES_SHARE_OF_PEER_BUDGET_PERCENT`]). A record reached
2373    /// once it fell due is held back for the next sync. Without one the
2374    /// resumes share one per-graph deadline (the lens fold's M1).
2375    #[must_use]
2376    pub fn with_resume_share(
2377        mut self,
2378        share: Box<dyn Fn() -> crate::engine::SleepFuture + 'a>,
2379    ) -> Self {
2380        self.resume_share = Some(share);
2381        self
2382    }
2383
2384    pub fn with_graph_budget(mut self, budget: GraphBudget<'a>) -> Self {
2385        self.graph_budget = Some(budget);
2386        self
2387    }
2388
2389    /// What the last `sync` did with deferred graphs (bsv-low #555).
2390    pub fn deferral_stats(&self) -> DeferralStats {
2391        self.stats.borrow().clone()
2392    }
2393
2394    /// How many UTXOs the sync set out to ingest (a new walk, a resume, or a
2395    /// record held back): the peer served it work it did not hold. A sync
2396    /// that attempted none was quiet (bsv-low #555, the delta fold's D-M2:
2397    /// a quiet sync never counts toward [`PEER_YIELDLESS_SYNCS_ALLOWED`]).
2398    pub fn graphs_attempted(&self) -> u64 {
2399        self.graphs_attempted.get()
2400    }
2401
2402    /// Have `hook` called after every completed incoming UTXO (bsv-low #552,
2403    /// see [`FinalizedGraphHook`]). Without one `sync` is unchanged.
2404    #[must_use]
2405    pub fn with_finalized_graph_hook(mut self, hook: Box<dyn FinalizedGraphHook + 'a>) -> Self {
2406        self.finalized_hook = Some(hook);
2407        self
2408    }
2409
2410    /// The cursor that is safe to persist if `sync` stopped RIGHT NOW (its
2411    /// future dropped at a deadline; bsv-low #552). It is the gap guard's
2412    /// rule applied to completed scores: never above a completed output, and
2413    /// strictly below the lowest score of
2414    /// any UTXO of the current page not yet completed (the one in flight
2415    /// included) and of any UTXO whose ingest failed, never below the cursor
2416    /// the sync entered with. The remote serves `score >= since`, so the next
2417    /// sync is served everything this one did not finish. After a completed
2418    /// `sync` it equals `last_interaction`.
2419    ///
2420    /// `last_interaction` itself is NOT safe after a drop: it is raised to
2421    /// each UTXO's score BEFORE that UTXO is ingested, for pagination.
2422    pub fn completed_cursor(&self) -> u64 {
2423        self.completed_cursor
2424    }
2425
2426    /// Whether a graph was being fetched, walked or anchor-checked when `sync`
2427    /// last stopped: `true` only after a `sync` future dropped mid-graph
2428    /// (bsv-low #552). That graph's nodes died with the storage adapter;
2429    /// nothing of it was finalized.
2430    pub fn graph_in_flight(&self) -> bool {
2431        self.graph_in_flight
2432    }
2433
2434    /// Highest completed score below every gap, floored at the entry cursor.
2435    /// Retaining scores handles unordered pages without inventing a cursor
2436    /// between outputs or skipping an unfinished member of a score tie.
2437    fn cursor_for_completed(
2438        completed: &std::collections::BTreeSet<u64>,
2439        lowest_unfinished: Option<u64>,
2440        floor: u64,
2441    ) -> u64 {
2442        let highest = match lowest_unfinished {
2443            Some(score) => completed.range(..score).next_back(),
2444            None => completed.iter().next_back(),
2445        };
2446        highest.copied().unwrap_or(floor).max(floor)
2447    }
2448
2449    /// How many graphs this orchestrator's last `sync` discarded because
2450    /// `validate_graph_anchor` REFUSED them (a root that does not verify, or
2451    /// one the topic manager does not admit at the end of the replay; bsv-low
2452    /// #551). Nothing of a discarded graph is finalized. As in the reference
2453    /// a refused graph is not a failed UTXO: the cursor advances past it. A
2454    /// graph whose anchor could not be CHECKED
2455    /// (`GASPError::AnchorUnavailable`: a tracker or storage fault, a topic
2456    /// manager error in the replay) is not counted here: that one fails its
2457    /// UTXO and is asked for again.
2458    pub fn discarded_graphs(&self) -> u64 {
2459        self.discarded_graphs.get()
2460    }
2461
2462    /// How many graphs this orchestrator's last `sync` HELD because their
2463    /// anchor's script walk could not run within the engine's walk budget
2464    /// (`GASPError::AnchorWalkHeld`; bsv-low #592, the E592 lens fold): not
2465    /// finalized, the UTXO failed and the cursor kept below it, until the
2466    /// peer serves the root proven. Not counted in `discarded_graphs`.
2467    pub fn anchor_walk_held(&self) -> u64 {
2468        self.anchor_walk_held.get()
2469    }
2470
2471    /// How many manager-named inputs this orchestrator pruned because the
2472    /// peer answered that it does not hold them (the D8 decoy rule, see
2473    /// `process_incoming_node`). Counted per DISTINCT outpoint per `sync`
2474    /// call of this orchestrator, which talks to ONE peer: the same decoy
2475    /// seen through two peers is counted by each. A pruned branch is NOT a
2476    /// failed UTXO: the graph completes with what it has and the cursor
2477    /// advances.
2478    pub fn pruned_inputs(&self) -> u64 {
2479        self.pruned_inputs.get()
2480    }
2481
2482    /// Opt in to chain-backed ancestor hydration (OFF by default).
2483    ///
2484    /// When set, a peer's inability to serve a needed ancestor during ingest
2485    /// triggers a fallback fetch of that ancestor's raw tx from chain. This is
2486    /// a deliberate one-time-migration escape hatch — production should NOT
2487    /// call this. Without it, behavior is unchanged.
2488    #[must_use]
2489    pub fn with_ancestor_fetcher(
2490        mut self,
2491        fetcher: Option<std::rc::Rc<dyn AncestorFetcher + 'a>>,
2492    ) -> Self {
2493        self.ancestor_fetcher = fetcher;
2494        self
2495    }
2496
2497    /// Run the sync protocol with the remote peer.
2498    ///
2499    /// 1. Request remote's UTXOs since last interaction (paginated)
2500    /// 2. For each unknown UTXO, request the full graph and ingest it
2501    /// 3. If bidirectional, push our unknown UTXOs to the remote
2502    pub async fn sync(&mut self, limit: Option<u64>) -> Result<(), GASPError> {
2503        info!(
2504            "{} Starting sync. last_interaction={}",
2505            self.log_prefix, self.last_interaction
2506        );
2507        self.page.pages = 0;
2508        self.page.advanced = false;
2509        self.page.reached_tip = false;
2510        self.pruned.borrow_mut().clear();
2511        self.pruned_inputs.set(0);
2512        self.absent.borrow_mut().clear();
2513        self.expired_refused.set(0);
2514        self.root_proofs.borrow_mut().clear();
2515        self.roots_proven.set(0);
2516        self.roots_unproven.set(0);
2517        self.cursor_held_by = None;
2518        self.in_flight = None;
2519        self.retained.set(0);
2520        self.resumed_with_progress.set(0);
2521        self.cursor_yielded.set(false);
2522        self.last_fault.set(None);
2523        self.faulted.borrow_mut().clear();
2524        self.unanchorable_recorded.set(0);
2525        self.unanchorable_cleared.set(0);
2526        self.absent_struck.set(0);
2527        self.dead_recorded.set(0);
2528        self.expired_swept.set(0);
2529        self.memo_folded.set(0);
2530        self.root_expiries.borrow_mut().clear();
2531        self.strikes_refused.set(0);
2532        self.fault_records.borrow_mut().clear();
2533        self.discarded_graphs.set(0);
2534        self.anchor_walk_held.set(0);
2535        self.completed_cursor = self.last_interaction;
2536        self.graph_in_flight = false;
2537        self.walk.borrow_mut().take();
2538        *self.stats.borrow_mut() = DeferralStats::default();
2539        self.deferred.borrow_mut().clear();
2540        self.held_records.set(0);
2541        self.resume_deadline.borrow_mut().take();
2542        self.resume_left.set(
2543            self.graph_budget
2544                .as_ref()
2545                .map_or(PassCap::NONE, GraphBudget::pass),
2546        );
2547        // Load only keys here. Records are resumed independently of pages,
2548        // one at a time under the shared resume allowance. A key-read fault
2549        // conservatively reserves all slots for the records already held.
2550        let mut held_keys = Vec::new();
2551        if self.graph_budget.is_some() {
2552            let memo = self.storage.read_fault_memos(None).await?;
2553            self.memo_folded.set(memo.folded);
2554            self.expired_swept.set(memo.swept);
2555            match self.storage.load_deferred_graphs().await {
2556                Ok(keys) => {
2557                    held_keys.clone_from(&keys);
2558                    self.held_records.set(keys.len());
2559                    self.deferred
2560                        .borrow_mut()
2561                        .extend(keys.into_iter().map(|k| k.outpoint));
2562                }
2563                Err(e) => {
2564                    self.held_records.set(DEFERRED_GRAPHS_PER_PEER_TOPIC);
2565                    warn!(
2566                        "{} Could not read the deferred graphs (bsv-low #555): {}",
2567                        self.log_prefix, e
2568                    );
2569                }
2570            }
2571            for record in memo.records {
2572                held_keys.retain(|key| key.outpoint != record.outpoint);
2573                self.fault_records
2574                    .borrow_mut()
2575                    .insert(record.outpoint.clone());
2576                self.deferred.borrow_mut().insert(record.outpoint.clone());
2577                held_keys.push(DeferredGraphKey {
2578                    outpoint: record.outpoint,
2579                    score: record.score,
2580                });
2581            }
2582            held_keys.sort_by(|a, b| (a.score, &a.outpoint).cmp(&(b.score, &b.outpoint)));
2583        }
2584
2585        // Track what we already know
2586        let local_utxos = self.storage.find_known_utxos(0, None).await?;
2587        let mut known_outpoints: std::collections::HashSet<String> = local_utxos
2588            .iter()
2589            .map(|u| format!("{}.{}", u.txid, u.output_index))
2590            .collect();
2591        let mut shared_outpoints: std::collections::HashSet<String> =
2592            std::collections::HashSet::new();
2593
2594        // The cursor we entered with. The persisted cursor must never regress
2595        // below it (a failed RE-ingest of an already-synced range is not a new
2596        // gap), and the gap-guard below is floored at it.
2597        let initial_interaction = self.last_interaction;
2598        let mut completed_scores = std::collections::BTreeSet::new();
2599        // Lowest score of any UTXO whose graph ingest FAILED this run. The
2600        // in-loop `last_interaction` advance below is by max-seen-score so
2601        // pagination terminates, but a transient ingest failure must NOT let the
2602        // PERSISTED cursor skip past that output — else the peer never re-serves
2603        // it (next `since` excludes scores below the cursor) and it is stranded
2604        // forever. After the loop we cap the cursor strictly below this score so
2605        // the next sync re-requests the failed graph. (Without this, a single
2606        // blipped graph fetch silently drops that UTXO from continuous sync.)
2607        let mut min_failed_score: Option<u64> = None;
2608        // The UTXOs whose ingest FAILED this run (bsv-low #554). The cursor
2609        // moves to a UTXO's score before its ingest and the responder serves
2610        // `score >= since`, so the row at a page boundary is served again on
2611        // the next page of this same sync. A completed one is in
2612        // `shared_outpoints` and skipped; a failed one was in no set and was
2613        // walked a second time, at twice the requests and twice the per-peer
2614        // budget. An addition to the reference: `GASP.ts sync` keeps only
2615        // `sharedOutpoints` (added on success), so a failed UTXO served
2616        // again by a later page is ingested again there. Here a UTXO is
2617        // ingested at most once per sync; the retry is the next sync's, which
2618        // the gap guard below makes sure is served it. Kept apart from
2619        // `shared_outpoints`, which also decides what a bidirectional sync
2620        // pushes.
2621        let mut failed_outpoints: std::collections::HashSet<String> =
2622            std::collections::HashSet::new();
2623
2624        // Saved graphs are work independent of the peer's pagination cursor.
2625        // Read one record at a time and share the existing resume allowance.
2626        // A held root remembered dead is refused with no fetch.
2627        self.load_remembered_expired(held_keys.iter().map(|k| k.outpoint.clone()).collect())
2628            .await;
2629        // Engine 0.1.11: the resumes' share starts with the held loop, so the
2630        // storage's calls between resumes are inside it (polled once now, so
2631        // a timer that starts when it is polled runs).
2632        if !held_keys.is_empty() && self.graph_budget.is_some() {
2633            if let Some(share) = &self.resume_share {
2634                let mut deadline = latched(share());
2635                let _ = Self::due(&mut deadline).await;
2636                *self.resume_deadline.borrow_mut() = Some(deadline);
2637            }
2638        }
2639        let held_scores: std::collections::HashMap<String, u64> = held_keys
2640            .iter()
2641            .map(|key| (key.outpoint.clone(), key.score))
2642            .collect();
2643        for key in held_keys {
2644            if self.request_stopped() {
2645                break;
2646            }
2647            if known_outpoints.contains(&key.outpoint) {
2648                self.deferred.borrow_mut().remove(&key.outpoint);
2649                self.drop_record(&key.outpoint, DropReason::Held).await;
2650                shared_outpoints.insert(key.outpoint);
2651                continue;
2652            }
2653            let Some((txid, output_index)) = parse_outpoint(&key.outpoint) else {
2654                continue;
2655            };
2656            let utxo = GASPOutput {
2657                txid,
2658                output_index,
2659                score: key.score as f64,
2660            };
2661            self.graph_in_flight = true;
2662            self.in_flight = Some((key.score, key.outpoint.clone()));
2663            self.cursor_after_in_flight = initial_interaction;
2664            self.hold_cursor(key.score, &key.outpoint);
2665            let result = self.ingest_utxo(&utxo, &key.outpoint).await;
2666            self.graph_in_flight = false;
2667            self.in_flight = None;
2668            let settled = match result {
2669                Ok(Ingested::Completed) => {
2670                    let landed = match &self.finalized_hook {
2671                        Some(hook) => hook.graph_completed().await.is_ok(),
2672                        None => true,
2673                    };
2674                    self.settle_completed(landed).await;
2675                    if landed {
2676                        self.cursor_yielded.set(true);
2677                    }
2678                    landed
2679                }
2680                Ok(Ingested::Expired) => {
2681                    self.cursor_yielded.set(true);
2682                    true
2683                }
2684                Ok(
2685                    Ingested::Deferred
2686                    | Ingested::HeldBack
2687                    | Ingested::Unanchorable
2688                    | Ingested::Waiting,
2689                ) => true,
2690                Ok(Ingested::Retry) => false,
2691                Err(error) => {
2692                    warn!(
2693                        "{} Deferred graph {} retry failed: {}",
2694                        self.log_prefix, key.outpoint, error
2695                    );
2696                    self.walk.borrow_mut().take();
2697                    let class = self.last_fault.take();
2698                    self.note_faulted(&key.outpoint, &error, class, Strike::default());
2699                    false
2700                }
2701            };
2702            let settled = settled
2703                || self
2704                    .storage
2705                    .get_deferred_graph(&key.outpoint)
2706                    .await
2707                    .ok()
2708                    .flatten()
2709                    .is_some_and(|r| r.cursor_passable);
2710            if settled {
2711                if self
2712                    .cursor_held_by
2713                    .as_ref()
2714                    .is_some_and(|(_, held)| held == &key.outpoint)
2715                {
2716                    self.cursor_held_by = None;
2717                }
2718                // A saved graph settles only itself. The current page must
2719                // account for any earlier unsaved gap before its score can
2720                // contribute to cursor movement.
2721                shared_outpoints.insert(key.outpoint);
2722            } else {
2723                self.hold_cursor(key.score, &key.outpoint);
2724                if key.score >= initial_interaction {
2725                    min_failed_score =
2726                        Some(min_failed_score.map_or(key.score, |s| s.min(key.score)));
2727                }
2728                failed_outpoints.insert(key.outpoint);
2729            }
2730        }
2731
2732        // Paginated pull from remote
2733        'pages: loop {
2734            if self.request_stopped() {
2735                break;
2736            }
2737            let cursor_before_page = self.last_interaction;
2738            // Every UTXO seen so far is completed or failed: were the sync
2739            // dropped inside the page request below, this is what it did.
2740            self.completed_cursor = Self::cursor_for_completed(
2741                &completed_scores,
2742                min_failed_score,
2743                initial_interaction,
2744            );
2745            let request = GASPInitialRequest {
2746                version: GASP_VERSION,
2747                since: self.last_interaction,
2748                limit,
2749            };
2750            let response = self.remote.get_initial_response(&request).await?;
2751            let page_size = response.utxo_list.len();
2752            self.page.pages += 1;
2753
2754            info!(
2755                "{} Processing page with {} UTXOs (since: {})",
2756                self.log_prefix, page_size, response.since
2757            );
2758
2759            // The page's remembered dead are refused with no node fetch.
2760            self.load_remembered_expired(
2761                response
2762                    .utxo_list
2763                    .iter()
2764                    .map(|u| format!("{}.{}", u.txid, u.output_index))
2765                    .filter(|o| !known_outpoints.contains(o))
2766                    .collect(),
2767            )
2768            .await;
2769
2770            if self.graph_budget.is_some() {
2771                let outpoints: Vec<_> = response
2772                    .utxo_list
2773                    .iter()
2774                    .map(|u| format!("{}.{}", u.txid, u.output_index))
2775                    .collect();
2776                let memo = self.storage.read_fault_memos(Some(&outpoints)).await?;
2777                for record in memo.records {
2778                    let changed = response.utxo_list.iter().any(|u| {
2779                        format!("{}.{}", u.txid, u.output_index) == record.outpoint
2780                            && u.score as u64 != record.score
2781                    });
2782                    if changed && (record.dead || record.unanchorable) {
2783                        shared_outpoints.remove(&record.outpoint);
2784                        failed_outpoints.remove(&record.outpoint);
2785                    }
2786                    self.fault_records
2787                        .borrow_mut()
2788                        .insert(record.outpoint.clone());
2789                    self.deferred.borrow_mut().insert(record.outpoint);
2790                }
2791            }
2792
2793            // lowest_ahead[i]: the lowest score among this page's UTXOs from
2794            // i on, for `completed_cursor` (a page is not assumed sorted).
2795            let mut lowest_ahead: Vec<u64> =
2796                response.utxo_list.iter().map(|u| u.score as u64).collect();
2797            for i in (0..lowest_ahead.len().saturating_sub(1)).rev() {
2798                lowest_ahead[i] = lowest_ahead[i].min(lowest_ahead[i + 1]);
2799            }
2800
2801            // The request may have returned an unordered page. Hold below all
2802            // its unfinished outputs before any graph or storage await.
2803            let unfinished = match lowest_ahead.as_slice() {
2804                [lowest, ..] => Some(min_failed_score.map_or(*lowest, |score| score.min(*lowest))),
2805                [] => min_failed_score,
2806            };
2807            self.completed_cursor =
2808                Self::cursor_for_completed(&completed_scores, unfinished, initial_interaction);
2809
2810            for (position, utxo) in response.utxo_list.iter().enumerate() {
2811                if self.request_stopped() {
2812                    let score = lowest_ahead[position];
2813                    min_failed_score = Some(min_failed_score.map_or(score, |s| s.min(score)));
2814                    break 'pages;
2815                }
2816                // Track highest score for pagination
2817                if utxo.score as u64 > self.last_interaction {
2818                    self.last_interaction = utxo.score as u64;
2819                }
2820
2821                let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
2822                if held_scores
2823                    .get(&outpoint)
2824                    .is_some_and(|score| *score != utxo.score as u64)
2825                    && self
2826                        .storage
2827                        .get_deferred_graph(&outpoint)
2828                        .await?
2829                        .is_some_and(|r| r.is_unanchorable() || r.is_dead())
2830                {
2831                    shared_outpoints.remove(&outpoint);
2832                    failed_outpoints.remove(&outpoint);
2833                    self.deferred.borrow_mut().insert(outpoint.clone());
2834                }
2835                if known_outpoints.contains(&outpoint) {
2836                    self.cursor_yielded.set(true);
2837                    // A deferred graph whose UTXO the node now holds (it
2838                    // landed another way): nothing to resume.
2839                    if self.deferred.borrow_mut().remove(&outpoint) {
2840                        self.drop_record(&outpoint, DropReason::Held).await;
2841                    }
2842                    shared_outpoints.insert(outpoint.clone());
2843                    known_outpoints.remove(&outpoint);
2844                } else if !shared_outpoints.contains(&outpoint)
2845                    && !failed_outpoints.contains(&outpoint)
2846                {
2847                    // New UTXO — request and ingest the graph
2848                    let lowest_unfinished = min_failed_score
2849                        .map_or(lowest_ahead[position], |f| f.min(lowest_ahead[position]));
2850                    self.completed_cursor = Self::cursor_for_completed(
2851                        &completed_scores,
2852                        Some(lowest_unfinished),
2853                        initial_interaction,
2854                    );
2855                    let mut with_current = completed_scores.clone();
2856                    with_current.insert(utxo.score as u64);
2857                    let remaining = lowest_ahead
2858                        .get(position + 1)
2859                        .copied()
2860                        .into_iter()
2861                        .chain(min_failed_score)
2862                        .min();
2863                    self.cursor_after_in_flight =
2864                        Self::cursor_for_completed(&with_current, remaining, initial_interaction);
2865                    self.hold_cursor(utxo.score as u64, &outpoint);
2866                    self.graph_in_flight = true;
2867                    self.in_flight = Some((utxo.score as u64, outpoint.clone()));
2868                    let ingested = self.ingest_utxo(utxo, &outpoint).await;
2869                    self.graph_in_flight = false;
2870                    self.in_flight = None;
2871                    let ingested = match ingested {
2872                        Ok(Ingested::Expired) => {
2873                            self.cursor_yielded.set(true);
2874                            Ok(true)
2875                        }
2876                        Ok(Ingested::Completed) => {
2877                            let landed = match &self.finalized_hook {
2878                                Some(hook) => hook.graph_completed().await,
2879                                None => Ok(()),
2880                            };
2881                            self.settle_completed(landed.is_ok()).await;
2882                            if landed.is_ok() {
2883                                self.cursor_yielded.set(true);
2884                            }
2885                            landed.map(|()| true)
2886                        }
2887                        Ok(
2888                            Ingested::Deferred
2889                            | Ingested::HeldBack
2890                            | Ingested::Unanchorable
2891                            | Ingested::Waiting,
2892                        ) => Ok(true),
2893                        Ok(Ingested::Retry) => Ok(false),
2894                        Err(e) => {
2895                            self.walk.borrow_mut().take();
2896                            Err(e)
2897                        }
2898                    };
2899                    match ingested {
2900                        Ok(true) => {
2901                            if self
2902                                .cursor_held_by
2903                                .as_ref()
2904                                .is_some_and(|(_, held)| held == &outpoint)
2905                            {
2906                                self.cursor_held_by = None;
2907                            }
2908                            shared_outpoints.insert(outpoint.clone());
2909                        }
2910                        // An empty deadline retry has not earned a durable
2911                        // hold yet; retain the gap until its named threshold.
2912                        Ok(false) => {
2913                            let s = utxo.score as u64;
2914                            min_failed_score = Some(min_failed_score.map_or(s, |cur| cur.min(s)));
2915                            failed_outpoints.insert(outpoint.clone());
2916                        }
2917                        Err(e) => {
2918                            warn!(
2919                                "{} Error ingesting UTXO {}: {}",
2920                                self.log_prefix, outpoint, e
2921                            );
2922                            let s = utxo.score as u64;
2923                            // Engine 0.1.9: a FAULT of the lowest gap of the
2924                            // run counts the root's opening faulted run (a
2925                            // record `retry:fault:<class>`); its next runs
2926                            // walk it ahead of the pages, and the cursor
2927                            // passes it once it is recorded unanchorable.
2928                            // Only the lowest: one new record a (peer, topic)
2929                            // a run, so a peer that faults every node cannot
2930                            // fill the store in one tick (the delta fold's
2931                            // D-M1).
2932                            let lowest = min_failed_score.is_none_or(|m| s < m);
2933                            if self.strike_fresh(s, &outpoint, &e, lowest).await {
2934                                self.release_hold(&outpoint);
2935                                shared_outpoints.insert(outpoint.clone());
2936                            } else {
2937                                // Remember the lowest failed score so the
2938                                // persisted cursor cannot skip past it (see
2939                                // cap below).
2940                                min_failed_score =
2941                                    Some(min_failed_score.map_or(s, |cur| cur.min(s)));
2942                                // Not again in this sync (bsv-low #554).
2943                                failed_outpoints.insert(outpoint.clone());
2944                            }
2945                        }
2946                    }
2947                }
2948                // Known outputs and graphs whose finalize hook landed are
2949                // settled. Explicit anchor refusals retain the existing
2950                // terminal-discard rule. Saved holds can be passed; faults
2951                // without a durable hold retain a gap.
2952                if shared_outpoints.contains(&outpoint) {
2953                    completed_scores.insert(utxo.score as u64);
2954                }
2955                let unfinished = lowest_ahead
2956                    .get(position + 1)
2957                    .copied()
2958                    .into_iter()
2959                    .chain(min_failed_score)
2960                    .min();
2961                self.completed_cursor =
2962                    Self::cursor_for_completed(&completed_scores, unfinished, initial_interaction);
2963            }
2964
2965            // Keep the settled frontier and any completed scores above a gap.
2966            // An advancing page needs no older score again.
2967            completed_scores.retain(|score| *score >= self.completed_cursor);
2968
2969            // Pagination termination (bsv-low #291 gate findings M1/LOW-A):
2970            // keep paging on ANY page that advanced the score cursor —
2971            // with or without a requested limit. The old rule ("continue
2972            // only on a full page"; `None` never paged at all) silently
2973            // terminated after one page against a responder that CLAMPS
2974            // the page size (Engine::clamp_sync_limit clamps BOTH an
2975            // over-large and an ABSENT limit) — a clamped page is never
2976            // "full" by our limit, yet more rows remain. A non-advancing
2977            // page (empty, or only rows at scores we already hold — the
2978            // responder serves `score >= since`, so the boundary row is
2979            // re-served) is the true completion signal: no further request
2980            // can make progress.
2981            //
2982            // Known residual (gate LOW-B, documented not fixed): the
2983            // cursor is the bare GASP `since` score, so a tie group of
2984            // IDENTICAL scores at least as large as the responder's page
2985            // would end the run with that group's tail unreached (break on
2986            // non-advance — a silent gap, never a spin). A compound
2987            // (score, rowid) cursor would need a wire change to `since`,
2988            // which is out of bounds; unconstructible in practice — see
2989            // the responder-side note at
2990            // `D1Storage::find_utxos_for_topic`.
2991            if self.last_interaction == cursor_before_page {
2992                let settled = min_failed_score.is_none()
2993                    && response.utxo_list.iter().all(|u| {
2994                        shared_outpoints.contains(&format!("{}.{}", u.txid, u.output_index))
2995                    });
2996                if self.request_stop.is_some() && settled && !response.utxo_list.is_empty() {
2997                    // Inclusive peers repeat the boundary. Confirm an empty page above
2998                    // it before claiming tip, without ever storing the probe cursor.
2999                    // A clamped boundary can conceal later rows: retain our cursor
3000                    // and report no progress when the probe finds any.
3001                    if !self.request_stopped() {
3002                        if let Some(since) = self.last_interaction.checked_add(1) {
3003                            let probe = self
3004                                .remote
3005                                .get_initial_response(&GASPInitialRequest {
3006                                    version: GASP_VERSION,
3007                                    since,
3008                                    limit,
3009                                })
3010                                .await?;
3011                            self.page.pages += 1;
3012                            self.page.reached_tip = probe.utxo_list.is_empty();
3013                        }
3014                    }
3015                } else {
3016                    self.page.reached_tip = settled;
3017                }
3018                break;
3019            }
3020            self.page.advanced = true;
3021            if self.request_stop.is_some() {
3022                break;
3023            }
3024        }
3025
3026        // Gap-guard: if any graph ingest failed transiently, cap the cursor
3027        // strictly below the lowest failed score so the next sync re-pulls it
3028        // (the remote serves `score >= since`). Floored at `initial_interaction`
3029        // so the cursor never regresses — a failure within the already-synced
3030        // range is not a new gap and must not rewind the cursor.
3031        self.completed_cursor =
3032            Self::cursor_for_completed(&completed_scores, min_failed_score, initial_interaction);
3033        if let Some(failed) = min_failed_score {
3034            if self.last_interaction > self.completed_cursor {
3035                warn!(
3036                    "{} Capping cursor {} -> {} (transient ingest failure at score {}); next sync will re-pull",
3037                    self.log_prefix, self.last_interaction, self.completed_cursor, failed
3038                );
3039            }
3040        }
3041        self.last_interaction = self.completed_cursor;
3042
3043        // A saved graph can now lie below the peer cursor. Absence from a
3044        // page is not evidence that its work may be deleted.
3045
3046        // Bidirectional: push our UTXOs to remote
3047        if !self.unidirectional {
3048            // Find local UTXOs the remote doesn't have
3049            for utxo in &local_utxos {
3050                let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
3051                if !shared_outpoints.contains(&outpoint) {
3052                    match self.push_utxo(utxo).await {
3053                        Ok(()) => {}
3054                        Err(e) => {
3055                            warn!("{} Error pushing UTXO {}: {}", self.log_prefix, outpoint, e);
3056                        }
3057                    }
3058                }
3059            }
3060        }
3061
3062        info!("{} Sync completed!", self.log_prefix);
3063        Ok(())
3064    }
3065
3066    /// Request a graph or resume its durable record. Saved holds are safe
3067    /// to pass because the next run resumes keys independently of pagination.
3068    /// Empty deadline retries hold the cursor until the stall threshold.
3069    /// All resumed graphs share one allowance; fresh graphs retain theirs.
3070    async fn ingest_utxo(&self, utxo: &GASPOutput, outpoint: &str) -> Result<Ingested, GASPError> {
3071        if self.graph_budget.is_some() {
3072            crate::meter::root_scope(self.ingest_utxo_inner(utxo, outpoint)).await
3073        } else {
3074            self.ingest_utxo_inner(utxo, outpoint).await
3075        }
3076    }
3077
3078    async fn ingest_utxo_inner(
3079        &self,
3080        utxo: &GASPOutput,
3081        outpoint: &str,
3082    ) -> Result<Ingested, GASPError> {
3083        self.last_fault.set(None);
3084        self.resume_idle.set(None);
3085        self.pass_saved.set(false);
3086        if self.expired.borrow().contains(outpoint) {
3087            if self.deferred.borrow().contains(outpoint) {
3088                let record = self.storage.get_deferred_graph(outpoint).await?;
3089                if self.sweep_expired_record(record.as_ref()).await? {
3090                    return Ok(Ingested::Expired);
3091                }
3092            }
3093            return self.refuse_expired(outpoint).await;
3094        }
3095        debug!("{} Requesting node for {}", self.log_prefix, outpoint);
3096        self.graphs_attempted.set(self.graphs_attempted.get() + 1);
3097        let Some(budget) = &self.graph_budget else {
3098            *self.walk.borrow_mut() =
3099                Some(Self::fresh_walk(utxo.score as u64, outpoint, PassCap::NONE));
3100            crate::meter::walk_output();
3101            let walked = self.walk_graph(None).await;
3102            if matches!(walked, Ok(WalkEnd::Expired)) {
3103                return self.refuse_expired(outpoint).await;
3104            }
3105            let walk = self.walk.borrow_mut().take();
3106            walked?;
3107            self.complete_graph(&Self::graph_id_of(walk.as_ref(), outpoint))
3108                .await?;
3109            return Ok(Ingested::Completed);
3110        };
3111
3112        if !self.deferred.borrow_mut().remove(outpoint) {
3113            let mut deadline = latched((budget.deadline)());
3114            return self
3115                .ingest_budgeted(utxo, outpoint, &mut deadline, budget.pass(), false)
3116                .await;
3117        }
3118        let mut deadline = self
3119            .resume_deadline
3120            .borrow_mut()
3121            .take()
3122            .unwrap_or_else(|| latched((budget.deadline)()));
3123        let cap = self.resume_left.get();
3124        if cap.spent() || Self::due(&mut deadline).await {
3125            *self.resume_deadline.borrow_mut() = Some(deadline);
3126            let record = self.storage.get_deferred_graph(outpoint).await?;
3127            self.read_record(record.as_ref());
3128            if self.sweep_expired_record(record.as_ref()).await? {
3129                return Ok(Ingested::Expired);
3130            }
3131            if record
3132                .as_ref()
3133                .is_some_and(|r| r.waits_idle(Self::now_secs()))
3134            {
3135                return Ok(self.wait_idle(outpoint));
3136            }
3137            // An unanchorable root inside its backoff would not be walked
3138            // anyway: not held back, and no attempt (engine 0.1.11).
3139            if record.as_ref().is_some_and(|r| {
3140                r.is_dead() || (r.is_unanchorable() && Self::now_secs() < r.retry_at)
3141            }) {
3142                self.graphs_attempted
3143                    .set(self.graphs_attempted.get().saturating_sub(1));
3144                return Ok(Ingested::Unanchorable);
3145            }
3146            self.stats.borrow_mut().held_back += 1;
3147            info!(
3148                "{} Deferred graph {} held back: the resumes of this pass spent their budget (bsv-low #555)",
3149                self.log_prefix, outpoint
3150            );
3151            let Some(mut record) = record else {
3152                return Ok(Ingested::Retry);
3153            };
3154            if record.reason == "retry:deadline" {
3155                return Ok(Ingested::Retry);
3156            }
3157            // A fault streak not yet at its threshold holds the cursor; one
3158            // not walked this run is not a faulted run (engine 0.1.9).
3159            if record.is_struck() && !record.cursor_passable {
3160                return Ok(Ingested::Retry);
3161            }
3162            if !record.cursor_passable {
3163                record.cursor_passable = true;
3164                if self.storage.save_deferred_graph(&record).await? != DeferredGraphSave::Saved {
3165                    return Ok(Ingested::Retry);
3166                }
3167            }
3168            return Ok(Ingested::HeldBack);
3169        }
3170        let before = (
3171            self.calls_made.get(),
3172            self.bytes_fetched.get(),
3173            self.nodes_appended.get(),
3174        );
3175        let ingested = self
3176            .ingest_budgeted(utxo, outpoint, &mut deadline, cap, true)
3177            .await;
3178        // Engine 0.1.10: a held record's resume that asked the peer,
3179        // appended no node and did not finish counts one more idle resume.
3180        // Its own save counted it; any other ending counts it here (engine
3181        // 0.1.11): a drop that saved the record again as a fresh obligation
3182        // (`drop_record`) or an error that left it as it was. What the pass
3183        // KEPT is read from the record, not from the nodes it appended: on
3184        // 0.1.10 a root appended and then thrown away with the drop (fact 3
3185        // of the 0.1.11 brief: the courier exhausted on its parent) read as
3186        // progress, and the count never fired. A record a strike counted is
3187        // left to the strike.
3188        if let Some((prior, held)) = self.resume_idle.take() {
3189            if self.calls_made.get() > before.0
3190                && !self.pass_saved.get()
3191                && !matches!(ingested, Ok(Ingested::Completed | Ingested::Expired))
3192            {
3193                self.idle_resume(outpoint, prior, held).await;
3194            }
3195        }
3196        let narrowed = |spent: u64| u32::try_from(spent).unwrap_or(u32::MAX);
3197        self.resume_left.set(PassCap {
3198            calls: cap
3199                .calls
3200                .saturating_sub(narrowed(self.calls_made.get() - before.0)),
3201            bytes: cap
3202                .bytes
3203                .saturating_sub(self.bytes_fetched.get() - before.1),
3204            nodes: cap
3205                .nodes
3206                .saturating_sub(narrowed(self.nodes_appended.get() - before.2)),
3207        });
3208        *self.resume_deadline.borrow_mut() = Some(deadline);
3209        ingested
3210    }
3211
3212    /// A held record not resumed: it waits out the long backoff of its idle
3213    /// resumes (engine 0.1.10). Not asked of the peer: not an attempt for
3214    /// the yieldless streak, as an unanchorable root inside its backoff.
3215    fn wait_idle(&self, outpoint: &str) -> Ingested {
3216        self.graphs_attempted
3217            .set(self.graphs_attempted.get().saturating_sub(1));
3218        self.stats.borrow_mut().waiting += 1;
3219        debug!(
3220            "{} Deferred graph {} waits out its idle backoff (engine 0.1.10)",
3221            self.log_prefix, outpoint
3222        );
3223        Ingested::Waiting
3224    }
3225
3226    /// Count one more idle resume on the held record of `outpoint` after a
3227    /// pass that did not save it (engine 0.1.10): `prior` is what it counted
3228    /// when its pass read it, so a record the pass dropped and saved again as
3229    /// a fresh obligation (`drop_record`) counts on from there. At
3230    /// [`IDLE_RESUMES_BEFORE_BACKOFF`] it goes to the long backoff. A record
3231    /// gone, a fault record, one that holds the cursor, or one holding more
3232    /// nodes than the `held` its pass read (it kept progress) is left alone.
3233    async fn idle_resume(&self, outpoint: &str, prior: u32, held: usize) {
3234        let Ok(Some(mut record)) = self.storage.get_deferred_graph(outpoint).await else {
3235            return;
3236        };
3237        if record.is_struck() || !record.cursor_passable || record.nodes.len() > held {
3238            return;
3239        }
3240        record.idle_resumes = prior.saturating_add(1);
3241        let backoff = record.idle_resumes >= IDLE_RESUMES_BEFORE_BACKOFF;
3242        if backoff {
3243            record.retry_at = Self::now_secs() + IDLE_RESUME_RETRY_SECS;
3244        }
3245        let saved = self.storage.save_deferred_graph(&record).await;
3246        if let Ok(DeferredGraphSave::Saved) = saved {
3247            self.stats.borrow_mut().idle_counted += 1;
3248        }
3249        match saved {
3250            Ok(DeferredGraphSave::Saved) if backoff => {
3251                self.stats.borrow_mut().backed_off += 1;
3252                info!(
3253                    "{} Deferred graph {} resumed {} passes in a row with no node appended: not resumed for {} s (engine 0.1.10)",
3254                    self.log_prefix, outpoint, record.idle_resumes, IDLE_RESUME_RETRY_SECS
3255                );
3256            }
3257            Ok(_) => {}
3258            Err(e) => warn!(
3259                "{} Could not count an idle resume of deferred graph {}: {}",
3260                self.log_prefix, outpoint, e
3261            ),
3262        }
3263    }
3264
3265    /// Whether `deadline` has fallen due (polled once, with the task's own
3266    /// waker).
3267    async fn due(deadline: &mut crate::engine::SleepFuture) -> bool {
3268        std::future::poll_fn(|cx| std::task::Poll::Ready(deadline.as_mut().poll(cx).is_ready()))
3269            .await
3270    }
3271
3272    /// A walk from the root `outpoint`, nothing fetched yet.
3273    fn fresh_walk(score: u64, outpoint: &str, cap: PassCap) -> Walk {
3274        Walk {
3275            record: DeferredGraph {
3276                peer: String::new(),
3277                topic: String::new(),
3278                outpoint: outpoint.to_string(),
3279                score,
3280                nodes: Vec::new(),
3281                pending: vec![PendingInput {
3282                    outpoint: outpoint.to_string(),
3283                    graph_id: outpoint.to_string(),
3284                    metadata: true,
3285                    spent_by: None,
3286                    parent_proven: false,
3287                }],
3288                calls: 0,
3289                passes: 0,
3290                reason: String::new(),
3291                configured: false,
3292                idle_faults: 0,
3293                cursor_passable: false,
3294                faults: 0,
3295                retry_at: 0,
3296                idle_resumes: 0,
3297                unanchorable_retries: 0,
3298                expiry: None,
3299            },
3300            seen: std::collections::HashSet::new(),
3301            calls_this_pass: 0,
3302            bytes_this_pass: 0,
3303            nodes_this_pass: 0,
3304            resumed: false,
3305            cap,
3306            nodes_at_start: 0,
3307            counted: false,
3308            gone_on: false,
3309            half: None,
3310            struck: None,
3311        }
3312    }
3313
3314    /// One pass of a graph's walk under the per-graph budget: `deadline`,
3315    /// and `cap` (calls, bytes, nodes). `from_record`: a record of it is held (its key was
3316    /// loaded); it is read now.
3317    async fn ingest_budgeted(
3318        &self,
3319        utxo: &GASPOutput,
3320        outpoint: &str,
3321        deadline: &mut crate::engine::SleepFuture,
3322        cap: PassCap,
3323        from_record: bool,
3324    ) -> Result<Ingested, GASPError> {
3325        let score = utxo.score as u64;
3326        // A read fault fails the UTXO and keeps the record for the next sync.
3327        let mut record = if from_record {
3328            let record = self.storage.get_deferred_graph(outpoint).await?;
3329            self.read_record(record.as_ref());
3330            if record.is_none() {
3331                // Deleted since the keys were read (the worker's sweep).
3332                self.held_records
3333                    .set(self.held_records.get().saturating_sub(1));
3334            }
3335            record
3336        } else {
3337            None
3338        };
3339        if self.sweep_expired_record(record.as_ref()).await? {
3340            return Ok(Ingested::Expired);
3341        }
3342        if record
3343            .as_ref()
3344            .is_some_and(|r| (r.is_unanchorable() || r.is_dead()) && r.score != score)
3345        {
3346            self.storage.delete_deferred_graph(outpoint).await?;
3347            self.forget_record(outpoint);
3348            record = None;
3349        }
3350        if let Some(record) = record.as_ref().filter(|r| r.is_struck()) {
3351            return self
3352                .rewalk_struck(utxo, outpoint, record.clone(), deadline, cap)
3353                .await;
3354        }
3355        if let Some(record) = &record {
3356            if let [root, ..] = record.nodes.as_slice() {
3357                if self.root_expired(&root.node, outpoint)? {
3358                    self.deferred.borrow_mut().insert(outpoint.to_string());
3359                    return self.refuse_expired(outpoint).await;
3360                }
3361            }
3362            // Engine 0.1.10: a held record past its idle resumes waits out
3363            // the long backoff (an expired root it holds was refused above,
3364            // with no request); else its pass counts on from what it holds.
3365            if record.cursor_passable {
3366                if record.waits_idle(Self::now_secs()) {
3367                    return Ok(self.wait_idle(outpoint));
3368                }
3369                self.resume_idle
3370                    .set(Some((record.idle_resumes, record.nodes.len())));
3371            }
3372        }
3373        let walk = match record {
3374            None => {
3375                let mut walk = Self::fresh_walk(score, outpoint, cap);
3376                // D2-L1: the half-budget clock starts with the walk (polled
3377                // once now, so a timer that starts on its first poll runs).
3378                if let Some(half) = self
3379                    .graph_budget
3380                    .as_ref()
3381                    .and_then(|b| b.half_deadline.as_ref())
3382                {
3383                    let mut half = latched(half());
3384                    let _ = Self::due(&mut half).await;
3385                    walk.half = Some(half);
3386                }
3387                walk
3388            }
3389            Some(record) if record.passes >= DEFERRED_GRAPH_MAX_PASSES => {
3390                let passes = record.passes;
3391                self.drop_record(outpoint, DropReason::MaxPasses).await;
3392                return Err(GASPError::Other(format!(
3393                    "deferred graph {outpoint} dropped after {passes} passes (bsv-low #555)"
3394                )));
3395            }
3396            Some(record) => {
3397                self.stats.borrow_mut().resumed += 1;
3398                info!(
3399                    "{} Resuming deferred graph {} (bsv-low #555): {} nodes, {} pending, {} calls over {} passes",
3400                    self.log_prefix,
3401                    outpoint,
3402                    record.nodes.len(),
3403                    record.pending.len(),
3404                    record.calls,
3405                    record.passes
3406                );
3407                Walk {
3408                    seen: record
3409                        .nodes
3410                        .iter()
3411                        .filter_map(|w| Self::node_id(&w.node))
3412                        .collect(),
3413                    nodes_at_start: record.nodes.len(),
3414                    record,
3415                    calls_this_pass: 0,
3416                    bytes_this_pass: 0,
3417                    nodes_this_pass: 0,
3418                    resumed: true,
3419                    cap,
3420                    counted: false,
3421                    gone_on: false,
3422                    half: None,
3423                    struck: None,
3424                }
3425            }
3426        };
3427        let resumed = walk.resumed;
3428        let root_unproven = walk
3429            .record
3430            .nodes
3431            .first()
3432            .is_some_and(|w| w.node.proof.is_none());
3433        crate::meter::walk_output();
3434        *self.walk.borrow_mut() = Some(walk);
3435
3436        let ended = async {
3437            if resumed && root_unproven {
3438                // The root is asked again (one call): once its block lands
3439                // the peer serves it PROVEN, and the walk from it is shorter
3440                // than the unproven ancestry the record is still walking.
3441                let root = PendingInput {
3442                    outpoint: outpoint.to_string(),
3443                    graph_id: outpoint.to_string(),
3444                    metadata: true,
3445                    spent_by: None,
3446                    parent_proven: false,
3447                };
3448                match race_or_deadline(self.fetch_root(&root), deadline.as_mut()).await {
3449                    None => return Ok(WalkEnd::Deferred("time")),
3450                    Some(Ok(None)) => return Ok(WalkEnd::Expired),
3451                    Some(Ok(Some(node))) if node.proof.is_some() => {
3452                        // The walk is fresh, the PASS is not: what it spent
3453                        // of every counted limb goes with it (the re-ask
3454                        // appends nothing, so the nodes are 0 today; carried
3455                        // all the same, so a limb is never forgotten here).
3456                        let (carried, carried_bytes, carried_nodes) =
3457                            self.walk.borrow().as_ref().map_or((0, 0, 0), |w| {
3458                                (w.calls_this_pass, w.bytes_this_pass, w.nodes_this_pass)
3459                            });
3460                        let reserved = self
3461                            .walk
3462                            .borrow()
3463                            .as_ref()
3464                            .is_some_and(|w| w.record.cursor_passable);
3465                        self.drop_record(outpoint, DropReason::RootProven).await;
3466                        let mut restarted = Self::fresh_walk(score, outpoint, cap);
3467                        restarted.resumed = reserved;
3468                        restarted.calls_this_pass = carried;
3469                        restarted.bytes_this_pass = carried_bytes;
3470                        restarted.nodes_this_pass = carried_nodes;
3471                        restarted.record.calls = u64::from(carried);
3472                        *self.walk.borrow_mut() = Some(restarted);
3473                    }
3474                    // Unchanged, or not answered: the record goes on.
3475                    Some(_) => {}
3476                }
3477            }
3478            self.append_walked().await?;
3479            self.walk_graph(Some(&mut *deadline)).await
3480        }
3481        .await;
3482        self.finish_pass(outpoint, ended, deadline).await
3483    }
3484
3485    /// Append the walk's fetched nodes to the graph (a resume, or a walk
3486    /// that goes on after its graph was discarded).
3487    async fn append_walked(&self) -> Result<(), GASPError> {
3488        let nodes: Vec<WalkedNode> = self
3489            .walk
3490            .borrow()
3491            .as_ref()
3492            .map(|w| w.record.nodes.clone())
3493            .unwrap_or_default();
3494        for walked in &nodes {
3495            self.storage
3496                .append_to_graph(&walked.node, walked.spent_by.as_deref())
3497                .await?;
3498        }
3499        Ok(())
3500    }
3501
3502    /// The end of a budgeted pass: complete the graph, defer it, or fail
3503    /// its UTXO. A call/size cut whose record cannot be kept may continue
3504    /// within the same root deadline (L4). Time and courier limits stop it
3505    /// even when the storage refuses the save; the cursor retains its gap.
3506    async fn finish_pass(
3507        &self,
3508        outpoint: &str,
3509        mut ended: Result<WalkEnd, GASPError>,
3510        deadline: &mut crate::engine::SleepFuture,
3511    ) -> Result<Ingested, GASPError> {
3512        loop {
3513            let graph_id = Self::graph_id_of(self.walk.borrow().as_ref(), outpoint);
3514            // Whether a record of this graph is still held: not after a
3515            // `root_proven` restart, whose walk is fresh.
3516            let resumed = self.walk.borrow().as_ref().is_some_and(|w| w.resumed);
3517            let (reason, completed) = match ended {
3518                Ok(WalkEnd::Expired) => return self.refuse_expired(outpoint).await,
3519                Ok(WalkEnd::Done) => match self.complete_graph(&graph_id).await {
3520                    Ok(true) => return Ok(Ingested::Completed),
3521                    Ok(false) => {
3522                        // Refused by the anchor check: a verdict, the cursor
3523                        // moves, nothing to resume. A root's fault record
3524                        // goes with it (engine 0.1.9).
3525                        let struck = self
3526                            .walk
3527                            .borrow_mut()
3528                            .take()
3529                            .is_some_and(|w| w.struck.is_some());
3530                        if resumed || struck {
3531                            if struck {
3532                                self.unanchorable_cleared
3533                                    .set(self.unanchorable_cleared.get() + 1);
3534                            }
3535                            self.drop_record(outpoint, DropReason::Refused).await;
3536                        }
3537                        return Ok(Ingested::Completed);
3538                    }
3539                    // `complete_graph` discarded the graph already.
3540                    Err(GASPError::AnchorUnavailable(_)) => ("anchor_unavailable", true),
3541                    // The same hold, for a walk past the budget (E592 fold).
3542                    Err(GASPError::AnchorWalkHeld(_)) => ("anchor_walk_held", true),
3543                    // A finalize fault: the graph is still in hand.
3544                    Err(_) => {
3545                        let _ = self.storage.discard_graph(&graph_id).await;
3546                        ("fault", true)
3547                    }
3548                },
3549                Ok(WalkEnd::Deferred(reason)) => (reason, false),
3550                Err(e @ (GASPError::NodeNotFound(_) | GASPError::DefinitiveNotFound(_))) => {
3551                    let _ = self.storage.discard_graph(&graph_id).await;
3552                    let walk = self.walk.borrow_mut().take();
3553                    if resumed {
3554                        // Engine 0.1.11: a fault of the graph is a strike on
3555                        // the record's own slot, as for a fresh root.
3556                        if let Some(struck) = self.strike_resumed(outpoint, walk.as_ref(), &e).await
3557                        {
3558                            return if struck.passable() {
3559                                Ok(Ingested::Unanchorable)
3560                            } else {
3561                                Err(e)
3562                            };
3563                        }
3564                        self.drop_record(outpoint, DropReason::NotHeld).await;
3565                    }
3566                    return Err(e);
3567                }
3568                // A walk ERROR on a FRESH walk keeps no record (the delta
3569                // fold's D-M1): a fault is not a budget cut, and before #555
3570                // it failed the UTXO. A record then costs a peer a budget
3571                // cut (`calls`, `time`, `peer_deadline`), never a quick 5xx:
3572                // a stranger who answered each input with a 503 kept a
3573                // one-node record per UTXO, 16 per (peer, topic) in one tick
3574                // with no time spent, and filled the worker's ceiling. A
3575                // RESUMED walk keeps its record (its progress was paid for).
3576                //
3577                // Unless it PAID (the delta-2 fold's D2-L1): a fresh walk
3578                // that faults after half its per-graph calls or half its
3579                // time keeps its record as a budget cut would, so an honest
3580                // flaky peer's deep graph is not walked from its root on
3581                // every tick ((1-p)^100 a clean pass at a fault rate p).
3582                Err(e) if !resumed && !self.walk_paid().await => {
3583                    warn!(
3584                        "{} Walk of {} faulted: no record, the UTXO fails as before #555: {}",
3585                        self.log_prefix, outpoint, e
3586                    );
3587                    let _ = self.storage.discard_graph(&graph_id).await;
3588                    self.walk.borrow_mut().take();
3589                    return Err(e);
3590                }
3591                Err(e) => {
3592                    // D2-M2: a RESUMED pass that faulted having appended
3593                    // nothing is idle; at DEFERRED_GRAPH_MAX_IDLE_FAULTS in a
3594                    // row the record goes and the UTXO fails.
3595                    let idle = {
3596                        let mut guard = self.walk.borrow_mut();
3597                        guard.as_mut().map_or(0, |w| {
3598                            if w.resumed && w.record.nodes.len() <= w.nodes_at_start {
3599                                w.record.idle_faults += 1;
3600                            }
3601                            w.record.idle_faults
3602                        })
3603                    };
3604                    if idle >= DEFERRED_GRAPH_MAX_IDLE_FAULTS {
3605                        warn!(
3606                            "{} Walk of {} faulted with nothing appended {} passes in a row: dropped: {}",
3607                            self.log_prefix, outpoint, idle, e
3608                        );
3609                        let _ = self.storage.discard_graph(&graph_id).await;
3610                        let walk = self.walk.borrow_mut().take();
3611                        // Engine 0.1.11: dropped by a fault of the graph, a
3612                        // strike on the record's own slot.
3613                        if let Some(struck) = self.strike_resumed(outpoint, walk.as_ref(), &e).await
3614                        {
3615                            return if struck.passable() {
3616                                Ok(Ingested::Unanchorable)
3617                            } else {
3618                                Err(e)
3619                            };
3620                        }
3621                        self.drop_record(outpoint, DropReason::IdleFaults).await;
3622                        return Err(e);
3623                    }
3624                    warn!(
3625                        "{} Walk of {} faulted, deferred with its progress: {}",
3626                        self.log_prefix, outpoint, e
3627                    );
3628                    let _ = self.storage.discard_graph(&graph_id).await;
3629                    ("fault", false)
3630                }
3631            };
3632            // Call and size cuts may go on if no record fits (L4), with
3633            // the original deadline still active. Time and courier cuts
3634            // stop this root even if its save is refused.
3635            let budget_cut = matches!(reason, "calls" | "bytes" | "nodes");
3636            let (why, mut walk) = match self.save_walk(reason, completed).await {
3637                Saved::Retry => {
3638                    let _ = self.storage.discard_graph(&graph_id).await;
3639                    return Ok(Ingested::Retry);
3640                }
3641                Saved::Yes => {
3642                    let _ = self.storage.discard_graph(&graph_id).await;
3643                    return Ok(Ingested::Deferred);
3644                }
3645                Saved::WentOn => {
3646                    let _ = self.storage.discard_graph(&graph_id).await;
3647                    return Err(GASPError::Other(format!(
3648                        "graph {outpoint} went on and did not complete (bsv-low #555)"
3649                    )));
3650                }
3651                // A store FAULT at a deferral goes on as the other bounds do
3652                // (the delta fold's D-L2; counted `store_fault` by
3653                // `save_walk`): it failed the UTXO, a transient D1 fault
3654                // failing a graph the per-peer budget would have completed.
3655                Saved::Fault(e, walk) => {
3656                    if !budget_cut {
3657                        let _ = self.storage.discard_graph(&graph_id).await;
3658                        return Err(e);
3659                    }
3660                    (DropReason::StoreFault, walk)
3661                }
3662                // No room for a RESUMED walk (bsv-low #585): its held record
3663                // stays, so what this pass adds is lost and nothing else. A
3664                // budget cut goes on as the other bounds do; any other end
3665                // fails the UTXO and the next pass resumes from the record.
3666                Saved::Ceiling(walk) => {
3667                    if !budget_cut {
3668                        let _ = self.storage.discard_graph(&graph_id).await;
3669                        return Err(GASPError::Other(format!(
3670                            "deferred graph {outpoint} found no room, its record kept (bsv-low #585)"
3671                        )));
3672                    }
3673                    (DropReason::TooMany, walk)
3674                }
3675                Saved::Unkept(why, mut walk) => {
3676                    self.unkept(why, &mut walk).await;
3677                    if !(budget_cut && why == DropReason::TooMany) {
3678                        let _ = self.storage.discard_graph(&graph_id).await;
3679                        return Err(GASPError::Other(format!(
3680                            "deferred graph {outpoint} not kept: {} (bsv-low #555)",
3681                            why.as_str()
3682                        )));
3683                    }
3684                    (why, walk)
3685                }
3686            };
3687            info!(
3688                "{} Graph {} cannot be kept ({}): its walk goes on with the root deadline (bsv-low #555)",
3689                self.log_prefix,
3690                outpoint,
3691                why.as_str()
3692            );
3693            walk.cap = PassCap::NONE;
3694            walk.gone_on = true;
3695            *self.walk.borrow_mut() = Some(*walk);
3696            // The graph in hand was never discarded: walk on.
3697            ended = self.walk_graph(Some(&mut *deadline)).await;
3698        }
3699    }
3700
3701    /// After a COMPLETED graph's hook (bsv-low #555): a graph that landed
3702    /// deletes its record (a resumed one converged); one whose finalize did
3703    /// not land keeps its walk as a record with nothing pending, so the next
3704    /// pass completes it again without walking it again. No-op without a
3705    /// per-graph budget.
3706    async fn settle_completed(&self, landed: bool) {
3707        if self.graph_budget.is_none() {
3708            self.walk.borrow_mut().take();
3709            return;
3710        }
3711        if landed {
3712            let Some(walk) = self.walk.borrow_mut().take() else {
3713                return;
3714            };
3715            if walk.struck.is_some() {
3716                // A root walked again after faulted runs landed (engine
3717                // 0.1.9): admitted as any root, its record cleared.
3718                if let Err(e) = self
3719                    .storage
3720                    .delete_deferred_graph(&walk.record.outpoint)
3721                    .await
3722                {
3723                    warn!(
3724                        "{} Could not delete the fault record of landed root {}: {}",
3725                        self.log_prefix, walk.record.outpoint, e
3726                    );
3727                }
3728                self.forget_record(&walk.record.outpoint);
3729                self.unanchorable_cleared
3730                    .set(self.unanchorable_cleared.get() + 1);
3731                info!(
3732                    "{} Root {} LANDED after {} faulted runs: its record cleared (engine 0.1.9)",
3733                    self.log_prefix,
3734                    walk.record.outpoint,
3735                    walk.struck.as_ref().map_or(0, |r| r.faults)
3736                );
3737            } else if walk.resumed {
3738                if let Err(e) = self
3739                    .storage
3740                    .delete_deferred_graph(&walk.record.outpoint)
3741                    .await
3742                {
3743                    warn!(
3744                        "{} Could not delete the record of converged graph {}: {}",
3745                        self.log_prefix, walk.record.outpoint, e
3746                    );
3747                }
3748                self.forget_record(&walk.record.outpoint);
3749                self.stats.borrow_mut().converged += 1;
3750                self.resumed_with_progress
3751                    .set(self.resumed_with_progress.get() + 1);
3752                info!(
3753                    "{} Deferred graph {} CONVERGED after {} passes, {} calls, {} nodes (bsv-low #555)",
3754                    self.log_prefix,
3755                    walk.record.outpoint,
3756                    walk.record.passes + 1,
3757                    walk.record.calls,
3758                    walk.record.nodes.len()
3759                );
3760            }
3761        } else if let Saved::Unkept(why, mut walk) = self.save_walk("not_landed", true).await {
3762            self.unkept(why, &mut walk).await;
3763        }
3764    }
3765
3766    /// Save the walk in hand as its graph's record (bsv-low #555), counting
3767    /// a deferral; or hand it back UNKEPT with the reason (past a bound, or
3768    /// holding no node), or answer the storage's fault with the walk (a call
3769    /// or size cut may go on within its deadline, D-L2; any other fails its
3770    /// UTXO). A walk that already went on is neither saved nor counted again
3771    /// (D-L1). Counts the pass progressed or stalled (the lens fold's H1),
3772    /// once per pass.
3773    async fn save_walk(&self, reason: &'static str, completed: bool) -> Saved {
3774        let Some(mut walk) = self.walk.borrow_mut().take() else {
3775            // Nothing in hand: nothing to save.
3776            return Saved::Yes;
3777        };
3778        if walk.gone_on {
3779            // Its drop was counted when it went on (D-L1).
3780            return Saved::WentOn;
3781        }
3782        if !walk.counted {
3783            walk.counted = true;
3784            let mut stats = self.stats.borrow_mut();
3785            if completed || walk.record.nodes.len() > walk.nodes_at_start {
3786                stats.progressed += 1;
3787            } else {
3788                stats.stalled += 1;
3789            }
3790        }
3791        let was_held = walk.record.cursor_passable;
3792        let deadline_cut = matches!(reason, "time" | "peer_deadline");
3793        let deadline_streak = was_held || walk.record.reason == "retry:deadline";
3794        if walk.record.nodes.is_empty() && !deadline_streak {
3795            walk.record.passes = 0;
3796        }
3797        walk.record.passes += 1;
3798        // Only the graph's OWN deadline earns the stall allowance. The
3799        // per-peer deadline ends the slice, not the graph: what it cut is
3800        // held at once and the cursor passes it.
3801        let retry = walk.record.nodes.is_empty()
3802            && reason == "time"
3803            && !was_held
3804            && walk.record.passes < DEADLINE_STALL_DEFERRAL_RUNS;
3805        walk.record.cursor_passable = !retry;
3806        walk.record.reason = if retry {
3807            "retry:deadline".into()
3808        } else {
3809            reason.into()
3810        };
3811        if walk.record.nodes.len() > walk.nodes_at_start {
3812            walk.record.idle_faults = 0;
3813            // A pass that appends a node resets the idle resumes (0.1.10).
3814            walk.record.idle_resumes = 0;
3815            walk.record.retry_at = 0;
3816        }
3817        // Engine 0.1.10: a RESUMED pass of a held record that asked the peer
3818        // and appended nothing counts one idle resume in this save; at the
3819        // bound the record waits out the long backoff.
3820        let idle_now = walk.resumed
3821            && was_held
3822            && walk.struck.is_none()
3823            && !completed
3824            && walk.calls_this_pass > 0
3825            && walk.record.nodes.len() <= walk.nodes_at_start;
3826        let backing_off = if idle_now {
3827            walk.record.idle_resumes = walk.record.idle_resumes.saturating_add(1);
3828            let due = walk.record.idle_resumes >= IDLE_RESUMES_BEFORE_BACKOFF;
3829            if due {
3830                walk.record.retry_at = Self::now_secs() + IDLE_RESUME_RETRY_SECS;
3831            }
3832            due
3833        } else {
3834            false
3835        };
3836        // Empty walks qualify only after repeated deadline cuts. The small
3837        // retry record uses the same per-peer and global storage ceilings.
3838        // A quick fresh fault still earns no record.
3839        if walk.record.nodes.is_empty() && !deadline_cut && !was_held {
3840            return Saved::Unkept(DropReason::NoProgress, Box::new(walk));
3841        }
3842        // A resumed walk holds its record's deferred slot. A root walked
3843        // again after faulted runs holds a FAULT record (engine 0.1.10): the
3844        // hold its walk earned replaces it only with room among the deferred
3845        // slots, else the walk goes on as any walk past the bound (L4) and
3846        // its fault record stays as it was.
3847        if !walk.resumed && self.held_records.get() >= DEFERRED_GRAPHS_PER_PEER_TOPIC {
3848            return Saved::Unkept(DropReason::TooMany, Box::new(walk));
3849        }
3850        // No bound on a record's size (bsv-low #585): the figure is logged
3851        // and is the storage's to budget.
3852        let bytes = walk.record.byte_size();
3853        let outpoint = walk.record.outpoint.clone();
3854        match self.storage.save_deferred_graph(&walk.record).await {
3855            Ok(DeferredGraphSave::Saved) => {
3856                if walk.resumed {
3857                    self.pass_saved.set(true);
3858                }
3859                if idle_now {
3860                    self.stats.borrow_mut().idle_counted += 1;
3861                }
3862                if !walk.resumed {
3863                    // A fault record replaced is a fault record no more.
3864                    self.fault_records.borrow_mut().remove(&outpoint);
3865                    self.held_records.set(self.held_records.get() + 1);
3866                    if !retry && !walk.record.nodes.is_empty() {
3867                        self.retained.set(self.retained.get() + 1);
3868                    }
3869                } else if walk.record.nodes.len() > walk.nodes_at_start {
3870                    self.resumed_with_progress
3871                        .set(self.resumed_with_progress.get() + 1);
3872                }
3873                if !retry {
3874                    self.stats.borrow_mut().deferred += 1;
3875                }
3876                if backing_off {
3877                    self.stats.borrow_mut().backed_off += 1;
3878                    info!(
3879                        "{} Deferred graph {} resumed {} passes in a row with no node appended: not resumed for {} s (engine 0.1.10)",
3880                        self.log_prefix, outpoint, walk.record.idle_resumes, IDLE_RESUME_RETRY_SECS
3881                    );
3882                }
3883                info!(
3884                    "{} DEFERRED graph {} ({}): {} nodes, {} pending, {} calls ({} this pass), pass {}, {} bytes (bsv-low #555)",
3885                    self.log_prefix,
3886                    outpoint,
3887                    reason,
3888                    walk.record.nodes.len(),
3889                    walk.record.pending.len(),
3890                    walk.record.calls,
3891                    walk.calls_this_pass,
3892                    walk.record.passes,
3893                    bytes
3894                );
3895                if retry {
3896                    Saved::Retry
3897                } else {
3898                    Saved::Yes
3899                }
3900            }
3901            // The storage's ceiling is a budget of room, not a verdict on
3902            // the graph (bsv-low #585): a RESUMED walk keeps the record it
3903            // holds (it was deleted, and the graph walked from its root at
3904            // the next pass); a fresh walk has none to keep.
3905            Ok(DeferredGraphSave::AtCeiling) if walk.resumed => {
3906                self.note_dropped(&outpoint, DropReason::TooMany);
3907                Saved::Ceiling(Box::new(walk))
3908            }
3909            Ok(DeferredGraphSave::AtCeiling) => Saved::Unkept(DropReason::TooMany, Box::new(walk)),
3910            // The save is lost and counted `store_fault`. A RESUMED walk's
3911            // held record is KEPT (the delta-2 lens's D2-N2: it was deleted,
3912            // and one transient D1 fault threw away every earlier pass of a
3913            // walk the per-peer budget did not then finish): the next pass
3914            // resumes from it, losing this pass only; a walk that goes on
3915            // and lands deletes it as a converged one.
3916            Err(e) => {
3917                self.note_dropped(&outpoint, DropReason::StoreFault);
3918                Saved::Fault(e, Box::new(walk))
3919            }
3920        }
3921    }
3922
3923    /// A walk the save did not keep: reset its retained obligation or count
3924    /// the drop. A fresh walk that fetched nothing is only logged.
3925    async fn unkept(&self, why: DropReason, walk: &mut Walk) {
3926        let outpoint = walk.record.outpoint.clone();
3927        if walk.resumed {
3928            self.drop_record(&outpoint, why).await;
3929            walk.resumed = false;
3930        } else if why == DropReason::NoProgress {
3931            warn!(
3932                "{} Walk of {} fetched nothing: not kept, the UTXO fails (bsv-low #555)",
3933                self.log_prefix, outpoint
3934            );
3935        } else {
3936            self.note_dropped(&outpoint, why);
3937        }
3938    }
3939
3940    /// Whether the walk in hand has PAID for a record (the delta-2 fold's
3941    /// D2-L1): half its per-graph calls made in this pass, or its half
3942    /// deadline fallen due. A walk that holds no node never has.
3943    async fn walk_paid(&self) -> bool {
3944        let Some(budget) = &self.graph_budget else {
3945            return false;
3946        };
3947        let mut half = {
3948            let mut guard = self.walk.borrow_mut();
3949            let Some(walk) = guard.as_mut() else {
3950                return false;
3951            };
3952            if walk.record.nodes.is_empty() {
3953                return false;
3954            }
3955            if u64::from(walk.calls_this_pass) * 2 >= u64::from(budget.max_calls) {
3956                return true;
3957            }
3958            match walk.half.take() {
3959                Some(half) => half,
3960                None => return false,
3961            }
3962        };
3963        let paid = Self::due(&mut half).await;
3964        if let Some(walk) = self.walk.borrow_mut().as_mut() {
3965            walk.half = Some(half);
3966        }
3967        paid
3968    }
3969
3970    /// Drop the partial walk, preserving a retry obligation if the cursor may have passed.
3971    async fn drop_record(&self, outpoint: &str, reason: DropReason) {
3972        if !matches!(reason, DropReason::Held | DropReason::Refused) {
3973            let Ok(record) = self.storage.get_deferred_graph(outpoint).await else {
3974                return;
3975            };
3976            if let Some(record) = record {
3977                if record.cursor_passable {
3978                    let mut retry = Self::fresh_walk(record.score, outpoint, PassCap::NONE).record;
3979                    retry.reason = "retry".into();
3980                    retry.cursor_passable = true;
3981                    let _ = self.storage.save_deferred_graph(&retry).await;
3982                    self.note_dropped(outpoint, reason);
3983                    return;
3984                }
3985            }
3986        }
3987        if let Err(e) = self.storage.delete_deferred_graph(outpoint).await {
3988            warn!(
3989                "{} Could not delete the record of deferred graph {}: {}",
3990                self.log_prefix, outpoint, e
3991            );
3992        }
3993        self.forget_record(outpoint);
3994        self.note_dropped(outpoint, reason);
3995    }
3996
3997    fn note_dropped(&self, outpoint: &str, reason: DropReason) {
3998        warn!(
3999            "{} Deferred graph {} DROPPED ({}) (bsv-low #555)",
4000            self.log_prefix,
4001            outpoint,
4002            reason.as_str()
4003        );
4004        self.stats.borrow_mut().dropped.push(DroppedGraph {
4005            outpoint: outpoint.to_string(),
4006            reason,
4007        });
4008    }
4009
4010    /// Save the walk of the graph that was in hand when a deadline dropped
4011    /// `sync` (bsv-low #555): the per-peer deadline (D16) defers it like the
4012    /// per-graph one, so the next pass resumes it instead of walking it
4013    /// again. No-op without a per-graph budget.
4014    ///
4015    /// The graph in flight is HELD at once, whatever it fetched: its root
4016    /// outpoint and partial walk become a durable record (reason
4017    /// `peer_deadline`) the next sync resumes ahead of its pages, so the
4018    /// cursor passes it to the page's last finished score. Before 0.1.8 a
4019    /// graph the deadline met before its root came back was only a retry,
4020    /// and the next run re-read the same page behind it (bsv-low #552:
4021    /// "the graph in flight is lost whole"). A graph the deadline met after
4022    /// its refusal is finished, not held. A graph that cannot be held (no
4023    /// room) stays the cursor's gap and is named in `cursor_held_by`.
4024    pub async fn defer_in_flight(&mut self) {
4025        let in_flight = self.in_flight.take();
4026        if self.graph_budget.is_none() {
4027            return;
4028        }
4029        if let Some((_, outpoint)) = &in_flight {
4030            if self.expired.borrow().contains(outpoint) {
4031                let outpoint = outpoint.clone();
4032                self.walk.borrow_mut().take();
4033                self.completed_cursor = self.cursor_after_in_flight;
4034                self.release_hold(&outpoint);
4035                return;
4036            }
4037        }
4038        // An unanchorable root cut mid-walk stays unanchorable (engine
4039        // 0.1.9): its record is kept, its backoff starts again, the cursor
4040        // passes it as before. A root whose fault streak is still under the
4041        // threshold is held at the deadline as any graph in flight.
4042        let unanchorable = self
4043            .walk
4044            .borrow()
4045            .as_ref()
4046            .and_then(|w| w.struck.as_deref().filter(|r| r.is_unanchorable()).cloned());
4047        if let Some(record) = unanchorable {
4048            self.walk.borrow_mut().take();
4049            let outpoint = record.outpoint.clone();
4050            if let Err(e) = self.keep_unanchorable(&record).await {
4051                warn!(
4052                    "{} Could not keep unanchorable root {} at the deadline: {}",
4053                    self.log_prefix, outpoint, e
4054                );
4055            }
4056            self.completed_cursor = self.cursor_after_in_flight;
4057            self.release_hold(&outpoint);
4058            return;
4059        }
4060        // A deadline during pagination has no graph to save. Preserve the
4061        // completed cursor, including any earlier unsaved gap.
4062        if self.walk.borrow().is_none() {
4063            let Some((score, outpoint)) = in_flight else {
4064                return;
4065            };
4066            *self.walk.borrow_mut() = Some(Self::fresh_walk(score, &outpoint, PassCap::NONE));
4067        }
4068        let outpoint = self
4069            .walk
4070            .borrow()
4071            .as_ref()
4072            .map(|w| w.record.outpoint.clone())
4073            .unwrap_or_default();
4074        match self.save_walk("peer_deadline", false).await {
4075            Saved::Yes => {
4076                self.completed_cursor = self.cursor_after_in_flight;
4077                self.release_hold(&outpoint);
4078            }
4079            Saved::Unkept(why, mut walk) => self.unkept(why, &mut walk).await,
4080            _ => {}
4081        }
4082    }
4083
4084    /// The graph id of the walk in hand: its root's, else the outpoint.
4085    fn graph_id_of(walk: Option<&Walk>, outpoint: &str) -> String {
4086        walk.and_then(|w| w.record.nodes.first())
4087            .map_or_else(|| outpoint.to_string(), |w| w.node.graph_id.clone())
4088    }
4089
4090    /// `txid.outputIndex` of a node, its txid computed from its raw bytes.
4091    fn node_id(node: &GASPNode) -> Option<String> {
4092        bsv_rs::transaction::Transaction::from_hex(&node.raw_tx)
4093            .ok()
4094            .map(|tx| format!("{}.{}", tx.id(), node.output_index))
4095    }
4096
4097    /// Count a node the graph in hand was SERVED (bsv-low #586): the bytes
4098    /// the peer sent for it, which are the bytes a record keeps of it.
4099    fn count_fetched(&self, node: &GASPNode) {
4100        let bytes = (node.raw_tx.len() + node.proof.as_ref().map_or(0, String::len)) as u64;
4101        self.bytes_fetched.set(self.bytes_fetched.get() + bytes);
4102        if let Some(w) = self.walk.borrow_mut().as_mut() {
4103            w.bytes_this_pass += bytes;
4104        }
4105    }
4106
4107    /// Count one call of the graph in hand.
4108    fn count_call(&self) {
4109        self.calls_made.set(self.calls_made.get() + 1);
4110        if let Some(w) = self.walk.borrow_mut().as_mut() {
4111            w.calls_this_pass += 1;
4112            w.record.calls += 1;
4113        }
4114    }
4115
4116    /// Push a local UTXO's graph to the remote.
4117    async fn push_utxo(&self, utxo: &GASPOutput) -> Result<(), GASPError> {
4118        let outpoint = format!("{}.{}", utxo.txid, utxo.output_index);
4119        debug!("{} Hydrating node for {}", self.log_prefix, outpoint);
4120
4121        let node = self
4122            .storage
4123            .hydrate_gasp_node(&outpoint, &utxo.txid, utxo.output_index, true)
4124            .await?;
4125
4126        self.process_outgoing_node(&node, &mut std::collections::HashSet::new())
4127            .await?;
4128
4129        Ok(())
4130    }
4131
4132    fn root_bound(&self, reason: &'static str) -> WalkEnd {
4133        self.last_fault.set(None);
4134        if let Some(walk) = self.walk.borrow().as_ref() {
4135            self.stats
4136                .borrow_mut()
4137                .root_bounds
4138                .push(crate::sync_load::RootBound {
4139                    peer: String::new(),
4140                    outpoint: walk.record.outpoint.clone(),
4141                    reason: reason.into(),
4142                });
4143        }
4144        WalkEnd::Deferred(reason)
4145    }
4146
4147    /// Walk the graph in hand until nothing is pending (an explicit stack,
4148    /// bsv-low #555; before it a recursion, in the same order: an input's
4149    /// whole branch before its next sibling). Each step's result is
4150    /// committed to the walk only once the step has finished, so a deadline
4151    /// that drops this future leaves the walk as it was before that step.
4152    /// With a per-graph budget the walk stops at a counted limb of it (its
4153    /// calls; the bytes it was served or the nodes it appended, bsv-low #586)
4154    /// or at its `deadline`, and answers `Deferred` with the limb's name;
4155    /// without one it runs to its end. A limb is read BEFORE a step, so a
4156    /// pass always makes one: no node is too big to walk.
4157    async fn walk_graph(
4158        &self,
4159        mut deadline: Option<&mut crate::engine::SleepFuture>,
4160    ) -> Result<WalkEnd, GASPError> {
4161        loop {
4162            let (item, over) = {
4163                let walk = self.walk.borrow();
4164                let Some(walk) = walk.as_ref() else {
4165                    return Ok(WalkEnd::Done);
4166                };
4167                (
4168                    walk.record.pending.last().cloned(),
4169                    self.graph_budget.as_ref().and_then(|_| walk.over()),
4170                )
4171            };
4172            let Some(item) = item else {
4173                return Ok(WalkEnd::Done);
4174            };
4175            // One failed round trip per decoy: an outpoint pruned earlier in
4176            // this sync is not asked for again, even when a later graph of
4177            // the sync names it (two UTXOs of one decoy-bearing transaction).
4178            if item.parent_proven && self.pruned.borrow().contains(&item.outpoint) {
4179                debug!(
4180                    "{} Input {} of {:?} was already pruned in this sync; not re-requested",
4181                    self.log_prefix, item.outpoint, item.spent_by
4182                );
4183                if let Some(w) = self.walk.borrow_mut().as_mut() {
4184                    w.record.pending.pop();
4185                }
4186                continue;
4187            }
4188            if let Some(limb) = over {
4189                return Ok(WalkEnd::Deferred(limb));
4190            }
4191            let step = self.step(&item);
4192            let out = match deadline.as_mut() {
4193                Some(deadline) => match race_or_deadline(step, deadline.as_mut()).await {
4194                    Some(out) => out,
4195                    None => return Ok(self.root_bound("time")),
4196                },
4197                None => step.await,
4198            };
4199            if crate::meter::root_exhausted() || matches!(out, Err(GASPError::CourierBudget)) {
4200                return Ok(self.root_bound("courier_rungs"));
4201            }
4202            let out = out?;
4203            if matches!(out, StepOut::Expired) {
4204                return Ok(WalkEnd::Expired);
4205            }
4206            self.commit(out);
4207        }
4208    }
4209
4210    /// Commit one finished step to the walk in hand: its item is no longer
4211    /// pending, and an appended node's needed inputs are, the first of them
4212    /// on top.
4213    fn commit(&self, out: StepOut) {
4214        let mut walk = self.walk.borrow_mut();
4215        let Some(walk) = walk.as_mut() else {
4216            return;
4217        };
4218        walk.record.pending.pop();
4219        if let StepOut::Appended {
4220            node_id,
4221            walked,
4222            children,
4223        } = out
4224        {
4225            walk.seen.insert(node_id);
4226            walk.nodes_this_pass += 1;
4227            self.nodes_appended.set(self.nodes_appended.get() + 1);
4228            walk.record.nodes.push(*walked);
4229            walk.record.pending.extend(children.into_iter().rev());
4230        }
4231    }
4232
4233    /// The walk from a root already in hand (the lib tests' entry, from
4234    /// before the walk was a stack): its proof hydrated, then every needed
4235    /// input to the end.
4236    #[cfg(test)]
4237    async fn process_incoming_node(
4238        &self,
4239        node: &GASPNode,
4240        _spent_by: Option<&str>,
4241        _seen: &mut std::collections::HashSet<String>,
4242    ) -> Result<(), GASPError> {
4243        let root = PendingInput {
4244            outpoint: node.graph_id.clone(),
4245            graph_id: node.graph_id.clone(),
4246            metadata: true,
4247            spent_by: None,
4248            parent_proven: false,
4249        };
4250        *self.walk.borrow_mut() = Some(Walk {
4251            record: DeferredGraph {
4252                peer: String::new(),
4253                topic: String::new(),
4254                outpoint: node.graph_id.clone(),
4255                score: 0,
4256                nodes: Vec::new(),
4257                pending: vec![root.clone()],
4258                calls: 0,
4259                passes: 0,
4260                reason: String::new(),
4261                configured: false,
4262                idle_faults: 0,
4263                cursor_passable: false,
4264                faults: 0,
4265                retry_at: 0,
4266                idle_resumes: 0,
4267                unanchorable_retries: 0,
4268                expiry: None,
4269            },
4270            seen: std::collections::HashSet::new(),
4271            calls_this_pass: 0,
4272            bytes_this_pass: 0,
4273            nodes_this_pass: 0,
4274            resumed: false,
4275            cap: PassCap::NONE,
4276            nodes_at_start: 0,
4277            counted: false,
4278            gone_on: false,
4279            half: None,
4280            struck: None,
4281        });
4282        let node = self.hydrate_root(node.clone()).await;
4283        let out = self.absorb(&root, node).await?;
4284        self.commit(out);
4285        self.walk_graph(None).await.map(|_| ())
4286    }
4287
4288    /// The ROOT of a graph: the peer's node for the UTXO, its own proof
4289    /// hydrated by the ancestor fetcher when it has none.
4290    async fn fetch_root(&self, item: &PendingInput) -> Result<Option<GASPNode>, GASPError> {
4291        let (txid, oi) = parse_outpoint(&item.outpoint)
4292            .ok_or_else(|| GASPError::Other(format!("bad outpoint {}", item.outpoint)))?;
4293        self.count_call();
4294        let node = self
4295            .remote
4296            .request_node(&item.graph_id, &txid, oi, item.metadata)
4297            .await?;
4298        self.count_fetched(&node);
4299        if self.root_expired(&node, &item.outpoint)? {
4300            return Ok(None);
4301        }
4302        Ok(Some(self.hydrate_root(node).await))
4303    }
4304
4305    /// The root's own proof, hydrated by the ancestor fetcher when the peer
4306    /// served it with none.
4307    async fn hydrate_root(&self, mut node: GASPNode) -> GASPNode {
4308        // The peer already supplied the raw. Ask our proof source for only
4309        // its verified BUMP, inside the graph and peer deadlines. Production
4310        // re-verifies courier proofs against CHAINTRACKS; the graph's anchor
4311        // check still runs before any admission. A resumed proofless root
4312        // takes this path too, so a kept graph can land once its proof exists.
4313        if node.proof.is_none() {
4314            if let Some(fetcher) = &self.ancestor_fetcher {
4315                if let Some(node_txid) =
4316                    Self::node_id(&node).and_then(|id| parse_outpoint(&id).map(|(txid, _)| txid))
4317                {
4318                    self.count_call();
4319                    node.proof = fetcher.verified_proof_for(&node_txid).await;
4320                }
4321            }
4322        }
4323        self.root_proofs
4324            .borrow_mut()
4325            .insert(node.graph_id.clone(), node.proof.is_some());
4326        node
4327    }
4328
4329    /// One step of the walk: fetch `item`, append it to the graph, name its
4330    /// needed inputs. Nothing of the walk is changed here (see
4331    /// [`Self::walk_graph`]).
4332    async fn step(&self, item: &PendingInput) -> Result<StepOut, GASPError> {
4333        // THE D8 DECOY RULE (zanaadu-v2 #314, the owner's ruling of
4334        // 2026-10-06). A DELIBERATE DIVERGENCE from the reference.
4335        //
4336        // The reference requests every needed input with no catch
4337        // (`GASP.ts:602`, `await this.remote.requestNode(...)` inside
4338        // `processIncomingNode`), so one input the peer cannot serve
4339        // throws out of the walk and the per-UTXO catch in `sync`
4340        // drops that whole UTXO: the graph is never completed.
4341        //
4342        // We keep that for an UNPROVEN parent and diverge for a PROVEN
4343        // one. A proven parent needs no input for SPV; the only
4344        // inputs `find_needed_inputs` returns for it are the ones its
4345        // topic manager NAMED as history. A manager cannot always
4346        // tell which input is the real one: a head covenant that
4347        // signs under ANYONECANPAY lets a spender place a decoy
4348        // witness-shaped input ahead of the real head input, and once
4349        // mined it is permanent. The pairing is that such a manager
4350        // names EVERY witness-shaped input, and the engine PRUNES the
4351        // branch of a named input the PEER DEFINITELY DOES NOT HOLD
4352        // instead of discarding the graph: warn, count, carry on with
4353        // the parent's other named inputs, complete the graph with
4354        // what it has. Under the reference's rule one decoy would
4355        // strand the chain behind it on every sync, forever.
4356        //
4357        // An unproven parent's inputs are SPV necessities, not named
4358        // history: a missing one still fails the UTXO (the `?` below),
4359        // exactly as the reference does.
4360        //
4361        // THE CLASSIFICATION RULE. A named input is pruned only on a
4362        // DEFINITE answer: the peer said it does not hold the
4363        // outpoint, the typed class `GASPError::NodeNotFound`. Every
4364        // other error (the request could not be sent, a timeout, a
4365        // 5xx, a 429, a body that does not parse) is a fault of the
4366        // moment and says nothing about what the peer holds: it
4367        // fails the UTXO as the reference does, the per-UTXO arm of
4368        // `sync` records it in the cursor gap guard, and the next
4369        // sync asks again. Pruning on such a fault would cut the
4370        // REAL head input, finalize a truncated graph, advance the
4371        // cursor and never ask for that history again. The remote
4372        // decides the class: the worker's maps HTTP 400 from
4373        // `/requestForeignGASPNode` to `NodeNotFound` and nothing
4374        // else (`gasp_remote.rs`), because 400 is what the reference
4375        // peer answers for an outpoint it does not hold. Accepted
4376        // residual: the reference answers the same masked 400 when
4377        // its own storage faults inside `provideForeignGASPNode`, so
4378        // that fault at a reference peer reads as "not held".
4379        //
4380        // THE FETCHER ARM NEVER PRUNES. A chain fetcher has no
4381        // definite "cannot serve": every input of a mined transaction
4382        // exists on chain, so each of its errors is a fault of the
4383        // moment (its per-tick budget, a provider outage, a rate
4384        // limit), whatever class it carries. With a real chain
4385        // fetcher a decoy is SERVED from chain (one fetch, no failed
4386        // round trip, no prune), so the prune lives on the peer arm,
4387        // which is what runs when no fetcher is installed.
4388        //
4389        // NOTHING HERE BOUNDS THE DECOYS OF ONE PARENT. The manager's
4390        // list has no cap, and each definite decoy is one sequential
4391        // failed round trip inside the per-peer sync budget. A parent
4392        // with enough of them exceeds that budget and the sync is
4393        // dropped whole; what a dropped sync keeps is bsv-low #552's
4394        // ground, and a cap on the list is the manager's choice.
4395        // Each failure below is marked with its fault class (engine 0.1.9),
4396        // read where the root is dropped.
4397        let node = if item.spent_by.is_none() {
4398            let Some(node) = self
4399                .fetch_root(item)
4400                .await
4401                .map_err(|e| self.faulted(Self::peer_fault_class(&e), e))?
4402            else {
4403                return Ok(StepOut::Expired);
4404            };
4405            node
4406        } else {
4407            let Some((txid, oi)) = parse_outpoint(&item.outpoint) else {
4408                return Ok(StepOut::Pruned);
4409            };
4410            match &self.ancestor_fetcher {
4411                // OPT-IN ancestry hydration (off by default). When a
4412                // fetcher is configured we KNOW the peer cannot serve
4413                // ancestry — e.g. legacy beta stores minimal BEEFs and
4414                // returns HTTP 400 "Incomplete SPV data!" for every
4415                // ancestor — so we SKIP the doomed peer round-trip
4416                // entirely and fetch the ancestor's raw tx from chain
4417                // directly. Asking the peer first would cost one
4418                // sequential request per ancestor (the ~90-deep
4419                // user_registry chain → ~90 round-trips), enough to
4420                // exhaust a worker invocation before the graph finalizes.
4421                //
4422                // The fetcher returns the ancestor's rawtx and, when it
4423                // is mined, its BUMP proof. A proven node ends the walk
4424                // UNLESS its topic manager names inputs. Empty managers
4425                // still stop at the first proven layer; managers needing
4426                // history select their ancestors through this same
4427                // fetcher. Without a proof, every input is requested
4428                // as before.
4429                // The transaction DAG (no cycles), `seen` keyed by
4430                // `txid.outputIndex`, the already-known strip, and the
4431                // manager naming nothing at genesis bound the walk.
4432                // There is no node cap, matching the reference's
4433                // undefined `maxNodesInGraph` in `Engine.startGASPSync`.
4434                // A per-peer budget drops the sync future at its
4435                // deadline: graphs finalized before it stay admitted
4436                // (bsv-low #552), the graph in flight is lost whole,
4437                // and ONE graph whose own walk outlasts the budget
4438                // never completes unless a per-graph budget defers and
4439                // resumes it (bsv-low #555).
4440                //
4441                // Every fetcher error fails the UTXO: the fetcher arm
4442                // never prunes, see the rule above.
4443                //
4444                // THE PEER DECIDES ABSENCE (engine 0.1.15, #56). An input
4445                // of an UNPROVEN node the fetcher cannot serve is asked of
4446                // the peer, one request: a rung fetches, it never decides.
4447                // On a deployment with no rung configured (the stack's
4448                // production since 2026-10-14) the fetcher answers every
4449                // such input "exhausted" with no request, so before 0.1.15
4450                // the peer was never asked and a graph the chain never
4451                // held was named `courier`, never the absence it is. The
4452                // peer serving it, the walk goes on; its `NodeNotFound` is
4453                // its word that nothing of this graph can anchor
4454                // ([`fault_class::NOT_FOUND`]); any other answer keeps the
4455                // fetcher's error and class. A proven node's named inputs
4456                // and a spent courier budget are as before.
4457                Some(fetcher) => {
4458                    self.count_call();
4459                    let ancestor = match fetcher.fetch_ancestor(&txid).await {
4460                        Ok(ancestor) => ancestor,
4461                        Err(e) => {
4462                            let class = if matches!(e, GASPError::DefinitiveNotFound(_)) {
4463                                fault_class::NOT_FOUND
4464                            } else {
4465                                fault_class::COURIER
4466                            };
4467                            if item.parent_proven
4468                                || matches!(e, GASPError::CourierBudget)
4469                                || crate::meter::root_exhausted()
4470                            {
4471                                return Err(self.faulted(class, e));
4472                            }
4473                            return match self.ask_peer_for_input(item, &txid, oi).await {
4474                                Ok(node) => self
4475                                    .absorb(item, node)
4476                                    .await
4477                                    .map_err(|e| self.faulted(fault_class::VERIFICATION, e)),
4478                                Err(peer @ GASPError::NodeNotFound(_)) => {
4479                                    Err(self.faulted(fault_class::NOT_FOUND, peer))
4480                                }
4481                                Err(_) => Err(self.faulted(class, e)),
4482                            };
4483                        }
4484                    };
4485                    let node = GASPNode {
4486                        graph_id: item.graph_id.clone(),
4487                        raw_tx: ancestor.raw_tx,
4488                        output_index: oi,
4489                        proof: ancestor.proof,
4490                        tx_metadata: None,
4491                        output_metadata: None,
4492                        inputs: None,
4493                    };
4494                    self.count_fetched(&node);
4495                    node
4496                }
4497                // No fetcher, an unproven parent: ask the peer; its
4498                // `NodeNotFound` is absence (engine 0.1.15), remembered for
4499                // the rest of the sync.
4500                None if !item.parent_proven => self
4501                    .ask_peer_for_input(item, &txid, oi)
4502                    .await
4503                    .map_err(|e| self.faulted(Self::peer_fault_class(&e), e))?,
4504                // No fetcher, a proven parent → ask the peer.
4505                None => {
4506                    self.count_call();
4507                    match self
4508                        .remote
4509                        .request_node(&item.graph_id, &txid, oi, item.metadata)
4510                        .await
4511                    {
4512                        Ok(child_node) => {
4513                            self.count_fetched(&child_node);
4514                            child_node
4515                        }
4516                        // Proven parent and a DEFINITE "not held": the D8 prune
4517                        // (see the rule above).
4518                        Err(e @ GASPError::NodeNotFound(_)) if item.parent_proven => {
4519                            warn!(
4520                            "{} Pruned input {} named by proven node {}: the peer does not hold it: {}",
4521                            self.log_prefix,
4522                            item.outpoint,
4523                            item.spent_by.as_deref().unwrap_or_default(),
4524                            e
4525                        );
4526                            if self.pruned.borrow_mut().insert(item.outpoint.clone()) {
4527                                self.pruned_inputs.set(self.pruned_inputs.get() + 1);
4528                            }
4529                            return Ok(StepOut::Pruned);
4530                        }
4531                        // Any other error: propagate, as the reference does.
4532                        Err(e) => return Err(self.faulted(Self::peer_fault_class(&e), e)),
4533                    }
4534                }
4535            }
4536        };
4537        self.absorb(item, node)
4538            .await
4539            .map_err(|e| self.faulted(fault_class::VERIFICATION, e))
4540    }
4541
4542    /// Ask the peer for `item`, an input an UNPROVEN node needs (engine
4543    /// 0.1.15): one request, or none when the peer already answered in this
4544    /// sync that it does not hold it (counted a peer-absence memo hit).
4545    async fn ask_peer_for_input(
4546        &self,
4547        item: &PendingInput,
4548        txid: &str,
4549        output_index: u32,
4550    ) -> Result<GASPNode, GASPError> {
4551        if self.absent.borrow().contains(&item.outpoint) {
4552            crate::meter::peer_absent_memo_hit();
4553            return Err(GASPError::NodeNotFound(format!(
4554                "{}: the peer answered it does not hold it earlier in this sync",
4555                item.outpoint
4556            )));
4557        }
4558        self.count_call();
4559        match self
4560            .remote
4561            .request_node(&item.graph_id, txid, output_index, item.metadata)
4562            .await
4563        {
4564            Ok(node) => {
4565                self.count_fetched(&node);
4566                Ok(node)
4567            }
4568            Err(e) => {
4569                if matches!(e, GASPError::NodeNotFound(_)) {
4570                    self.absent.borrow_mut().insert(item.outpoint.clone());
4571                }
4572                Err(e)
4573            }
4574        }
4575    }
4576
4577    /// The node of `item`, fetched: append it to the graph and name its
4578    /// needed inputs.
4579    async fn absorb(&self, item: &PendingInput, node: GASPNode) -> Result<StepOut, GASPError> {
4580        // Key by the node's own TXID (computed from raw_tx), NOT graph_id (which
4581        // is constant across a whole graph) and NOT the raw_tx hex. Mirrors TS
4582        // @bsv/gasp processIncomingNode: nodeId = `${computeTXID(rawTx)}.${oi}`
4583        // (GASP.js:319) and spentBy = compute36ByteStructure(computeTXID(rawTx), oi)
4584        // (GASP.js:335). Matches the append-side key in gasp_overlay.rs
4585        // (Transaction::from_hex(raw_tx).id()). Using graph_id/raw_tx here orphaned
4586        // every child node → multi-node graphs never assembled → stranded sync.
4587        let node_txid = match bsv_rs::transaction::Transaction::from_hex(&node.raw_tx) {
4588            Ok(tx) => tx.id(),
4589            Err(_) => node.raw_tx[..node.raw_tx.len().min(64)].to_string(),
4590        };
4591        let node_id = format!("{}.{}", node_txid, node.output_index);
4592        if self
4593            .walk
4594            .borrow()
4595            .as_ref()
4596            .is_some_and(|w| w.seen.contains(&node_id))
4597        {
4598            return Ok(StepOut::Seen);
4599        }
4600
4601        self.storage
4602            .append_to_graph(&node, item.spent_by.as_deref())
4603            .await?;
4604
4605        let mut children = Vec::new();
4606        if let Some(needed) = self.storage.find_needed_inputs(&node).await? {
4607            let parent_proven = node.proof.is_some();
4608            for (outpoint, input_req) in &needed.requested_inputs {
4609                if parse_outpoint(outpoint).is_some() {
4610                    children.push(PendingInput {
4611                        outpoint: outpoint.clone(),
4612                        graph_id: node.graph_id.clone(),
4613                        metadata: input_req.metadata,
4614                        spent_by: Some(node_id.clone()),
4615                        parent_proven,
4616                    });
4617                }
4618            }
4619        }
4620        Ok(StepOut::Appended {
4621            node_id,
4622            walked: Box::new(WalkedNode {
4623                node,
4624                spent_by: item.spent_by.clone(),
4625            }),
4626            children,
4627        })
4628    }
4629
4630    /// Process an outgoing node: submit to remote, then recursively send requested inputs.
4631    fn process_outgoing_node<'b>(
4632        &'b self,
4633        node: &'b GASPNode,
4634        seen: &'b mut std::collections::HashSet<String>,
4635    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), GASPError>> + 'b>> {
4636        Box::pin(async move {
4637            if self.unidirectional {
4638                return Ok(());
4639            }
4640
4641            let node_id = format!("{}.{}", node.graph_id, node.output_index);
4642            if seen.contains(&node_id) {
4643                return Ok(());
4644            }
4645            seen.insert(node_id);
4646
4647            if let Some(response) = self.remote.submit_node(node).await? {
4648                for (outpoint, input_req) in &response.requested_inputs {
4649                    if let Some((txid, oi)) = parse_outpoint(outpoint) {
4650                        match self
4651                            .storage
4652                            .hydrate_gasp_node(&node.graph_id, &txid, oi, input_req.metadata)
4653                            .await
4654                        {
4655                            Ok(hydrated) => {
4656                                self.process_outgoing_node(&hydrated, seen).await?;
4657                            }
4658                            Err(e) => {
4659                                error!("{} Error hydrating outgoing node: {}", self.log_prefix, e);
4660                                return Ok(()); // Stop this branch, remote will discard
4661                            }
4662                        }
4663                    }
4664                }
4665            }
4666
4667            Ok(())
4668        })
4669    }
4670
4671    /// Validate and finalize a completed graph, or discard on failure.
4672    /// `Ok(true)`: finalized; `Ok(false)`: refused by the anchor check and
4673    /// discarded (a verdict: the cursor moves past it).
4674    async fn complete_graph(&self, graph_id: &str) -> Result<bool, GASPError> {
4675        info!("{} Completing graph: {}", self.log_prefix, graph_id);
4676        match self.storage.validate_graph_anchor(graph_id).await {
4677            Ok(()) => {
4678                self.storage.finalize_graph(graph_id).await?;
4679                let proven =
4680                    self.root_proofs
4681                        .borrow_mut()
4682                        .remove(graph_id)
4683                        .or_else(|| {
4684                            self.walk.borrow().as_ref().and_then(|w| {
4685                                match w.record.nodes.as_slice() {
4686                                    [root, ..] => Some(root.node.proof.is_some()),
4687                                    [] => None,
4688                                }
4689                            })
4690                        })
4691                        .unwrap_or(false);
4692                let count = if proven {
4693                    &self.roots_proven
4694                } else {
4695                    &self.roots_unproven
4696                };
4697                count.set(count.get() + 1);
4698                info!("{} Graph finalized: {}", self.log_prefix, graph_id);
4699                Ok(true)
4700            }
4701            Err(e) => {
4702                warn!(
4703                    "{} Graph validation failed for {}: {}. Discarding.",
4704                    self.log_prefix, graph_id, e
4705                );
4706                self.storage.discard_graph(graph_id).await?;
4707                // The anchor could not be checked (a tracker outage, a
4708                // storage fault, a topic manager that answered the replay
4709                // with an error): no verdict. Fail the UTXO so the gap guard
4710                // re-requests it, instead of advancing the cursor past a
4711                // graph nobody judged (a divergence by addition, bsv-low
4712                // #551: the reference discards and moves on either way).
4713                if matches!(e, GASPError::AnchorUnavailable(_)) {
4714                    return Err(e);
4715                }
4716                // A walk past the budget: held the same way, counted apart
4717                // (the E592 lens fold, H1 and L3).
4718                if matches!(e, GASPError::AnchorWalkHeld(_)) {
4719                    self.anchor_walk_held.set(self.anchor_walk_held.get() + 1);
4720                    return Err(e);
4721                }
4722                self.discarded_graphs.set(self.discarded_graphs.get() + 1);
4723                Ok(false)
4724            }
4725        }
4726    }
4727}
4728
4729/// Parse "txid.outputIndex" into components.
4730pub fn parse_outpoint(s: &str) -> Option<(String, u32)> {
4731    let parts: Vec<&str> = s.splitn(2, '.').collect();
4732    if parts.len() != 2 {
4733        return None;
4734    }
4735    let oi = parts[1].parse::<u32>().ok()?;
4736    Some((parts[0].to_string(), oi))
4737}
4738
4739// ============================================================================
4740// Error type
4741// ============================================================================
4742
4743/// GASP protocol errors.
4744#[derive(Debug, Clone, thiserror::Error)]
4745pub enum GASPError {
4746    /// Every enabled raw rung answered absence, with no skipped or failed rung.
4747    /// Since engine 0.1.15 it counts one run of absence beside the peer's
4748    /// word ([`fault_class::NOT_FOUND`]), never a strike by itself.
4749    #[error("all raw couriers report not found: {0}")]
4750    DefinitiveNotFound(String),
4751    /// The pass spent its courier allowance; retain its pending walk.
4752    #[error("root courier rung budget exhausted")]
4753    CourierBudget,
4754    /// Version mismatch between peers.
4755    #[error("version mismatch: local={local}, remote={remote}")]
4756    VersionMismatch { local: u32, remote: u32 },
4757
4758    /// Invalid timestamp format.
4759    #[error("invalid timestamp: {0}")]
4760    InvalidTimestamp(String),
4761
4762    /// Node not found.
4763    #[error("node not found: {0}")]
4764    NodeNotFound(String),
4765
4766    /// Graph validation failed.
4767    #[error("graph validation failed: {0}")]
4768    ValidationFailed(String),
4769
4770    /// Network/communication error.
4771    #[error("remote error: {0}")]
4772    RemoteError(String),
4773
4774    /// The platform answered before the peer was reached (engine 0.2.0,
4775    /// bsv-overlay-cloudflare #57; [`crate::route_fault`]): a fault of the
4776    /// route, never of the peer. It counts nothing against the peer's
4777    /// health rows and is named `route_fault:<class>`.
4778    #[error("route_fault:{class}: {detail}")]
4779    RouteFault { class: String, detail: String },
4780
4781    /// Storage error.
4782    #[error("storage error: {0}")]
4783    StorageError(String),
4784
4785    /// A graph's anchor could not be CHECKED right now (the chain tracker or
4786    /// a storage read faulted, or the topic manager answered the replay with
4787    /// an error): a fault of the moment, not a verdict on the graph. `GASPSync::complete_graph` discards the graph and fails the
4788    /// UTXO, so the cursor gap guard asks for it again (bsv-low #551).
4789    #[error("anchor unavailable: {0}")]
4790    AnchorUnavailable(String),
4791
4792    /// The anchor's script walk could not run within the engine's walk
4793    /// budget (bsv-low #592; the E592 lens fold, H1): no verdict, and
4794    /// nothing stands in for one (no network accepted these bytes). Held
4795    /// exactly as [`GASPError::AnchorUnavailable`] holds: the graph is not
4796    /// finalized, the UTXO fails and the cursor stays below it, until the
4797    /// peer serves its root PROVEN (#555's `root_proven` restart, whose walk
4798    /// trusts the proof and runs no script). Counted apart
4799    /// (`GASPSync::anchor_walk_held`).
4800    #[error("anchor walk held: {0}")]
4801    AnchorWalkHeld(String),
4802
4803    /// Generic error.
4804    #[error("{0}")]
4805    Other(String),
4806}
4807
4808// ============================================================================
4809// Tests
4810// ============================================================================
4811
4812#[cfg(test)]
4813mod tests {
4814    use super::*;
4815    use std::collections::HashMap;
4816    use std::sync::Mutex;
4817
4818    // ── race_or_deadline (bsv-low#257/#302, generalized here) ──────────
4819
4820    #[tokio::test]
4821    async fn race_or_deadline_future_wins() {
4822        let out = race_or_deadline(async { 42u32 }, std::future::pending::<()>()).await;
4823        assert_eq!(out, Some(42));
4824    }
4825
4826    #[tokio::test]
4827    async fn race_or_deadline_deadline_wins() {
4828        let out = race_or_deadline(std::future::pending::<u32>(), async {}).await;
4829        assert_eq!(out, None);
4830    }
4831
4832    // The lens fold's HIGH-1: a deadline that falls due inside a write
4833    // section waits for the section to close, then drops the future at its
4834    // next pending point; the writer that asks at the boundary stops there.
4835    #[tokio::test]
4836    async fn guarded_race_never_drops_inside_a_write_section() {
4837        let gate = SubmitGate::default();
4838        let written = std::cell::Cell::new(0u32);
4839        let out = race_or_deadline_guarded(
4840            async {
4841                for _ in 0..3 {
4842                    gate.stop_if_due().await;
4843                    let _section = gate.write_section();
4844                    // Two writes of one transaction, each a round trip.
4845                    tokio::task::yield_now().await;
4846                    written.set(written.get() + 1);
4847                    tokio::task::yield_now().await;
4848                    written.set(written.get() + 1);
4849                }
4850            },
4851            async {},
4852            &gate,
4853        )
4854        .await;
4855        assert_eq!(out, None, "the deadline still wins");
4856        assert_eq!(written.get(), 2, "one transaction, whole, and no second");
4857        assert!(
4858            !gate.deadline_is_due(),
4859            "the flag does not outlive the race"
4860        );
4861
4862        // With no section open it is `race_or_deadline`.
4863        let out = race_or_deadline_guarded(std::future::pending::<u8>(), async {}, &gate).await;
4864        assert_eq!(out, None);
4865        let out = race_or_deadline_guarded(async { 7u8 }, std::future::pending(), &gate).await;
4866        assert_eq!(out, Some(7));
4867        // A future that finishes inside its section after the deadline wins.
4868        let out = race_or_deadline_guarded(
4869            async {
4870                let _section = gate.write_section();
4871                tokio::task::yield_now().await;
4872                7u8
4873            },
4874            async {},
4875            &gate,
4876        )
4877        .await;
4878        assert_eq!(out, Some(7));
4879        assert!(!gate.deadline_is_due());
4880    }
4881
4882    #[tokio::test]
4883    async fn race_or_deadline_ready_future_beats_ready_deadline() {
4884        // The sync future is polled FIRST — an instantly-ready result wins
4885        // even against an already-expired deadline (a completed sync is
4886        // never discarded).
4887        let out = race_or_deadline(async { 7u32 }, async {}).await;
4888        assert_eq!(out, Some(7));
4889    }
4890
4891    // ── peer_sync_quarantined (bsv-low#302 pure rule) ──────────────────
4892
4893    fn health(fails: u64, age: Option<u64>) -> crate::storage::PeerSyncHealth {
4894        crate::storage::PeerSyncHealth {
4895            consecutive_failures: fails,
4896            secs_since_last_attempt: age,
4897        }
4898    }
4899
4900    #[test]
4901    fn quarantine_needs_the_full_threshold() {
4902        assert!(!peer_sync_quarantined(&health(0, Some(0))));
4903        assert!(!peer_sync_quarantined(&health(
4904            PEER_QUARANTINE_THRESHOLD - 1,
4905            Some(0)
4906        )));
4907        assert!(peer_sync_quarantined(&health(
4908            PEER_QUARANTINE_THRESHOLD,
4909            Some(0)
4910        )));
4911        assert!(peer_sync_quarantined(&health(
4912            PEER_QUARANTINE_THRESHOLD + 100,
4913            Some(0)
4914        )));
4915    }
4916
4917    #[test]
4918    fn quarantine_reopens_one_probe_after_the_reprobe_window() {
4919        let fails = PEER_QUARANTINE_THRESHOLD;
4920        assert!(peer_sync_quarantined(&health(
4921            fails,
4922            Some(PEER_QUARANTINE_REPROBE_SECS - 1)
4923        )));
4924        // AT the window boundary the probe re-opens — a quarantined peer is
4925        // never stranded forever.
4926        assert!(!peer_sync_quarantined(&health(
4927            fails,
4928            Some(PEER_QUARANTINE_REPROBE_SECS)
4929        )));
4930    }
4931
4932    #[test]
4933    fn never_attempted_peer_is_never_quarantined() {
4934        // `None` age = pristine peer OR a backend without health tracking —
4935        // fail-safe: always attempted.
4936        assert!(!peer_sync_quarantined(&health(u64::MAX, None)));
4937    }
4938
4939    // ── Mock GASPStorage ───────────────────────────────────────────────
4940
4941    struct MockGASPStorage {
4942        utxos: Vec<GASPOutput>,
4943        graphs: Mutex<HashMap<String, Vec<GASPNode>>>,
4944        finalized: Mutex<Vec<String>>,
4945        discarded: Mutex<Vec<String>>,
4946    }
4947
4948    impl MockGASPStorage {
4949        fn new(utxos: Vec<GASPOutput>) -> Self {
4950            Self {
4951                utxos,
4952                graphs: Mutex::new(HashMap::new()),
4953                finalized: Mutex::new(Vec::new()),
4954                discarded: Mutex::new(Vec::new()),
4955            }
4956        }
4957    }
4958
4959    #[async_trait(?Send)]
4960    impl GASPStorage for MockGASPStorage {
4961        // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
4962        async fn load_deferred_graphs(
4963            &self,
4964        ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
4965            Ok(Vec::new())
4966        }
4967        async fn get_deferred_graph(
4968            &self,
4969            _: &str,
4970        ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
4971            Ok(None)
4972        }
4973        async fn save_deferred_graph(
4974            &self,
4975            _: &crate::gasp::DeferredGraph,
4976        ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
4977            Err(GASPError::StorageError("keeps no deferred graphs".into()))
4978        }
4979        async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
4980            Ok(())
4981        }
4982        async fn find_known_utxos(
4983            &self,
4984            since: u64,
4985            _limit: Option<u64>,
4986        ) -> Result<Vec<GASPOutput>, GASPError> {
4987            Ok(self
4988                .utxos
4989                .iter()
4990                .filter(|u| u.score as u64 >= since)
4991                .cloned()
4992                .collect())
4993        }
4994
4995        async fn hydrate_gasp_node(
4996            &self,
4997            graph_id: &str,
4998            txid: &str,
4999            output_index: u32,
5000            _metadata: bool,
5001        ) -> Result<GASPNode, GASPError> {
5002            Ok(GASPNode {
5003                graph_id: graph_id.to_string(),
5004                raw_tx: format!("rawtx_{txid}"),
5005                output_index,
5006                proof: None,
5007                tx_metadata: None,
5008                output_metadata: None,
5009                inputs: None,
5010            })
5011        }
5012
5013        async fn find_needed_inputs(
5014            &self,
5015            _node: &GASPNode,
5016        ) -> Result<Option<GASPNodeResponse>, GASPError> {
5017            Ok(None) // No inputs needed for simple tests
5018        }
5019
5020        async fn append_to_graph(
5021            &self,
5022            node: &GASPNode,
5023            _spent_by: Option<&str>,
5024        ) -> Result<(), GASPError> {
5025            self.graphs
5026                .lock()
5027                .unwrap()
5028                .entry(node.graph_id.clone())
5029                .or_default()
5030                .push(node.clone());
5031            Ok(())
5032        }
5033
5034        async fn validate_graph_anchor(&self, _graph_id: &str) -> Result<(), GASPError> {
5035            Ok(())
5036        }
5037
5038        async fn finalize_graph(&self, graph_id: &str) -> Result<(), GASPError> {
5039            self.finalized.lock().unwrap().push(graph_id.to_string());
5040            Ok(())
5041        }
5042
5043        async fn discard_graph(&self, graph_id: &str) -> Result<(), GASPError> {
5044            self.discarded.lock().unwrap().push(graph_id.to_string());
5045            Ok(())
5046        }
5047    }
5048
5049    // ── Mock GASPRemote ────────────────────────────────────────────────
5050
5051    struct MockGASPRemote {
5052        remote_utxos: Vec<GASPOutput>,
5053        submitted: Mutex<Vec<GASPNode>>,
5054    }
5055
5056    impl MockGASPRemote {
5057        fn new(utxos: Vec<GASPOutput>) -> Self {
5058            Self {
5059                remote_utxos: utxos,
5060                submitted: Mutex::new(Vec::new()),
5061            }
5062        }
5063    }
5064
5065    #[async_trait(?Send)]
5066    impl GASPRemote for MockGASPRemote {
5067        async fn get_initial_response(
5068            &self,
5069            request: &GASPInitialRequest,
5070        ) -> Result<GASPInitialResponse, GASPError> {
5071            if request.version != GASP_VERSION {
5072                return Err(GASPError::VersionMismatch {
5073                    local: GASP_VERSION,
5074                    remote: request.version,
5075                });
5076            }
5077            let utxos: Vec<GASPOutput> = self
5078                .remote_utxos
5079                .iter()
5080                .filter(|u| u.score as u64 >= request.since)
5081                .cloned()
5082                .collect();
5083            Ok(GASPInitialResponse {
5084                utxo_list: utxos,
5085                since: request.since,
5086            })
5087        }
5088
5089        async fn get_initial_reply(
5090            &self,
5091            _response: &GASPInitialResponse,
5092        ) -> Result<GASPInitialReply, GASPError> {
5093            Ok(GASPInitialReply {
5094                utxo_list: Vec::new(),
5095            })
5096        }
5097
5098        async fn request_node(
5099            &self,
5100            graph_id: &str,
5101            txid: &str,
5102            output_index: u32,
5103            _metadata: bool,
5104        ) -> Result<GASPNode, GASPError> {
5105            Ok(GASPNode {
5106                graph_id: graph_id.to_string(),
5107                raw_tx: format!("remote_rawtx_{txid}"),
5108                output_index,
5109                proof: Some("proof_hex".to_string()),
5110                tx_metadata: None,
5111                output_metadata: None,
5112                inputs: None,
5113            })
5114        }
5115
5116        async fn submit_node(
5117            &self,
5118            node: &GASPNode,
5119        ) -> Result<Option<GASPNodeResponse>, GASPError> {
5120            self.submitted.lock().unwrap().push(node.clone());
5121            Ok(None) // No further inputs needed
5122        }
5123    }
5124
5125    // ── Tests ──────────────────────────────────────────────────────────
5126
5127    #[tokio::test]
5128    async fn proofs_page_deadline_never_passes_a_failed_unsaved_graph() {
5129        struct PageDeadline(std::rc::Rc<std::cell::Cell<bool>>);
5130        #[async_trait(?Send)]
5131        impl GASPRemote for PageDeadline {
5132            async fn get_initial_response(
5133                &self,
5134                request: &GASPInitialRequest,
5135            ) -> Result<GASPInitialResponse, GASPError> {
5136                if request.since > 0 {
5137                    self.0.set(true);
5138                    std::future::pending::<()>().await;
5139                }
5140                Ok(GASPInitialResponse {
5141                    since: request.since,
5142                    utxo_list: vec![GASPOutput {
5143                        txid: "11".repeat(32),
5144                        output_index: 0,
5145                        score: 10.0,
5146                    }],
5147                })
5148            }
5149            async fn get_initial_reply(
5150                &self,
5151                _: &GASPInitialResponse,
5152            ) -> Result<GASPInitialReply, GASPError> {
5153                unreachable!()
5154            }
5155            async fn request_node(
5156                &self,
5157                _: &str,
5158                _: &str,
5159                _: u32,
5160                _: bool,
5161            ) -> Result<GASPNode, GASPError> {
5162                Err(GASPError::RemoteError("offline".into()))
5163            }
5164            async fn submit_node(
5165                &self,
5166                _: &GASPNode,
5167            ) -> Result<Option<GASPNodeResponse>, GASPError> {
5168                unreachable!()
5169            }
5170        }
5171        let due = std::rc::Rc::new(std::cell::Cell::new(false));
5172        let mut sync = GASPSync::new(
5173            Box::new(MockGASPStorage::new(vec![])),
5174            Box::new(PageDeadline(due.clone())),
5175            0,
5176            "test",
5177            true,
5178        )
5179        .with_graph_budget(GraphBudget {
5180            max_calls: 10,
5181            max_bytes_fetched: u64::MAX,
5182            max_nodes: u32::MAX,
5183            deadline: Box::new(|| Box::pin(std::future::pending())),
5184            half_deadline: None,
5185        });
5186        let deadline = std::future::poll_fn(move |_| {
5187            if due.get() {
5188                std::task::Poll::Ready(())
5189            } else {
5190                std::task::Poll::Pending
5191            }
5192        });
5193        assert!(race_or_deadline(sync.sync(None), deadline).await.is_none());
5194        assert!(!sync.graph_in_flight());
5195        sync.defer_in_flight().await;
5196        assert_eq!(
5197            sync.completed_cursor(),
5198            0,
5199            "a failed graph has no durable hold"
5200        );
5201        assert_eq!(
5202            sync.cursor_held_by(),
5203            Some(format!("{}.0", "11".repeat(32)))
5204        );
5205    }
5206
5207    #[tokio::test]
5208    async fn test_sync_pulls_remote_utxos() {
5209        let local_storage = MockGASPStorage::new(vec![]);
5210        let remote = MockGASPRemote::new(vec![
5211            GASPOutput {
5212                txid: "tx1".to_string(),
5213                output_index: 0,
5214                score: 100.0,
5215            },
5216            GASPOutput {
5217                txid: "tx2".to_string(),
5218                output_index: 0,
5219                score: 200.0,
5220            },
5221        ]);
5222
5223        let mut gasp = GASPSync::new(
5224            Box::new(local_storage),
5225            Box::new(remote),
5226            0,
5227            "[TEST]",
5228            false,
5229        );
5230
5231        gasp.sync(None).await.unwrap();
5232
5233        assert_eq!(gasp.last_interaction, 200);
5234    }
5235
5236    #[tokio::test]
5237    async fn test_sync_skips_known_utxos() {
5238        let local_storage = MockGASPStorage::new(vec![GASPOutput {
5239            txid: "tx1".to_string(),
5240            output_index: 0,
5241            score: 100.0,
5242        }]);
5243        let remote = MockGASPRemote::new(vec![
5244            GASPOutput {
5245                txid: "tx1".to_string(),
5246                output_index: 0,
5247                score: 100.0,
5248            },
5249            GASPOutput {
5250                txid: "tx2".to_string(),
5251                output_index: 0,
5252                score: 200.0,
5253            },
5254        ]);
5255
5256        let mut gasp = GASPSync::new(
5257            Box::new(local_storage),
5258            Box::new(remote),
5259            0,
5260            "[TEST]",
5261            true, // unidirectional — skip push
5262        );
5263
5264        gasp.sync(None).await.unwrap();
5265
5266        // Only tx2 should have been ingested (tx1 was already known)
5267        // last_interaction should be 200
5268        assert_eq!(gasp.last_interaction, 200);
5269    }
5270
5271    #[tokio::test]
5272    async fn test_sync_unidirectional_skips_push() {
5273        let local_storage = MockGASPStorage::new(vec![GASPOutput {
5274            txid: "local_only".to_string(),
5275            output_index: 0,
5276            score: 50.0,
5277        }]);
5278        let remote = MockGASPRemote::new(vec![]);
5279
5280        let mut gasp = GASPSync::new(Box::new(local_storage), Box::new(remote), 0, "[TEST]", true);
5281
5282        gasp.sync(None).await.unwrap();
5283        // In unidirectional mode, local_only should NOT be pushed to remote
5284        // (no way to check directly with current mock, but no error = success)
5285    }
5286
5287    #[tokio::test]
5288    async fn test_complete_graph_finalizes_on_valid() {
5289        let storage = MockGASPStorage::new(vec![]);
5290        let remote = MockGASPRemote::new(vec![]);
5291
5292        let gasp = GASPSync::new(Box::new(storage), Box::new(remote), 0, "[TEST]", false);
5293
5294        gasp.complete_graph("test_graph.0").await.unwrap();
5295        // Storage mock always validates OK, so graph should be finalized
5296    }
5297
5298    #[tokio::test]
5299    async fn test_complete_graph_discards_on_invalid() {
5300        struct FailValidationStorage;
5301
5302        #[async_trait(?Send)]
5303        impl GASPStorage for FailValidationStorage {
5304            // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
5305            async fn load_deferred_graphs(
5306                &self,
5307            ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
5308                Ok(Vec::new())
5309            }
5310            async fn get_deferred_graph(
5311                &self,
5312                _: &str,
5313            ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
5314                Ok(None)
5315            }
5316            async fn save_deferred_graph(
5317                &self,
5318                _: &crate::gasp::DeferredGraph,
5319            ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
5320                Err(GASPError::StorageError("keeps no deferred graphs".into()))
5321            }
5322            async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
5323                Ok(())
5324            }
5325            async fn find_known_utxos(
5326                &self,
5327                _: u64,
5328                _: Option<u64>,
5329            ) -> Result<Vec<GASPOutput>, GASPError> {
5330                Ok(vec![])
5331            }
5332            async fn hydrate_gasp_node(
5333                &self,
5334                _: &str,
5335                _: &str,
5336                _: u32,
5337                _: bool,
5338            ) -> Result<GASPNode, GASPError> {
5339                unreachable!()
5340            }
5341            async fn find_needed_inputs(
5342                &self,
5343                _: &GASPNode,
5344            ) -> Result<Option<GASPNodeResponse>, GASPError> {
5345                Ok(None)
5346            }
5347            async fn append_to_graph(
5348                &self,
5349                _: &GASPNode,
5350                _: Option<&str>,
5351            ) -> Result<(), GASPError> {
5352                Ok(())
5353            }
5354            async fn validate_graph_anchor(&self, _: &str) -> Result<(), GASPError> {
5355                Err(GASPError::ValidationFailed("bad anchor".into()))
5356            }
5357            async fn finalize_graph(&self, _: &str) -> Result<(), GASPError> {
5358                panic!("should not finalize")
5359            }
5360            async fn discard_graph(&self, _: &str) -> Result<(), GASPError> {
5361                Ok(())
5362            }
5363        }
5364
5365        let gasp = GASPSync::new(
5366            Box::new(FailValidationStorage),
5367            Box::new(MockGASPRemote::new(vec![])),
5368            0,
5369            "[TEST]",
5370            false,
5371        );
5372
5373        // Should not error — discards instead of finalizing
5374        gasp.complete_graph("bad_graph.0").await.unwrap();
5375    }
5376
5377    // ── AncestorFetcher fallback tests ─────────────────────────────────
5378
5379    /// Build a minimal valid tx hex with one input referencing `source_txid`.
5380    fn make_tx_hex(source_txid: &str, source_oi: u32) -> String {
5381        let mut tx = bsv_rs::transaction::Transaction::new();
5382        tx.inputs.push(bsv_rs::transaction::TransactionInput::new(
5383            source_txid.to_string(),
5384            source_oi,
5385        ));
5386        tx.outputs.push(bsv_rs::transaction::TransactionOutput::new(
5387            100,
5388            bsv_rs::script::LockingScript::from_hex(
5389                "76a914000000000000000000000000000000000000000088ac",
5390            )
5391            .unwrap(),
5392        ));
5393        tx.to_hex()
5394    }
5395
5396    /// Storage that records appended nodes and requests exactly one ancestor
5397    /// (the first input) on the FIRST node it sees, then nothing further.
5398    struct RecordingStorage {
5399        appended: Mutex<Vec<GASPNode>>,
5400        request_once: Mutex<bool>,
5401        ancestor_outpoint: String,
5402    }
5403
5404    #[async_trait(?Send)]
5405    impl GASPStorage for RecordingStorage {
5406        // Keeps no deferred graphs (bsv-low #555): never given a per-graph budget.
5407        async fn load_deferred_graphs(
5408            &self,
5409        ) -> Result<Vec<crate::gasp::DeferredGraphKey>, GASPError> {
5410            Ok(Vec::new())
5411        }
5412        async fn get_deferred_graph(
5413            &self,
5414            _: &str,
5415        ) -> Result<Option<crate::gasp::DeferredGraph>, GASPError> {
5416            Ok(None)
5417        }
5418        async fn save_deferred_graph(
5419            &self,
5420            _: &crate::gasp::DeferredGraph,
5421        ) -> Result<crate::gasp::DeferredGraphSave, GASPError> {
5422            Err(GASPError::StorageError("keeps no deferred graphs".into()))
5423        }
5424        async fn delete_deferred_graph(&self, _: &str) -> Result<(), GASPError> {
5425            Ok(())
5426        }
5427        async fn find_known_utxos(
5428            &self,
5429            _: u64,
5430            _: Option<u64>,
5431        ) -> Result<Vec<GASPOutput>, GASPError> {
5432            Ok(vec![])
5433        }
5434        async fn hydrate_gasp_node(
5435            &self,
5436            _: &str,
5437            _: &str,
5438            _: u32,
5439            _: bool,
5440        ) -> Result<GASPNode, GASPError> {
5441            unreachable!()
5442        }
5443        async fn find_needed_inputs(
5444            &self,
5445            _: &GASPNode,
5446        ) -> Result<Option<GASPNodeResponse>, GASPError> {
5447            let mut once = self.request_once.lock().unwrap();
5448            if *once {
5449                *once = false;
5450                let mut requested_inputs = HashMap::new();
5451                requested_inputs.insert(
5452                    self.ancestor_outpoint.clone(),
5453                    crate::types::GASPInputRequest { metadata: false },
5454                );
5455                Ok(Some(GASPNodeResponse { requested_inputs }))
5456            } else {
5457                Ok(None)
5458            }
5459        }
5460        async fn append_to_graph(&self, node: &GASPNode, _: Option<&str>) -> Result<(), GASPError> {
5461            self.appended.lock().unwrap().push(node.clone());
5462            Ok(())
5463        }
5464        async fn validate_graph_anchor(&self, _: &str) -> Result<(), GASPError> {
5465            Ok(())
5466        }
5467        async fn finalize_graph(&self, _: &str) -> Result<(), GASPError> {
5468            Ok(())
5469        }
5470        async fn discard_graph(&self, _: &str) -> Result<(), GASPError> {
5471            Ok(())
5472        }
5473    }
5474
5475    /// Remote that always errors on `request_node` (mimics beta's HTTP 400
5476    /// "Incomplete SPV data!").
5477    struct FailingNodeRemote;
5478
5479    #[async_trait(?Send)]
5480    impl GASPRemote for FailingNodeRemote {
5481        async fn get_initial_response(
5482            &self,
5483            _: &GASPInitialRequest,
5484        ) -> Result<GASPInitialResponse, GASPError> {
5485            Ok(GASPInitialResponse {
5486                utxo_list: vec![],
5487                since: 0,
5488            })
5489        }
5490        async fn get_initial_reply(
5491            &self,
5492            _: &GASPInitialResponse,
5493        ) -> Result<GASPInitialReply, GASPError> {
5494            Ok(GASPInitialReply { utxo_list: vec![] })
5495        }
5496        async fn request_node(
5497            &self,
5498            _: &str,
5499            _: &str,
5500            _: u32,
5501            _: bool,
5502        ) -> Result<GASPNode, GASPError> {
5503            Err(GASPError::RemoteError(
5504                "Peer returned HTTP 400: Incomplete SPV data!".to_string(),
5505            ))
5506        }
5507        async fn submit_node(&self, _: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError> {
5508            Ok(None)
5509        }
5510    }
5511
5512    /// Mock fetcher that returns a pre-built ancestor rawtx (+ optional proof).
5513    struct MockFetcher {
5514        ancestor_hex: String,
5515        proof: Option<String>,
5516        called: Mutex<u32>,
5517    }
5518
5519    #[async_trait(?Send)]
5520    impl AncestorFetcher for MockFetcher {
5521        async fn fetch_ancestor(&self, _txid: &str) -> Result<FetchedAncestor, GASPError> {
5522            *self.called.lock().unwrap() += 1;
5523            Ok(FetchedAncestor {
5524                raw_tx: self.ancestor_hex.clone(),
5525                proof: self.proof.clone(),
5526            })
5527        }
5528    }
5529
5530    /// Remote that records how many times `request_node` is invoked (it would
5531    /// be a doomed peer call on the migration path) so a test can assert the
5532    /// fetcher path SKIPS the peer entirely.
5533    struct CountingNodeRemote {
5534        request_node_calls: std::rc::Rc<Mutex<u32>>,
5535    }
5536
5537    #[async_trait(?Send)]
5538    impl GASPRemote for CountingNodeRemote {
5539        async fn get_initial_response(
5540            &self,
5541            _: &GASPInitialRequest,
5542        ) -> Result<GASPInitialResponse, GASPError> {
5543            Ok(GASPInitialResponse {
5544                utxo_list: vec![],
5545                since: 0,
5546            })
5547        }
5548        async fn get_initial_reply(
5549            &self,
5550            _: &GASPInitialResponse,
5551        ) -> Result<GASPInitialReply, GASPError> {
5552            Ok(GASPInitialReply { utxo_list: vec![] })
5553        }
5554        async fn request_node(
5555            &self,
5556            _: &str,
5557            _: &str,
5558            _: u32,
5559            _: bool,
5560        ) -> Result<GASPNode, GASPError> {
5561            *self.request_node_calls.lock().unwrap() += 1;
5562            Err(GASPError::RemoteError(
5563                "Peer returned HTTP 400: Incomplete SPV data!".to_string(),
5564            ))
5565        }
5566        async fn submit_node(&self, _: &GASPNode) -> Result<Option<GASPNodeResponse>, GASPError> {
5567            Ok(None)
5568        }
5569    }
5570
5571    #[tokio::test]
5572    async fn ancestor_fetcher_none_preserves_peer_error() {
5573        // Build a tip tx whose input references some ancestor.
5574        let ancestor_hex = make_tx_hex(
5575            "1111111111111111111111111111111111111111111111111111111111111111",
5576            0,
5577        );
5578        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
5579            .unwrap()
5580            .id();
5581        let tip_hex = make_tx_hex(&ancestor_txid, 0);
5582
5583        let storage = RecordingStorage {
5584            appended: Mutex::new(vec![]),
5585            request_once: Mutex::new(true),
5586            ancestor_outpoint: format!("{ancestor_txid}.0"),
5587        };
5588
5589        // No fetcher configured → default path → peer error must propagate.
5590        let gasp = GASPSync::new(
5591            Box::new(storage),
5592            Box::new(FailingNodeRemote),
5593            0,
5594            "[TEST]",
5595            true,
5596        );
5597
5598        let tip_node = GASPNode {
5599            graph_id: format!("{}.0", "deadbeef"),
5600            raw_tx: tip_hex,
5601            output_index: 0,
5602            proof: None,
5603            tx_metadata: None,
5604            output_metadata: None,
5605            inputs: None,
5606        };
5607
5608        let mut seen = std::collections::HashSet::new();
5609        let result = gasp.process_incoming_node(&tip_node, None, &mut seen).await;
5610        assert!(
5611            result.is_err(),
5612            "with no fetcher, the peer error must propagate (default path unchanged)"
5613        );
5614    }
5615
5616    #[tokio::test]
5617    async fn ancestor_fetcher_some_self_heals_missing_ancestor() {
5618        let ancestor_hex = make_tx_hex(
5619            "2222222222222222222222222222222222222222222222222222222222222222",
5620            0,
5621        );
5622        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
5623            .unwrap()
5624            .id();
5625        let tip_hex = make_tx_hex(&ancestor_txid, 0);
5626
5627        let storage = RecordingStorage {
5628            appended: Mutex::new(vec![]),
5629            request_once: Mutex::new(true),
5630            ancestor_outpoint: format!("{ancestor_txid}.0"),
5631        };
5632
5633        let fetcher = std::rc::Rc::new(MockFetcher {
5634            ancestor_hex: ancestor_hex.clone(),
5635            proof: None,
5636            called: Mutex::new(0),
5637        });
5638
5639        let gasp = GASPSync::new(
5640            Box::new(storage),
5641            Box::new(FailingNodeRemote),
5642            0,
5643            "[TEST]",
5644            true,
5645        )
5646        .with_ancestor_fetcher(Some(fetcher.clone()));
5647
5648        let tip_node = GASPNode {
5649            graph_id: "deadbeef.0".to_string(),
5650            raw_tx: tip_hex.clone(),
5651            output_index: 0,
5652            proof: None,
5653            tx_metadata: None,
5654            output_metadata: None,
5655            inputs: None,
5656        };
5657
5658        let mut seen = std::collections::HashSet::new();
5659        gasp.process_incoming_node(&tip_node, None, &mut seen)
5660            .await
5661            .expect("with fetcher, missing ancestor self-heals from chain");
5662
5663        assert_eq!(
5664            *fetcher.called.lock().unwrap(),
5665            2,
5666            "fetcher fires twice: once to hydrate the root's OWN proof (mock returns \
5667             proof:None here, so the root stays proofless + the walk continues), then \
5668             once to self-heal the missing ancestor (#126 root proof-anchoring)"
5669        );
5670
5671        // The synthesized ancestor node must have been appended to the graph,
5672        // with proof: None so the existing recursion would continue upward.
5673        // (We can't reach into the boxed storage here, but the Ok(()) above
5674        // proves the synthesized node flowed through process_incoming_node and
5675        // append_to_graph without error.)
5676    }
5677
5678    #[tokio::test]
5679    async fn ancestor_fetcher_some_skips_peer_request_node() {
5680        // Proof of the peer-skip optimization: with a fetcher present, the
5681        // doomed peer `request_node` call must NOT fire for ancestors — the
5682        // fetcher is consulted directly. (Otherwise a deep chain pays one
5683        // sequential peer round-trip per ancestor before falling back.)
5684        let ancestor_hex = make_tx_hex(
5685            "3333333333333333333333333333333333333333333333333333333333333333",
5686            0,
5687        );
5688        let ancestor_txid = bsv_rs::transaction::Transaction::from_hex(&ancestor_hex)
5689            .unwrap()
5690            .id();
5691        let tip_hex = make_tx_hex(&ancestor_txid, 0);
5692
5693        let storage = RecordingStorage {
5694            appended: Mutex::new(vec![]),
5695            request_once: Mutex::new(true),
5696            ancestor_outpoint: format!("{ancestor_txid}.0"),
5697        };
5698
5699        let counter = std::rc::Rc::new(Mutex::new(0u32));
5700        let remote = CountingNodeRemote {
5701            request_node_calls: counter.clone(),
5702        };
5703        let fetcher = std::rc::Rc::new(MockFetcher {
5704            ancestor_hex: ancestor_hex.clone(),
5705            proof: None,
5706            called: Mutex::new(0),
5707        });
5708
5709        let gasp = GASPSync::new(Box::new(storage), Box::new(remote), 0, "[TEST]", true)
5710            .with_ancestor_fetcher(Some(fetcher.clone()));
5711
5712        let tip_node = GASPNode {
5713            graph_id: "deadbeef.0".to_string(),
5714            raw_tx: tip_hex,
5715            output_index: 0,
5716            proof: None,
5717            tx_metadata: None,
5718            output_metadata: None,
5719            inputs: None,
5720        };
5721
5722        let mut seen = std::collections::HashSet::new();
5723        gasp.process_incoming_node(&tip_node, None, &mut seen)
5724            .await
5725            .expect("self-heal via fetcher should succeed");
5726
5727        assert_eq!(
5728            *counter.lock().unwrap(),
5729            0,
5730            "peer request_node must be SKIPPED for ancestors when a fetcher is present"
5731        );
5732        assert_eq!(
5733            *fetcher.called.lock().unwrap(),
5734            2,
5735            "fetcher fires twice: root's OWN proof hydration (#126) + serving the \
5736             ancestor directly (peer request_node still skipped)"
5737        );
5738    }
5739
5740    #[test]
5741    fn test_parse_outpoint() {
5742        let (txid, oi) = parse_outpoint("abc123.5").unwrap();
5743        assert_eq!(txid, "abc123");
5744        assert_eq!(oi, 5);
5745
5746        assert!(parse_outpoint("no_dot").is_none());
5747        assert!(parse_outpoint("abc.notanum").is_none());
5748    }
5749
5750    #[tokio::test]
5751    async fn test_gasp_storage_is_object_safe() {
5752        let storage: Box<dyn GASPStorage> = Box::new(MockGASPStorage::new(vec![]));
5753        let utxos = storage.find_known_utxos(0, None).await.unwrap();
5754        assert!(utxos.is_empty());
5755    }
5756
5757    #[tokio::test]
5758    async fn test_gasp_remote_is_object_safe() {
5759        let remote: Box<dyn GASPRemote> = Box::new(MockGASPRemote::new(vec![]));
5760        let response = remote
5761            .get_initial_response(&GASPInitialRequest {
5762                version: 1,
5763                since: 0,
5764                limit: None,
5765            })
5766            .await
5767            .unwrap();
5768        assert!(response.utxo_list.is_empty());
5769    }
5770
5771    #[tokio::test]
5772    async fn test_version_mismatch_error() {
5773        let remote = MockGASPRemote::new(vec![]);
5774        let result = remote
5775            .get_initial_response(&GASPInitialRequest {
5776                version: 99,
5777                since: 0,
5778                limit: None,
5779            })
5780            .await;
5781        assert!(result.is_err());
5782        assert!(matches!(
5783            result.unwrap_err(),
5784            GASPError::VersionMismatch { .. }
5785        ));
5786    }
5787}