diff --git a/mesh/crates/mesh-llm-host-runtime/src/command_support.rs b/mesh/crates/mesh-llm-host-runtime/src/command_support.rs index f0e46dbcc6..63f8cac644 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/command_support.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/command_support.rs @@ -7,7 +7,8 @@ pub mod discovery { pub mod nostr { pub use crate::network::nostr::{ - DiscoveredMesh, MeshFilter, MeshListing, discover, rotate_keys, score_mesh, + DiscoveredMesh, MeshFilter, MeshListing, RelayHealth, discover, discover_with_health, + rotate_keys, score_mesh, }; } diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/nostr.rs b/mesh/crates/mesh-llm-host-runtime/src/network/nostr.rs index 6bf2af0a77..f53462d381 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/nostr.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/nostr.rs @@ -13,7 +13,7 @@ mod publish; pub use auto::{AutoDecision, is_auto_eligible, score_mesh, smart_auto}; pub use contracts::{DEFAULT_RELAYS, DiscoveredMesh, MeshListing}; -pub use discovery::{MeshFilter, discover}; +pub use discovery::{MeshFilter, RelayHealth, discover, discover_with_health}; pub use keys::{load_or_create_keys, rotate_keys}; pub use model_packs::default_models_for_vram; pub(crate) use model_packs::small_node_default_model; diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/nostr/discovery.rs b/mesh/crates/mesh-llm-host-runtime/src/network/nostr/discovery.rs index 6fdfbcbaac..3717d8c78e 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/nostr/discovery.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/nostr/discovery.rs @@ -71,6 +71,135 @@ impl MeshFilter { } } +/// How many relays a discovery round actually heard back from. +/// +/// `fetch_events` swallows per-relay errors, so "zero meshes" alone +/// cannot distinguish "the mesh plane is empty" from "no relay +/// answered" — callers that act on absence (the publish watchdog) or +/// report to users (the discover CLI) need this alongside the results. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct RelayHealth { + /// Relays the discovery client tried to query. + pub relays_queried: usize, + /// Relays that spoke: completed the query (EOSE) or delivered + /// events before the round ended. Silence-until-deadline and + /// never-issued requests do not count. + pub relays_answered: usize, + /// Relays that completed their query with EOSE. Higher bar than + /// `relays_answered`: a relay that delivered partial events and + /// disconnected did not finish, so absence inference must not rest + /// on it — the listing it never sent may still have been coming. + pub queries_completed: usize, +} + +impl RelayHealth { + /// False only when no relay answered at all — the "cannot tell" + /// state for the CLI's outage reporting. + pub fn any_relay_answered(&self) -> bool { + self.relays_answered > 0 + } + + /// True when at least one relay finished its query. Only a + /// completed query that did not contain the listing is evidence of + /// absence; the absence-based takeover decision requires this. + pub fn any_query_completed(&self) -> bool { + self.queries_completed > 0 + } +} + +/// One relay's round outcome, accumulated from the notification stream. +#[derive(Debug, Default)] +pub(crate) struct RelayRound { + /// The relay sent EOSE for this round's subscription: the query + /// completed, so an empty event set still counts as answered. + eose: bool, + /// The relay terminated the subscription without EOSE (Closed), so + /// no completion should be expected even if the round waits. + closed: bool, + /// Events delivered before the round ended — kept even when the + /// relay never finished, because a delivered listing is evidence + /// regardless of completion. + events: std::collections::BTreeSet, +} + +impl RelayRound { + fn terminal(&self) -> bool { + self.eose || self.closed + } +} + +/// One relay's fetch outcome, normalized for counting and merging. +#[derive(Debug)] +pub(crate) enum RelayFetchResult { + /// The relay spoke: completed the query (EOSE) or delivered events + /// before the round ended. `completed_query` distinguishes the two — + /// only a completed query supports absence inference. + Answered { + events: std::collections::BTreeSet, + completed_query: bool, + }, + /// The relay neither completed nor delivered anything: never + /// connected, disconnected before EOSE, closed without EOSE, or + /// silent until the deadline. + Silent, +} + +/// Classify one relay's round from completion evidence. +/// +/// A relay counts as answered when its query completed (EOSE observed on +/// the notification stream) or when it demonstrably spoke (delivered +/// events, even if it never finished). Only a relay that neither +/// completed nor delivered anything is silent: never connected, +/// disconnected before EOSE, or hung to the deadline. Unlike a +/// pre-fetch connection snapshot, EOSE cannot be observed for a relay +/// that dropped mid-fetch, so a truncated round can no longer pose as a +/// completed empty one. +pub(crate) fn classify_relay_round_outcome(round: RelayRound) -> RelayFetchResult { + if round.eose || !round.events.is_empty() { + RelayFetchResult::Answered { + events: round.events, + completed_query: round.eose, + } + } else { + RelayFetchResult::Silent + } +} + +/// Count answered relays and merge their events. +/// +/// Only a completed round trip counts as answered: deadline silence and +/// never-issued requests do not. Events merge into one set, deduplicated +/// by event id. +pub(crate) fn merge_relay_fetch_results( + relays_queried: usize, + results: Vec, +) -> (std::collections::BTreeSet, RelayHealth) { + let mut events = std::collections::BTreeSet::new(); + let mut relays_answered = 0usize; + let mut queries_completed = 0usize; + for result in results { + match result { + RelayFetchResult::Answered { + events: relay_events, + completed_query, + } => { + relays_answered += 1; + queries_completed += usize::from(completed_query); + events.extend(relay_events); + } + RelayFetchResult::Silent => {} + } + } + ( + events, + RelayHealth { + relays_queried, + relays_answered, + queries_completed, + }, + ) +} + /// A reusable read-only Nostr client for discovery. /// Create once, pass to repeated `discover()` calls to avoid opening /// new websocket connections and generating throwaway keys every time. @@ -96,6 +225,7 @@ impl DiscoveryClient { ); } client.connect().await; + wait_for_relay_connections(&client, CONNECT_WAIT_CAP).await; Ok(Self { client }) } } @@ -104,12 +234,93 @@ impl DiscoveryClient { /// /// If `cached_client` is provided, reuses its connections. Otherwise /// creates (and drops) a one-shot client — fine for the initial -/// `--auto` join but wasteful in tight loops. +/// `--auto` join but wasteful in tight loops. Discards relay health; +/// callers that need to distinguish "no meshes" from "no relay +/// answered" use [`discover_with_health`]. pub async fn discover( relays: &[String], filter: &MeshFilter, cached_client: Option<&DiscoveryClient>, ) -> Result> { + let (meshes, _health) = discover_with_health(relays, filter, cached_client).await?; + Ok(meshes) +} + +/// Fold one client notification into the round map. +/// +/// Events are collected from the raw `RelayMessage::Event` stream, not +/// the `ClientNotification::Event` variant: that variant is +/// deduplicated against the client's event database, so a listing +/// re-delivered on a later round of the same cached client (the +/// watchdog's) would be suppressed while its EOSE still counts — +/// manufacturing a "relay answered with nothing" round and, downstream, +/// a takeover for a listing that is present. The raw message is +/// delivered for every receipt and carries the fully validated event +/// (limits, filter match, expiry, signature). +fn apply_discovery_notification( + rounds: &mut std::collections::HashMap, + subscription_id: &SubscriptionId, + notification: ClientNotification, +) { + let ClientNotification::Message { relay_url, message } = notification else { + return; + }; + match *message { + RelayMessage::Event { + subscription_id: id, + event, + } if *id == *subscription_id => { + let event = event.into_owned(); + // The SDK's relay verification cache keys on the CLAIMED + // event id (shared.rs `verify_and_cache` returns Ok on a + // cache hit without checking the signature), so a relay can + // replay a cached id over altered content and pass. Verify + // here: hash and signature must match the content actually + // received. + match event.verify() { + Ok(()) => { + if let Some(round) = rounds.get_mut(&relay_url) { + round.events.insert(event); + } + } + Err(e) => { + tracing::warn!("Nostr relay {relay_url} sent an invalid event: {e}"); + } + } + } + RelayMessage::EndOfStoredEvents(id) if *id == *subscription_id => { + if let Some(round) = rounds.get_mut(&relay_url) { + round.eose = true; + } + } + // A relay that closes the subscription (rejected, auth-required, + // rate-limited) will never send EOSE for it: mark it terminal so + // the round does not wait out the deadline on its behalf. + RelayMessage::Closed { + subscription_id: id, + .. + } if *id == *subscription_id => { + if let Some(round) = rounds.get_mut(&relay_url) { + round.closed = true; + } + } + _ => {} + } +} + +/// Discover meshes and report how many relays answered. +/// +/// The fetch fans out per relay (one request each, 5 s timeout) so a +/// relay that errors or stays silent is visible instead of folded into +/// an all-or-nothing result; events are merged and deduplicated across +/// relays before the usual per-publisher dedupe. An all-relays failure +/// still returns `Ok` with empty results — plus `relays_answered == 0` +/// — rather than a hard error, matching `discover`'s contract. +pub async fn discover_with_health( + relays: &[String], + filter: &MeshFilter, + cached_client: Option<&DiscoveryClient>, +) -> Result<(Vec, RelayHealth)> { // Build a temporary client only when no cached one is supplied. let _tmp; let client: &Client = if let Some(cc) = cached_client { @@ -119,22 +330,75 @@ pub async fn discover( &_tmp }; + // With a cached client the pool is the one it was built with; health + // describes that pool, which is what the watchdog's long-lived + // client re-checks against. + let relay_urls: Vec = + client.relays().await.keys().cloned().collect(); + + // Drive one subscription across every relay and route the + // notification stream per relay. This replaces per-relay + // `fetch_events` futures, which have two blind spots this round + // cannot afford: their collected events are dropped if the future + // is cancelled at the deadline (a delivered listing would vanish), + // and their `Ok(empty)` cannot distinguish a completed empty query + // (EOSE) from a stream that ended because the relay disconnected + // mid-fetch. The notification stream exposes both signals + // per relay: `EndOfStoredEvents` is completion evidence a + // connection snapshot can never fake, and events accumulate + // outside any cancellable future. + let subscription_id = SubscriptionId::generate(); + // Subscribe to the notification channel BEFORE sending the REQ: + // anything received before the channel exists is not delivered to + // it (nostr-sdk documents this ordering requirement). + let mut notifications = client.notifications(); let nostr_filter = Filter::new() .kind(Kind::Custom(MESH_SERVICE_KIND)) .custom_tag(SingleLetterTag::LOWERCASE_K, "mesh-llm".to_string()) .limit(100); + let targets: Vec<(nostr_sdk::prelude::RelayUrl, Vec)> = relay_urls + .iter() + .cloned() + .map(|url| (url, vec![nostr_filter.clone()])) + .collect(); + let _output = client + .subscribe(ReqTarget::manual(targets)) + .with_id(subscription_id.clone()) + .await?; - let events = match client - .fetch_events(nostr_filter) - .timeout(Duration::from_secs(5)) - .await - { - Ok(e) => e, - Err(e) => { - tracing::warn!("Nostr fetch failed: {e}"); - return Ok(Vec::new()); // No results rather than hard error + let mut rounds: std::collections::HashMap = + relay_urls + .iter() + .cloned() + .map(|url| (url, RelayRound::default())) + .collect(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let pending: usize = rounds.values().filter(|r| !r.terminal()).count(); + if pending == 0 { + break; } - }; + let next = tokio::time::timeout_at(deadline, notifications.next()).await; + let notification = match next { + Ok(Some(notification)) => notification, + // Deadline: relays that neither completed nor delivered + // anything classify as silent; their partial events (if any) + // are already accumulated and are kept. + Ok(None) | Err(_) => break, + }; + apply_discovery_notification(&mut rounds, &subscription_id, notification); + } + // Always drop the subscription, including on the cached client the + // watchdog reuses — a leaked REQ would keep streaming events into + // later rounds' notification channels. + let _ = client.unsubscribe(&subscription_id).await; + + let outcomes = relay_urls + .iter() + .filter_map(|url| rounds.remove(url)) + .map(classify_relay_round_outcome) + .collect(); + let (events, health) = merge_relay_fetch_results(relay_urls.len(), outcomes); let now = Timestamp::now().as_secs(); @@ -160,7 +424,53 @@ pub async fn discover( .then(b.listing.total_vram_bytes.cmp(&a.listing.total_vram_bytes)) }); - Ok(meshes) + Ok((meshes, health)) +} + +/// How long a fresh discovery client waits for its relay connections +/// before the first round: long enough for a websocket handshake against +/// a healthy relay (observed well under a second), short enough that a +/// dead relay set does not stall the command. +const CONNECT_WAIT_CAP: Duration = Duration::from_secs(2); + +/// Wait, capped, until every relay's first connection attempt has +/// settled. +/// +/// nostr-sdk 0.45.x `connect()` only spawns connection tasks; it does +/// not wait for the handshakes. Sampling `relay.status()` immediately +/// afterwards therefore reports every relay of a freshly built client — +/// including healthy ones that answer moments later — as not connected, +/// which would classify a genuine empty EOSE as silence. Waiting here +/// makes the one-shot path's connection sample meaningful. +/// +/// "Settled" means Connected or a status a first attempt ends in +/// (disconnected through banned, sleeping, shutdown): the wait exits as +/// soon as no relay is still initializing or connecting, so a pool with +/// one dead relay costs the handshake time of the healthy ones plus the +/// dead one's failed attempt, not the full cap. A relay that would +/// auto-reconnect later still samples as not connected, which can only +/// undercount `relays_answered` — never inflate it. +async fn wait_for_relay_connections(client: &Client, cap: Duration) { + use nostr_sdk::relay::RelayStatus; + + let deadline = tokio::time::Instant::now() + cap; + loop { + let first_attempts_settled = client.relays().await.values().all(|relay| { + matches!( + relay.status(), + RelayStatus::Connected + | RelayStatus::Disconnected + | RelayStatus::Terminated + | RelayStatus::Banned + | RelayStatus::Sleeping + | RelayStatus::Shutdown + ) + }); + if first_attempts_settled || tokio::time::Instant::now() >= deadline { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } } async fn build_discovery_client(relays: &[String]) -> Result { @@ -180,6 +490,7 @@ async fn build_discovery_client(relays: &[String]) -> Result { ); } client.connect().await; + wait_for_relay_connections(&client, CONNECT_WAIT_CAP).await; Ok(client) } @@ -236,6 +547,258 @@ fn parse_discovered_mesh(event: &Event, now: u64) -> Option { }) } +#[cfg(test)] +mod relay_health_tests { + use super::*; + + fn answered(events: &[&str]) -> RelayFetchResult { + // Events are opaque to the accumulator (merged by set identity), + // so any Event works; reuse one per unique id. + let mut set = std::collections::BTreeSet::new(); + for id in events { + let event = EventBuilder::new(Kind::Custom(1), *id) + .finalize(&nostr_sdk::prelude::Keys::generate()) + .expect("sign"); + set.insert(event); + } + RelayFetchResult::Answered { + events: set, + completed_query: true, + } + } + + #[test] + fn silent_relays_do_not_count_as_answered() { + let (events, health) = merge_relay_fetch_results( + 3, + vec![ + answered(&[]), + RelayFetchResult::Silent, + RelayFetchResult::Silent, + ], + ); + assert_eq!( + health, + RelayHealth { + relays_queried: 3, + relays_answered: 1, + queries_completed: 1 + } + ); + assert!(events.is_empty()); + } + + #[test] + fn an_all_silent_round_reads_as_zero_answered() { + let (_, health) = + merge_relay_fetch_results(5, (0..5).map(|_| RelayFetchResult::Silent).collect()); + assert!(!health.any_relay_answered()); + assert!(!health.any_query_completed()); + } + + #[test] + fn duplicate_events_across_relays_merge_to_one() { + // The same event fetched from two relays must not duplicate. + let event = EventBuilder::new(Kind::Custom(1), "same") + .finalize(&nostr_sdk::prelude::Keys::generate()) + .expect("sign"); + let mut first = std::collections::BTreeSet::new(); + first.insert(event.clone()); + let mut second = std::collections::BTreeSet::new(); + second.insert(event); + let (events, health) = merge_relay_fetch_results( + 2, + vec![ + RelayFetchResult::Answered { + events: first, + completed_query: true, + }, + RelayFetchResult::Answered { + events: second, + completed_query: true, + }, + ], + ); + assert_eq!(events.len(), 1); + assert_eq!(health.relays_answered, 2); + assert_eq!(health.queries_completed, 2); + } + + /// Regression (review round 2): on a later round of the same cached + /// client, a re-delivered listing arrives ONLY as a raw + /// `RelayMessage::Event` — the `ClientNotification::Event` variant + /// is deduplicated against the client's event database and never + /// fires again. A round shaped exactly like that (raw event + EOSE, + /// no deduped variant) must still find the listing; this test fails + /// if collection ever reverts to the deduped arm. + #[test] + fn a_repeat_delivery_arrives_only_on_the_raw_message_stream() { + use std::borrow::Cow; + use std::collections::HashMap; + + let id = SubscriptionId::generate(); + let relay_url: nostr_sdk::prelude::RelayUrl = "wss://relay.example".parse().unwrap(); + let event = EventBuilder::new(Kind::Custom(1), "x") + .finalize(&Keys::generate()) + .expect("sign"); + + let mut rounds = HashMap::new(); + rounds.insert(relay_url.clone(), RelayRound::default()); + + apply_discovery_notification( + &mut rounds, + &id, + ClientNotification::Message { + relay_url: relay_url.clone(), + message: Box::new(RelayMessage::Event { + subscription_id: Cow::Owned(id.clone()), + event: Cow::Owned(event), + }), + }, + ); + apply_discovery_notification( + &mut rounds, + &id, + ClientNotification::Message { + relay_url: relay_url.clone(), + message: Box::new(RelayMessage::EndOfStoredEvents(Cow::Owned(id.clone()))), + }, + ); + + let round = rounds.remove(&relay_url).expect("round to exist"); + let classified = classify_relay_round_outcome(round); + match classified { + RelayFetchResult::Answered { events, .. } => { + assert_eq!(events.len(), 1, "the raw re-delivery must be collected") + } + other => panic!("expected Answered, got {other:?}"), + } + } + + /// Regression (review round 3): the SDK's relay verification cache + /// keys on the CLAIMED event id, so a relay can replay a cached id + /// over altered content and pass `verify_and_cache`. The collector + /// verifies every raw event itself: hash and signature must match + /// the content actually received. The forged event goes to a fresh + /// round of its own — sharing a round with the legitimate event + /// would collide in the `BTreeSet` (same created_at second, same + /// claimed id ⇒ `Ord::Equal`) and mask a missing verification. + #[test] + fn an_event_reusing_a_cached_id_with_altered_content_is_rejected() { + use std::borrow::Cow; + use std::collections::HashMap; + + fn round_with( + id: &SubscriptionId, + relay_url: &nostr_sdk::prelude::RelayUrl, + event: Event, + ) -> RelayRound { + let mut rounds = HashMap::new(); + rounds.insert(relay_url.clone(), RelayRound::default()); + apply_discovery_notification( + &mut rounds, + id, + ClientNotification::Message { + relay_url: relay_url.clone(), + message: Box::new(RelayMessage::Event { + subscription_id: Cow::Owned(id.clone()), + event: Cow::Owned(event), + }), + }, + ); + rounds.remove(relay_url).expect("round to exist") + } + + let id = SubscriptionId::generate(); + let relay_url: nostr_sdk::prelude::RelayUrl = "wss://relay.example".parse().unwrap(); + + let valid = EventBuilder::new(Kind::Custom(1), "legitimate") + .finalize(&Keys::generate()) + .expect("sign"); + + // Same claimed id, altered content: an id-for-content mismatch + // `verify()` must catch regardless of any cache. + let other = EventBuilder::new(Kind::Custom(1), "forged") + .finalize(&Keys::generate()) + .expect("sign"); + let mut value = serde_json::to_value(&other).expect("serialize"); + value["id"] = serde_json::to_value(valid.id).expect("id json"); + let forged: Event = serde_json::from_value(value).expect("deserialize"); + + // The legitimate event is collected. + let accepted = round_with(&id, &relay_url, valid); + assert_eq!(accepted.events.len(), 1); + + // The forged replay, alone in its own round, is dropped by + // verification — with no legitimate twin to collide with, a + // missing `verify()` would let it through. + let rejected = round_with(&id, &relay_url, forged); + assert!( + rejected.events.is_empty(), + "forged event reusing a cached id must be rejected" + ); + } + + #[test] + fn a_round_without_eose_or_events_is_silence() { + // A relay that never connected, disconnected before EOSE, or + // hung to the deadline leaves neither completion evidence nor + // speech — the exact round a truncated `Ok(empty)` from the + // old fetch path used to fake. + let classified = classify_relay_round_outcome(RelayRound::default()); + assert!(matches!(classified, RelayFetchResult::Silent)); + + // A subscription the relay Closed without EOSE is the same + // non-answer. + let closed = RelayRound { + closed: true, + ..RelayRound::default() + }; + let classified = classify_relay_round_outcome(closed); + assert!(matches!(classified, RelayFetchResult::Silent)); + } + + #[test] + fn a_completed_empty_round_is_an_answer() { + // EOSE with nothing stored is a healthy relay that finished the + // query — completion evidence a connection snapshot cannot + // fake. + let completed_empty = RelayRound { + eose: true, + ..RelayRound::default() + }; + let classified = classify_relay_round_outcome(completed_empty); + assert!( + matches!(classified, RelayFetchResult::Answered { events, completed_query: true } if events.is_empty()) + ); + } + + #[test] + fn a_relay_that_delivered_events_without_finishing_is_an_answer_and_keeps_events() { + // The round deadline hit before EOSE, but the relay already + // spoke: its events must survive the bound and it counts as + // answered — a delivered listing is evidence regardless of + // completion. + let event = EventBuilder::new(Kind::Custom(1), "x") + .finalize(&nostr_sdk::prelude::Keys::generate()) + .expect("sign"); + let mut set = std::collections::BTreeSet::new(); + set.insert(event); + let unfinished = RelayRound { + events: set, + ..RelayRound::default() + }; + let classified = classify_relay_round_outcome(unfinished); + match classified { + RelayFetchResult::Answered { + events, + completed_query: false, + } => assert_eq!(events.len(), 1), + other => panic!("expected Answered without completion, got {other:?}"), + } + } +} + #[cfg(test)] mod filter_tests { use super::*; diff --git a/mesh/crates/mesh-llm-host-runtime/src/network/nostr/publish.rs b/mesh/crates/mesh-llm-host-runtime/src/network/nostr/publish.rs index 15b8219319..3221f33c75 100644 --- a/mesh/crates/mesh-llm-host-runtime/src/network/nostr/publish.rs +++ b/mesh/crates/mesh-llm-host-runtime/src/network/nostr/publish.rs @@ -1,7 +1,9 @@ //! Nostr publishing loops and listing construction. use super::contracts::{DiscoveredMesh, MESH_SERVICE_KIND, MeshListing}; -use super::discovery::{DiscoveryClient, MeshFilter, discover}; +use super::discovery::{DiscoveryClient, MeshFilter, RelayHealth, discover, discover_with_health}; +#[cfg(test)] +use super::discovery::{RelayFetchResult, merge_relay_fetch_results}; use super::keys::load_or_create_keys; use anyhow::Result; use mesh_llm_events::{OutputEvent, emit_event}; @@ -225,9 +227,9 @@ pub async fn publish_watchdog( let filter = MeshFilter::default(); loop { - match discover(&relays, &filter, disco.as_ref()).await { - Ok(meshes) => { - if should_take_over_publish(&node, &meshes).await { + match discover_with_health(&relays, &filter, disco.as_ref()).await { + Ok((meshes, health)) => { + if should_take_over_publish(&node, &meshes, health).await { if !confirm_missing_listing_after_backoff( &relays, &filter, @@ -388,11 +390,48 @@ async fn watchdog_initial_delay() { tokio::time::sleep(Duration::from_secs(jitter)).await; } -async fn should_take_over_publish(node: &crate::mesh::Node, meshes: &[DiscoveredMesh]) -> bool { +/// What a discovery round says about our own mesh's listing. +/// +/// `Unknown` is the zero-relays-answered case: absence proves nothing +/// when no relay spoke, and the watchdog must not publish a mesh that +/// was never published on the strength of it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ListingPresence { + /// A current listing for our mesh was seen. + Present, + /// At least one relay completed its query (EOSE) and none had our + /// listing. Partial speech — events delivered without the query + /// finishing — is not absence evidence: the listing may still have + /// been coming when the round ended. + Missing, + /// No relay completed its query; absence is not evidence. + Unknown, +} + +fn listing_presence( + meshes: &[DiscoveredMesh], + health: RelayHealth, + mesh_id: Option<&str>, + served: &[String], +) -> ListingPresence { + if mesh_listing_present(meshes, mesh_id, served) { + ListingPresence::Present + } else if health.any_query_completed() { + ListingPresence::Missing + } else { + ListingPresence::Unknown + } +} + +async fn should_take_over_publish( + node: &crate::mesh::Node, + meshes: &[DiscoveredMesh], + health: RelayHealth, +) -> bool { let our_peers = node.peers().await; let served = node.models_being_served().await; let our_mesh_id = node.mesh_id().await; - !mesh_listing_present(meshes, our_mesh_id.as_deref(), &served) + listing_presence(meshes, health, our_mesh_id.as_deref(), &served) == ListingPresence::Missing && (!our_peers.is_empty() || !served.is_empty()) } @@ -410,18 +449,31 @@ async fn confirm_missing_listing_after_backoff( }); tokio::time::sleep(Duration::from_secs(backoff)).await; - let Ok(recheck) = discover(relays, filter, disco).await else { - return true; + let recheck = match discover_with_health(relays, filter, disco).await { + Ok(round) => round, + // The recheck could not even build a client — the same + // cannot-tell state as zero relays answering: skip this + // takeover round rather than publish on an outage. + Err(_) => return false, }; let served = node.models_being_served().await; let our_mesh_id = node.mesh_id().await; - let still_missing = !mesh_listing_present(&recheck, our_mesh_id.as_deref(), &served); - if !still_missing { - let _ = emit_event(OutputEvent::NostrPublishing { - message: "📡 Someone else took over publishing — standing down".to_string(), - }); + match listing_presence(&recheck.0, recheck.1, our_mesh_id.as_deref(), &served) { + ListingPresence::Missing => true, + ListingPresence::Present => { + let _ = emit_event(OutputEvent::NostrPublishing { + message: "📡 Someone else took over publishing — standing down".to_string(), + }); + false + } + // Still no relay answered after the backoff: absence is not + // evidence, so skip this takeover round and retry later instead + // of publishing on the strength of an outage. + ListingPresence::Unknown => { + tracing::debug!("Publish watchdog: no relay answered after backoff — not taking over"); + false + } } - still_missing } async fn load_watchdog_publish_keys(check_interval_secs: u64) -> Option { @@ -679,6 +731,118 @@ async fn update_delisted_state( false } +#[cfg(test)] +mod listing_presence_tests { + use super::*; + use crate::network::nostr::MeshListing; + + fn mesh_with_id(mesh_id: Option<&str>, serving: &[&str]) -> DiscoveredMesh { + DiscoveredMesh { + listing: MeshListing { + invite_token: "t".to_string(), + serving: serving.iter().map(|s| s.to_string()).collect(), + wanted: vec![], + on_disk: vec![], + total_vram_bytes: 0, + node_count: 1, + client_count: 0, + max_clients: 0, + name: None, + region: None, + mesh_id: mesh_id.map(str::to_string), + publisher_serves: None, + }, + publisher_npub: "npub-x".to_string(), + published_at: 0, + expires_at: None, + } + } + + fn health(answered: usize, completed: usize) -> RelayHealth { + RelayHealth { + relays_queried: 5, + relays_answered: answered, + queries_completed: completed, + } + } + + /// The incomplete-query hole: a relay delivered an event for + /// another mesh and disconnected before EOSE, and nothing else + /// completed. Absence inference must not rest on partial speech. + #[test] + fn an_unrelated_event_without_a_completed_query_is_unknown_not_missing() { + let meshes = vec![mesh_with_id(Some("other"), &[])]; + // Spoke (delivered an event) but never finished the query. + let partial = listing_presence(&meshes, health(1, 0), Some("abc"), &[]); + assert_eq!(partial, ListingPresence::Unknown); + // The same round with a completed query elsewhere is a verdict. + let completed = listing_presence(&meshes, health(2, 1), Some("abc"), &[]); + assert_eq!(completed, ListingPresence::Missing); + } + + #[test] + fn matching_mesh_id_means_present() { + let meshes = vec![mesh_with_id(Some("abc"), &[])]; + assert_eq!( + listing_presence(&meshes, health(5, 5), Some("abc"), &[]), + ListingPresence::Present + ); + } + + #[test] + fn absence_with_answers_means_missing() { + let meshes = vec![mesh_with_id(Some("other"), &[])]; + assert_eq!( + listing_presence(&meshes, health(5, 5), Some("abc"), &[]), + ListingPresence::Missing + ); + // Empty results with a live relay are still a verdict. + assert_eq!( + listing_presence(&[], health(1, 1), Some("abc"), &[]), + ListingPresence::Missing + ); + } + + #[test] + fn absence_with_no_answers_is_unknown_not_missing() { + let meshes = vec![mesh_with_id(Some("other"), &[])]; + assert_eq!( + listing_presence(&meshes, health(0, 0), Some("abc"), &[]), + ListingPresence::Unknown + ); + } + + #[test] + fn unknown_presence_never_satisfies_the_takeover_gate_even_with_peers() { + // `should_take_over_publish` requires Missing AND (peers OR + // served). An outage round is Unknown no matter how healthy the + // mesh is, so the conjunction must fail on the presence side + // alone — this is the property that keeps the watchdog from + // taking over during relay outages. + let meshes = vec![mesh_with_id(Some("other"), &[])]; + let outage = listing_presence(&meshes, health(0, 0), Some("abc"), &[]); + assert_ne!(outage, ListingPresence::Missing); + assert_eq!(outage, ListingPresence::Unknown); + + // And the errored-fetch path feeds the same Unknown: a round + // where every fetch errored (requests never issued) has zero + // answered relays, not a quorum of speaking ones. + let all_errored = (0..5).map(|_| RelayFetchResult::Silent).collect::>(); + let (_, health) = merge_relay_fetch_results(5, all_errored); + assert!(!health.any_relay_answered()); + } + + #[test] + fn legacy_served_model_fallback_still_detects_presence() { + let meshes = vec![mesh_with_id(None, &["Qwen3-8B-Q4_K_M"])]; + let served = vec!["Qwen3-8B-Q4_K_M".to_string()]; + assert_eq!( + listing_presence(&meshes, health(3, 3), None, &served), + ListingPresence::Present + ); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/mesh/crates/mesh-llm/src/commands/discover.rs b/mesh/crates/mesh-llm/src/commands/discover.rs index 284488e4ba..da18107b34 100644 --- a/mesh/crates/mesh-llm/src/commands/discover.rs +++ b/mesh/crates/mesh-llm/src/commands/discover.rs @@ -51,7 +51,27 @@ async fn run_nostr_discover( let mut err = mesh_llm_events::console_err(); writeln!(err, "🔍 Searching Nostr relays for mesh-llm meshes...")?; - let meshes = nostr::discover(&relays, &filter, None).await?; + let (meshes, health) = nostr::discover_with_health(&relays, &filter, None).await?; + if health.relays_answered < health.relays_queried { + // "No meshes found" reads very differently when the round never + // heard from most relays; say which state it was. + writeln!( + err, + "ℹ️ {} of {} Nostr relay(s) answered", + health.relays_answered, health.relays_queried + )?; + } + + if !health.any_relay_answered() { + // A round where no relay spoke is not an observation about the + // mesh plane — it is an observation about reachability. Report + // it as a failure so scripts can tell a genuine "no meshes" + // (some relay answered) from an unreachable discovery plane. + anyhow::bail!( + "no Nostr relay answered (0 of {}); check network or relay URLs", + health.relays_queried + ); + } let mut err = mesh_llm_events::console_err(); if meshes.is_empty() { diff --git a/mesh/docs/MESHES.md b/mesh/docs/MESHES.md index 317b4b05cc..0c74cb6f1a 100644 --- a/mesh/docs/MESHES.md +++ b/mesh/docs/MESHES.md @@ -328,6 +328,9 @@ mesh-llm discover --auto ``` `discover --auto` prints the best invite token, which is useful for scripts. +When some Nostr relays stay silent, `discover` prints an `N of M Nostr +relay(s) answered` line; when no relay answers at all it exits nonzero, so +scripts can tell an unreachable discovery plane from an empty one. When using `--mesh-discovery-mode mdns`, discovery is LAN-scoped: mDNS TXT records advertise bounded capacity/model summaries and a token fingerprint. When the management API is reachable from LAN peers, for example with diff --git a/mesh/docs/design/DESIGN.md b/mesh/docs/design/DESIGN.md index 2b6378866a..3ff57fddf4 100644 --- a/mesh/docs/design/DESIGN.md +++ b/mesh/docs/design/DESIGN.md @@ -535,7 +535,7 @@ model-output verification. The operator-facing behavior is specified in Opt-in mesh advertisement via Nostr relays (NIP-89, kind 31990): - `--publish`: republish listing every 60s (TTL 120s) - `--auto`: discover meshes, score them, health-probe, join best -- Publish watchdog: if publisher dies, another node takes over +- Publish watchdog: if publisher dies, another node takes over — but only when discovery actually heard from a relay (zero relays answering means "cannot tell", not "listing gone") - `score_mesh()`: region match (+200), capacity, node count, VRAM, sticky preference (+500) - `smart_auto()`: picks best mesh or recommends starting new one with models for your VRAM