Skip to main content

vector_core/
dm_catchup.rs

1//! DM catch-up: what our read relays hold for us that we don't, fetched once each.
2//!
3//! Each relay reconciles (NIP-77) only the window it hasn't vouched for: from its
4//! cursor, less NIP-59's backdating slack. On an established account that is a few
5//! kilobytes of fingerprints. What a relay names missing is fetched from that relay
6//! alone, so a wrap five relays hold comes down once, not five times. A relay that
7//! can't reconcile walks its window in small pages instead. Everything commits as it
8//! lands, so a link that dies part-way keeps what came. Fetches wait for silence, not
9//! a total: a slow relay that keeps sending keeps its turn. A relay's cursor advances
10//! only once its whole window is held.
11
12use std::collections::{HashMap, HashSet};
13use std::future::Future;
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::time::Duration;
16
17use futures_util::stream::{FuturesUnordered, StreamExt};
18use nostr_sdk::prelude::*;
19
20use crate::community::transport::{fetch_relay_eose_filters, EoseFail};
21use crate::event_handler::{self, BatchingPersist, PreparedEvent};
22use crate::negentropy;
23
24/// NIP-59 backdates a wrap's created_at by up to two days, so a window that reaches
25/// back to a cursor has to start this much before it.
26pub const NIP59_BACKDATE_SLACK: u64 = 2 * 24 * 3600;
27/// A relay with no cursor catches up over this much of the recent past; deeper
28/// history is the bootstrap's.
29const UNCURSORED_WINDOW: u64 = 7 * 24 * 3600;
30/// Ids asked for per REQ.
31const FETCH_BATCH: usize = 200;
32/// Events per page when a relay's window is walked by REQ.
33const PAGE: usize = 100;
34/// A walk stops here whatever it finds: no window is this deep.
35const MAX_PAGES: usize = 200;
36/// Messages held before a batched persist.
37const PERSIST_BATCH: usize = 100;
38/// After an incomplete catch-up, the waits before each retry: soon, then less often.
39pub const RETRY_BACKOFF_SECS: [u64; 6] = [15, 45, 120, 300, 900, 1800];
40/// A catch-up this often while the app runs: a live subscription can die without a
41/// word, and the window since the last one is a few fingerprints.
42pub const SAFETY_NET_SECS: u64 = 600;
43
44pub struct Opts {
45    /// What arrives is news (a reconnect, a return to the app) rather than history (a launch).
46    pub is_new: bool,
47    /// Only these relays; `None` for every read relay.
48    pub only: Option<Vec<String>>,
49    /// A relay with no cursor reconciles its whole history and earns one, rather than
50    /// catching up its recent week (a fresh device's first sync).
51    pub bootstrap: bool,
52}
53
54#[derive(Debug, Default, Clone, serde::Serialize)]
55pub struct Report {
56    pub relays: usize,
57    pub reconciled: usize,
58    pub walked: usize,
59    /// Wraps found missing, each counted once however many relays held it.
60    pub missing: usize,
61    pub fetched: usize,
62    /// Wraps a relay named but then didn't send, reaching its end without them.
63    pub unservable: usize,
64    pub new_messages: u32,
65    pub cursors_advanced: usize,
66    /// Relays whose window isn't fully held yet, with why: worth another try.
67    pub incomplete: Vec<String>,
68    pub elapsed_ms: u64,
69}
70
71impl Report {
72    pub fn complete(&self) -> bool {
73        self.incomplete.is_empty()
74    }
75
76    /// The relays to try again, without their reasons.
77    pub fn incomplete_relays(&self) -> Vec<String> {
78        self.incomplete.iter().map(|r| r.split(' ').next().unwrap_or(r).to_string()).collect()
79    }
80
81    /// No relay answered at all: the network may be down, not empty.
82    pub fn reached_none(&self) -> bool {
83        self.relays > 0 && self.reconciled == 0 && self.walked == 0 && self.fetched == 0
84    }
85}
86
87struct Plan {
88    url: RelayUrl,
89    relay: Relay,
90    /// The window's start; `None` reconciles the whole history (a bootstrap).
91    since: Option<u64>,
92    cursored: bool,
93}
94
95enum Outcome {
96    Missing(HashSet<EventId>),
97    NoNeg,
98    Unreached,
99    Failed(String),
100}
101
102#[derive(Default)]
103struct Got {
104    received: HashSet<EventId>,
105    events: usize,
106    new_messages: u32,
107    /// The link went quiet before everything asked for came.
108    stalled: bool,
109    /// The relay refused the REQ, so what it didn't send says nothing.
110    closed: bool,
111}
112
113enum Job {
114    Reconcile(usize),
115    Fetch(usize, Vec<EventId>),
116    Walk(usize),
117}
118
119enum Step {
120    Reconciled(usize, Outcome),
121    Fetched(usize, Vec<EventId>, Got),
122    Walked(usize, Got, bool),
123}
124
125#[derive(Clone)]
126enum Standing {
127    Pending,
128    Reconciled,
129    Walked(bool),
130    Incomplete(String),
131}
132
133struct Ctx<'b, 'p, F> {
134    client: Client,
135    me: PublicKey,
136    now: u64,
137    plans: Vec<Plan>,
138    items: Vec<(EventId, Timestamp)>,
139    batcher: &'b BatchingPersist<'p>,
140    commit: &'b F,
141    is_new: bool,
142    flush_ok: AtomicBool,
143}
144
145/// Catch up on DMs over the read relays (or `opts.only`). Each event goes through
146/// `commit` (a shell's own commit, which may intercept, around the core one) with the
147/// shared `batcher` holding the persists.
148pub async fn catch_up<F, Fut>(opts: &Opts, batcher: &BatchingPersist<'_>, commit: F) -> Report
149where
150    F: Fn(PreparedEvent, bool) -> Fut,
151    Fut: Future<Output = bool>,
152{
153    let started = crate::rt::time::Instant::now();
154    let mut report = Report::default();
155    let (Some(client), Some(me)) = (crate::state::nostr_client(), crate::state::my_public_key()) else {
156        return report;
157    };
158    let now = crate::clock::timestamp().as_secs();
159    let wanted = |url: &RelayUrl| {
160        opts.only.as_ref().is_none_or(|only| {
161            only.iter().any(|u| u.trim_end_matches('/') == url.as_str().trim_end_matches('/'))
162        })
163    };
164    // Read relays only: a gossip-flagged community relay must never see a REQ naming our npub.
165    let plans: Vec<Plan> = client
166        .relays()
167        .await
168        .into_iter()
169        .filter(|(url, relay)| relay.capabilities().has_read() && wanted(url))
170        .map(|(url, relay)| {
171            let cursor = negentropy::reconcile_cursor(url.as_str());
172            let since = match cursor {
173                Some(c) => Some(c.saturating_sub(NIP59_BACKDATE_SLACK)),
174                None if opts.bootstrap => None,
175                None => Some(now.saturating_sub(UNCURSORED_WINDOW)),
176            };
177            Plan { url, relay, since, cursored: cursor.is_some() }
178        })
179        .collect();
180    report.relays = plans.len();
181    if plans.is_empty() {
182        return report;
183    }
184
185    // Our fingerprints over the widest window any relay needs, read once.
186    let items = if plans.iter().any(|p| p.since.is_none()) {
187        crate::db::wrappers::load_negentropy_items()
188    } else {
189        let widest = plans.iter().filter_map(|p| p.since).min().unwrap_or(now);
190        crate::db::wrappers::load_negentropy_items_since(widest)
191    }
192    .unwrap_or_default();
193
194    let n = plans.len();
195    let ctx = Ctx { client, me, now, plans, items, batcher, commit: &commit, is_new: opts.is_new, flush_ok: AtomicBool::new(true) };
196
197    let mut jobs = FuturesUnordered::new();
198    for i in 0..n {
199        jobs.push(run_job(Job::Reconcile(i), &ctx));
200    }
201    let mut standing = vec![Standing::Pending; n];
202    let mut wants: Vec<HashSet<EventId>> = vec![HashSet::new(); n];
203    // A relay that went quiet mid-fetch is handed nothing more this run.
204    let mut quiet = vec![false; n];
205    // What each relay named, was asked for, and ended its answer without.
206    let mut refused: Vec<HashSet<EventId>> = vec![HashSet::new(); n];
207    // Each missing wrap's fetcher while its fetch runs, and who has already failed it.
208    let mut owner: HashMap<EventId, usize> = HashMap::new();
209    let mut tried: HashMap<EventId, Vec<usize>> = HashMap::new();
210    let mut received: HashSet<EventId> = HashSet::new();
211
212    while let Some(step) = jobs.next().await {
213        match step {
214            Step::Reconciled(i, Outcome::Missing(ids)) => {
215                report.reconciled += 1;
216                standing[i] = Standing::Reconciled;
217                report.missing += ids.iter().filter(|id| !wants.iter().any(|w| w.contains(*id))).count();
218                let mine: Vec<EventId> = ids
219                    .iter()
220                    .filter(|id| !received.contains(*id) && !owner.contains_key(*id) && !tried.get(*id).is_some_and(|t| t.contains(&i)))
221                    .copied()
222                    .collect();
223                wants[i] = ids;
224                for id in &mine {
225                    owner.insert(*id, i);
226                }
227                if !mine.is_empty() {
228                    jobs.push(run_job(Job::Fetch(i, mine), &ctx));
229                }
230            }
231            Step::Reconciled(i, Outcome::NoNeg) => jobs.push(run_job(Job::Walk(i), &ctx)),
232            Step::Reconciled(i, Outcome::Unreached) => standing[i] = Standing::Incomplete("unreachable".into()),
233            Step::Reconciled(i, Outcome::Failed(e)) => standing[i] = Standing::Incomplete(e),
234            Step::Fetched(i, asked, got) => {
235                report.fetched += got.events;
236                report.new_messages += got.new_messages;
237                received.extend(got.received);
238                quiet[i] |= got.stalled;
239                let answered = !got.stalled && !got.closed;
240                // What it didn't bring goes to another relay that named it.
241                let mut handoff: HashMap<usize, Vec<EventId>> = HashMap::new();
242                for id in asked {
243                    owner.remove(&id);
244                    if received.contains(&id) {
245                        continue;
246                    }
247                    if answered {
248                        refused[i].insert(id);
249                    }
250                    let failed = tried.entry(id).or_default();
251                    failed.push(i);
252                    let next = (0..n).find(|j| {
253                        !quiet[*j] && !failed.contains(j) && matches!(standing[*j], Standing::Reconciled) && wants[*j].contains(&id)
254                    });
255                    if let Some(j) = next {
256                        owner.insert(id, j);
257                        handoff.entry(j).or_default().push(id);
258                    }
259                }
260                for (j, ids) in handoff {
261                    jobs.push(run_job(Job::Fetch(j, ids), &ctx));
262                }
263            }
264            Step::Walked(i, got, complete) => {
265                report.walked += 1;
266                report.fetched += got.events;
267                report.new_messages += got.new_messages;
268                received.extend(got.received);
269                standing[i] = if complete { Standing::Walked(true) } else { Standing::Incomplete("walk cut short".into()) };
270            }
271        }
272    }
273    drop(jobs);
274
275    let flushed = ctx.batcher.try_flush().await.is_ok() && ctx.flush_ok.load(Ordering::SeqCst);
276    let live = !crate::db::session_stopped();
277    for (i, plan) in ctx.plans.iter().enumerate() {
278        let url = plan.url.as_str();
279        let held = match &standing[i] {
280            // A windowed reconcile can't vouch for history before its window: only a
281            // cursored relay, or a whole-history reconcile, earns an advance.
282            Standing::Reconciled => {
283                // A wrap the relay itself won't serve can't hold its cursor back forever.
284                if !wants[i].iter().all(|id| received.contains(id) || refused[i].contains(id)) {
285                    report.incomplete.push(format!("{url} (not every missing wrap arrived)"));
286                    continue;
287                }
288                plan.cursored || plan.since.is_none()
289            }
290            // A walk is all a relay without NIP-77 ever gets, so its window is all there is to vouch for.
291            Standing::Walked(complete) => *complete,
292            Standing::Pending => false,
293            Standing::Incomplete(why) => {
294                report.incomplete.push(format!("{url} ({why})"));
295                continue;
296            }
297        };
298        if held && flushed && live {
299            negentropy::advance_reconcile_cursor(url, ctx.now);
300            report.cursors_advanced += 1;
301        }
302    }
303    if !flushed {
304        report.incomplete.push("(a batch failed to persist)".into());
305    }
306    report.unservable = refused.iter().flatten().filter(|id| !received.contains(*id)).collect::<HashSet<_>>().len();
307    report.elapsed_ms = started.elapsed().as_millis() as u64;
308
309    crate::log_net_info!(
310        "[DM catch-up] {} relay(s): {} reconciled, {} walked, {} missing, {} fetched ({} new, {} unservable), {} cursor(s) advanced in {}ms",
311        report.relays, report.reconciled, report.walked, report.missing, report.fetched,
312        report.new_messages, report.unservable, report.cursors_advanced, report.elapsed_ms
313    );
314    if !report.incomplete.is_empty() {
315        crate::log_net_fail!("[DM catch-up] incomplete: {}", report.incomplete.join(", "));
316    }
317    report
318}
319
320/// Retry what a catch-up left incomplete, backing off, until every relay is held or
321/// the account is swapped out. `run` catches up the relays it's given.
322pub async fn retry_incomplete<R, Fut>(report: &Report, run: R)
323where
324    R: Fn(Vec<String>) -> Fut,
325    Fut: Future<Output = Report>,
326{
327    let mut relays = report.incomplete_relays();
328    relays.retain(|u| u.contains("://"));
329    // A failed persist names no relay, but leaves every relay's window to fetch again.
330    let all = report.incomplete.iter().any(|r| !r.contains("://"));
331    for wait in RETRY_BACKOFF_SECS {
332        if (relays.is_empty() && !all) || crate::db::session_stopped() {
333            return;
334        }
335        crate::rt::time::sleep(Duration::from_secs(wait)).await;
336        if crate::db::session_stopped() {
337            return;
338        }
339        let next = run(if all { Vec::new() } else { relays.clone() }).await;
340        if next.complete() {
341            return;
342        }
343        relays = next.incomplete_relays();
344        relays.retain(|u| u.contains("://"));
345    }
346}
347
348struct SafetyNet;
349
350/// Catch up every [`SAFETY_NET_SECS`] for as long as this account is the one
351/// logged in. Once per account however often it's called.
352pub fn start_safety_net<R, Fut>(run: R)
353where
354    R: Fn() -> Fut + crate::rt::MaybeSend + 'static,
355    Fut: Future<Output = Report> + crate::rt::MaybeSend + 'static,
356{
357    let started = crate::db::current_session().scoped::<SafetyNet, AtomicBool>();
358    if started.swap(true, Ordering::SeqCst) {
359        return;
360    }
361    crate::db::spawn_bound(async move {
362        loop {
363            crate::rt::time::sleep(Duration::from_secs(SAFETY_NET_SECS)).await;
364            if crate::db::session_stopped() {
365                return;
366            }
367            run().await;
368        }
369    });
370}
371
372async fn run_job<F, Fut>(job: Job, ctx: &Ctx<'_, '_, F>) -> Step
373where
374    F: Fn(PreparedEvent, bool) -> Fut,
375    Fut: Future<Output = bool>,
376{
377    match job {
378        Job::Reconcile(i) => Step::Reconciled(i, reconcile(ctx, &ctx.plans[i]).await),
379        Job::Fetch(i, ids) => {
380            let got = fetch_ids(ctx, &ctx.plans[i].url, &ids).await;
381            Step::Fetched(i, ids, got)
382        }
383        Job::Walk(i) => {
384            let (got, complete) = walk(ctx, &ctx.plans[i]).await;
385            Step::Walked(i, got, complete)
386        }
387    }
388}
389
390async fn reconcile<F>(ctx: &Ctx<'_, '_, F>, plan: &Plan) -> Outcome {
391    let url = plan.url.as_str();
392    if !negentropy::wait_connected(&plan.relay, crate::relay_connect_timeout(Duration::from_secs(15))).await {
393        return Outcome::Unreached;
394    }
395    if negentropy::neg_supported_cached(url) == Some(false) {
396        return Outcome::NoNeg;
397    }
398    let mut filter = Filter::new().pubkey(ctx.me).kind(Kind::GiftWrap);
399    if let Some(since) = plan.since {
400        filter = filter.since(Timestamp::from_secs(since));
401    }
402    // A bootstrap's first frame is the relay walking its whole set, which a slow box
403    // can take minutes over; a window's is small, so its wait is about the link.
404    let (first, whole) = match plan.since {
405        Some(_) => (crate::relay_request_timeout(Duration::from_secs(20)), crate::relay_request_timeout(Duration::from_secs(90))),
406        None => (Duration::from_secs(300), Duration::from_secs(480)),
407    };
408    let sync_opts = SyncOptions::new().direction(SyncDirection::Down).initial_timeout(first).dry_run();
409    let in_window = |at: &Timestamp| plan.since.is_none_or(|s| at.as_secs() >= s);
410    let attempt = || {
411        crate::rt::time::timeout(
412            whole,
413            plan.relay
414                .sync(filter.clone())
415                .items(ctx.items.iter().filter(|(_, at)| in_window(at)).copied())
416                .opts(sync_opts.clone()),
417        )
418    };
419    let mut result = attempt().await;
420    // An AUTH-gating relay refuses the first gated request while its challenge is
421    // answered; a lagged broadcast says nothing about the relay at all.
422    if matches!(&result, Ok(Err(e)) if { let e = e.to_string(); e.contains("auth-required") || e.contains("lagged") }) {
423        crate::rt::time::sleep(Duration::from_millis(1200)).await;
424        result = attempt().await;
425    }
426    match result {
427        Ok(Ok(recon)) => {
428            negentropy::record_neg_support(url, true);
429            Outcome::Missing(recon.remote)
430        }
431        Ok(Err(e)) => {
432            let e = e.to_string();
433            if negentropy::classify_neg_sync_error(&e, false) == Some(false) {
434                crate::log_net_info!("[DM catch-up] {url} can't reconcile ({e}): walking its window");
435                negentropy::record_neg_support(url, false);
436                return Outcome::NoNeg;
437            }
438            // Silence is never recorded: a wrong verdict costs a walk of the whole window on
439            // every run for a day. One that has reconciled before is just slow; one that never
440            // has, yet answers a REQ promptly, walks this once.
441            if e == "timeout" && !negentropy::neg_ever_confirmed(url) && answers_req(ctx, url).await {
442                crate::log_net_info!("[DM catch-up] {url} silent on NIP-77: walking its window this time");
443                return Outcome::NoNeg;
444            }
445            crate::log_warn!("[DM catch-up] {url} reconcile failed: {e}");
446            Outcome::Failed(e)
447        }
448        Err(_) => {
449            crate::log_warn!("[DM catch-up] {url} reconcile ran past {whole:?}");
450            Outcome::Failed("timed out".into())
451        }
452    }
453}
454
455/// Whether a relay answers a REQ promptly: on a weak link a healthy relay is slow at
456/// both, so silence on a reconcile alone says nothing.
457async fn answers_req<F>(ctx: &Ctx<'_, '_, F>, url: &str) -> bool {
458    let probe = Filter::new().pubkey(ctx.me).kind(Kind::GiftWrap).limit(1);
459    fetch_relay_eose_filters(&ctx.client, url, vec![probe], crate::relay_request_timeout(Duration::from_secs(5)))
460        .await
461        .is_ok()
462}
463
464/// Fetch these wraps from one relay, committing each as it comes.
465async fn fetch_ids<F, Fut>(ctx: &Ctx<'_, '_, F>, url: &RelayUrl, ids: &[EventId]) -> Got
466where
467    F: Fn(PreparedEvent, bool) -> Fut,
468    Fut: Future<Output = bool>,
469{
470    // The wait for the next event, not for the whole batch.
471    let idle = crate::relay_request_timeout(Duration::from_secs(20));
472    let mut got = Got::default();
473    for batch in ids.chunks(FETCH_BATCH) {
474        if crate::db::session_stopped() {
475            break;
476        }
477        // The #p is not redundant: Ditto refuses gift-wrap REQs carrying neither authors nor #p.
478        let filter = Filter::new().ids(batch.iter().copied()).kind(Kind::GiftWrap).pubkey(ctx.me);
479        let Ok(stream) = ctx
480            .client
481            .stream_events(ReqTarget::single(url.as_str(), [filter]))
482            .timeout(Duration::from_secs(600))
483            .await
484        else {
485            got.stalled = true;
486            break;
487        };
488        let mut stream = std::pin::pin!(stream);
489        let mut pending: Vec<Event> = Vec::new();
490        loop {
491            match crate::rt::time::timeout(idle, stream.next()).await {
492                Ok(Some((_, Ok(event)))) => {
493                    if got.received.insert(event.id) {
494                        pending.push(event);
495                        if pending.len() >= event_handler::UNWRAP_BATCH {
496                            absorb(ctx, std::mem::take(&mut pending), &mut got).await;
497                        }
498                    }
499                }
500                Ok(Some((_, Err(_)))) => got.closed = true,
501                Ok(None) => break,
502                Err(_) => {
503                    got.stalled = true;
504                    break;
505                }
506            }
507        }
508        absorb(ctx, pending, &mut got).await;
509        if got.stalled {
510            break;
511        }
512    }
513    got
514}
515
516/// Walk a relay's window newest-first in small pages, for a relay that can't
517/// reconcile. Complete once a page brings nothing new.
518async fn walk<F, Fut>(ctx: &Ctx<'_, '_, F>, plan: &Plan) -> (Got, bool)
519where
520    F: Fn(PreparedEvent, bool) -> Fut,
521    Fut: Future<Output = bool>,
522{
523    // Never a whole history by REQ.
524    let since = plan.since.unwrap_or(ctx.now.saturating_sub(UNCURSORED_WINDOW));
525    let budget = crate::relay_request_timeout(Duration::from_secs(30));
526    let mut got = Got::default();
527    let mut until: Option<u64> = None;
528    for page in 0..MAX_PAGES {
529        if crate::db::session_stopped() {
530            return (got, false);
531        }
532        let mut filter = Filter::new().pubkey(ctx.me).kind(Kind::GiftWrap).since(Timestamp::from_secs(since)).limit(PAGE);
533        if let Some(u) = until {
534            // Inclusive: wraps sharing the boundary second are deduped, not skipped.
535            filter = filter.until(Timestamp::from_secs(u));
536        }
537        let events = match fetch_relay_eose_filters(&ctx.client, plan.url.as_str(), vec![filter.clone()], budget).await {
538            Ok(events) => events,
539            Err(EoseFail::Closed) if page == 0 => {
540                crate::rt::time::sleep(Duration::from_millis(1200)).await;
541                match fetch_relay_eose_filters(&ctx.client, plan.url.as_str(), vec![filter], budget).await {
542                    Ok(events) => events,
543                    Err(_) => return (got, false),
544                }
545            }
546            Err(_) => return (got, false),
547        };
548        let oldest = events.iter().map(|e| e.created_at.as_secs()).min();
549        let fresh: Vec<Event> = events.into_iter().filter(|e| got.received.insert(e.id)).collect();
550        if fresh.is_empty() {
551            return (got, true);
552        }
553        absorb(ctx, fresh, &mut got).await;
554        until = oldest;
555    }
556    (got, false)
557}
558
559async fn absorb<F, Fut>(ctx: &Ctx<'_, '_, F>, events: Vec<Event>, got: &mut Got)
560where
561    F: Fn(PreparedEvent, bool) -> Fut,
562    Fut: Future<Output = bool>,
563{
564    got.events += events.len();
565    for chunk in events.chunks(event_handler::UNWRAP_BATCH) {
566        for prepared in event_handler::prepare_events(chunk, ctx.me).await {
567            if (ctx.commit)(prepared, ctx.is_new).await {
568                got.new_messages += 1;
569            }
570            if ctx.batcher.buffered() >= PERSIST_BATCH && ctx.batcher.try_flush().await.is_err() {
571                ctx.flush_ok.store(false, Ordering::SeqCst);
572            }
573        }
574    }
575    // The page's arrivals are already on screen: stored now, unread counts and an opened chat
576    // read them without waiting out every other relay's catch-up.
577    if ctx.batcher.buffered() > 0 && ctx.batcher.try_flush().await.is_err() {
578        ctx.flush_ok.store(false, Ordering::SeqCst);
579    }
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    #[test]
587    fn incomplete_relays_drop_their_reasons() {
588        let report = Report {
589            incomplete: vec!["wss://a.example (timed out)".into(), "wss://b.example/nostr (unreachable)".into()],
590            ..Default::default()
591        };
592        assert!(!report.complete());
593        assert_eq!(report.incomplete_relays(), vec!["wss://a.example", "wss://b.example/nostr"]);
594    }
595
596    #[test]
597    fn reached_none_only_when_relays_were_asked() {
598        assert!(!Report::default().reached_none());
599        assert!(Report { relays: 3, ..Default::default() }.reached_none());
600        assert!(!Report { relays: 3, reconciled: 1, ..Default::default() }.reached_none());
601    }
602}