From 172ff0fc27f0b828e502beb42c43cfd7c714b55a Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:14:53 +0530 Subject: [PATCH 1/5] fix(discovery): distinguish no relay answered from no meshes found MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nostr::discover folded every per-relay failure into an empty result, and nostr-sdk's fetch_events swallows per-relay errors — worse, its own timeout resolves a silent relay to Ok(empty), so even a per-relay fan-out could not see an outage without owning the deadline. Three callers acted on that ambiguity: the CLI printed 'No meshes found.', the watchdog took over publishing (permanently) on the theory that the listing had disappeared, and the backoff recheck treated its own fetch error as confirmation. discover_with_health fans the fetch out per relay and owns the 5 s deadline itself (tokio::time::timeout around the un-timed fetch), so a relay that stays silent surfaces as not-answered instead of an empty success; a relay that completes with an error still counts as answered, so a quorum of erroring relays is not misread as an outage. Events merge and dedupe by event id before the usual per-publisher dedupe, counted by a pure merge_relay_fetch_results helper with unit tests. discover() stays a thin wrapper so existing callers are unchanged. The watchdog's absence decision now goes through a pure ListingPresence helper — Present / Missing (some relay answered, none had our listing) / Unknown (no relay answered or the client could not be built) — and Unknown skips the takeover round instead of publishing on the strength of an outage. The CLI prints 'N of M Nostr relay(s) answered' whenever some relay stayed silent. The --auto StartNew-on-empty behavior is deliberately untouched. Round-5 convergence folded in: - fresh discovery clients now wait (capped at 2s) for their relay connections before the round, so the one-shot path's connection sample is meaningful and an answered empty EOSE counts as answered (previously every relay of a fresh client sampled as not connected, printing '0 of N answered' against relays that replied in under a second); - a fetch Err is classified silent, not spoken: in nostr-sdk 0.45.x per-relay errors never surface as Err, so an Err means the request never issued; - classify_relay_round is a plain fn; - direct tests for the errored-fetch classification and the Unknown-with-peers takeover gate; - mesh-llm discover now exits nonzero when no relay answered, so scripts can distinguish an unreachable discovery plane from a genuinely empty one. Round-6: the handshake wait now exits as soon as every relay's first connection attempt settles (connected, or a terminal status such as disconnected/banned/shutdown) instead of always waiting for the full cap when any relay is unreachable — with a partly dead default relay set, a one-shot discovery round (including each /api/discover request) now costs the healthy handshakes plus the failed attempt, not a flat 2s. --- .../src/command_support.rs | 3 +- .../src/network/nostr.rs | 2 +- .../src/network/nostr/discovery.rs | 361 +++++++++++++++++- .../src/network/nostr/publish.rs | 174 ++++++++- mesh/crates/mesh-llm/src/commands/discover.rs | 22 +- mesh/docs/MESHES.md | 3 + mesh/docs/design/DESIGN.md | 2 +- 7 files changed, 533 insertions(+), 34 deletions(-) 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..d3297b9a79 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,103 @@ 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 completed the round trip — an EOSE, possibly empty. + /// Silence-until-deadline and never-issued requests do not count. + pub relays_answered: usize, +} + +impl RelayHealth { + /// False only when no relay answered at all — the "cannot tell" + /// state for absence-based decisions. + pub fn any_relay_answered(&self) -> bool { + self.relays_answered > 0 + } +} + +/// One relay's raw fetch outcome: whether its connection was live when +/// the attempt started, and the deadline-wrapped per-relay fetch result. +type RelayFetchOutcome = ( + bool, + Result< + Result, nostr_sdk::prelude::Error>, + tokio::time::error::Elapsed, + >, +); + +/// One relay's fetch outcome, normalized for counting and merging. +#[derive(Debug)] +pub(crate) enum RelayFetchResult { + /// The relay completed the round trip: events, or an empty EOSE from + /// a connection that was live when the attempt started. + Answered(std::collections::BTreeSet), + /// The relay never spoke: silence until the deadline, or a fetch + /// error that means the request was never issued to it. + Silent, +} + +/// Classify one relay's fetch outcome. +/// +/// `relay_connected` is the relay's live connection status, consulted for +/// empty successes because nostr-sdk resolves relays it has given up on +/// to a fast `Ok(empty)`: only a connected relay's empty result means +/// "healthy relay, nothing stored" (EOSE). +/// +/// An `Err` counts as silent, not spoken. In nostr-sdk 0.45.x per-relay +/// failures never surface as `Err` — the fetch collector logs them and +/// keeps collecting — so an `Err` here means the request never reached +/// the relay (target resolution, buffer limits). Counting it as answered +/// would inflate `relays_answered` in the unsafe direction if a future +/// SDK ever did propagate relay failures as `Err`. +pub(crate) fn classify_relay_fetch( + events: Result, E>, + relay_connected: bool, +) -> RelayFetchResult { + match events { + Ok(set) if !set.is_empty() => RelayFetchResult::Answered(set), + Ok(_) if relay_connected => RelayFetchResult::Answered(Default::default()), + Ok(_) | Err(_) => 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; + for result in results { + match result { + RelayFetchResult::Answered(relay_events) => { + relays_answered += 1; + events.extend(relay_events); + } + RelayFetchResult::Silent => {} + } + } + ( + events, + RelayHealth { + relays_queried, + relays_answered, + }, + ) +} + /// 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 +193,7 @@ impl DiscoveryClient { ); } client.connect().await; + wait_for_relay_connections(&client, CONNECT_WAIT_CAP).await; Ok(Self { client }) } } @@ -104,12 +202,68 @@ 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) +} + +/// Turn per-relay fetch outcomes into counted classifications. +/// +/// Empty successes are checked against the relay's live connection +/// status (nostr-sdk resolves relays it has given up on to a fast +/// Ok(empty)), deadline silence stays silent, and a fetch error means +/// the request never issued (nostr-sdk 0.45.x swallows per-relay +/// failures inside the collector), so the relay did not speak. +fn classify_relay_round( + relay_urls: &[nostr_sdk::prelude::RelayUrl], + results: Vec, +) -> Vec { + let mut outcomes: Vec = Vec::with_capacity(results.len()); + for (url, (connected_at_start, result)) in relay_urls.iter().cloned().zip(results) { + match result { + Ok(Ok(relay_events)) => { + // The SDK also resolves a relay it has given up + // connecting to (or one mid-reconnect) to a fast + // Ok(empty) — a spoke-relay is only one whose connection + // was live when the attempt started. + outcomes.push(classify_relay_fetch::( + Ok(relay_events), + connected_at_start, + )); + } + Ok(Err(e)) => { + tracing::warn!("Nostr relay {url} fetch failed: {e}"); + outcomes.push(classify_relay_fetch::<()>(Err(()), false)); + } + Err(_) => { + tracing::debug!("Nostr relay {url} stayed silent until the deadline"); + outcomes.push(RelayFetchResult::Silent); + } + } + } + outcomes +} + +/// 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 +273,46 @@ pub async fn discover( &_tmp }; - let nostr_filter = Filter::new() - .kind(Kind::Custom(MESH_SERVICE_KIND)) - .custom_tag(SingleLetterTag::LOWERCASE_K, "mesh-llm".to_string()) - .limit(100); - - 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 + // 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(); + + let fetch_one = |url: nostr_sdk::prelude::RelayUrl| { + let nostr_filter = Filter::new() + .kind(Kind::Custom(MESH_SERVICE_KIND)) + .custom_tag(SingleLetterTag::LOWERCASE_K, "mesh-llm".to_string()) + .limit(100); + // The timeout is ours, not the SDK's: fetch_events resolves a + // silent relay to Ok(empty) at its own timeout, which would make + // an outage indistinguishable from an empty relay. Wrapping the + // un-timed future means only a relay that actually completed + // (EOSE or error) resolves before the deadline; silence surfaces + // as Err(Elapsed). + // Connection status is sampled BEFORE the fetch, describing the + // state the attempt started from; sampling after would let a + // gave-up relay that reconnects mid-round masquerade as having + // answered with its earlier fast Ok(empty). + async move { + let connected_at_start = client + .relay(&url) + .await + .ok() + .flatten() + .is_some_and(|relay| relay.status().is_connected()); + let outcome = tokio::time::timeout( + Duration::from_secs(5), + client.fetch_events(ReqTarget::single(url, vec![nostr_filter])), + ) + .await; + (connected_at_start, outcome) } }; + let results = futures_util::future::join_all(relay_urls.iter().cloned().map(fetch_one)).await; + + let outcomes = classify_relay_round(&relay_urls, results); + let (events, health) = merge_relay_fetch_results(relay_urls.len(), outcomes); let now = Timestamp::now().as_secs(); @@ -160,7 +338,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 +404,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 +461,110 @@ 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(set) + } + + #[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 + } + ); + 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()); + } + + #[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(first), + RelayFetchResult::Answered(second), + ], + ); + assert_eq!(events.len(), 1); + assert_eq!(health.relays_answered, 2); + } + + #[test] + fn an_empty_result_from_a_disconnected_relay_is_silence() { + // The SDK resolves relays it gave up connecting to a fast + // Ok(empty); without the connection check a sustained outage + // would read as every relay answering. + let classified = classify_relay_fetch::<()>(Ok(Default::default()), false); + assert!(matches!(classified, RelayFetchResult::Silent)); + } + + #[test] + fn an_empty_result_from_a_connected_relay_is_an_answer() { + // EOSE with nothing stored is a healthy, speaking relay. + let classified = classify_relay_fetch::<()>(Ok(Default::default()), true); + assert!(matches!(classified, RelayFetchResult::Answered(_))); + } + + #[test] + fn an_errored_fetch_never_reached_the_relay_and_is_silence() { + // In nostr-sdk 0.45.x per-relay failures are swallowed by the + // fetch collector; an Err means the request was never issued + // (target resolution, buffer limits). The relay did not speak. + let classified = classify_relay_fetch::<()>(Err(()), true); + assert!(matches!(classified, RelayFetchResult::Silent)); + let classified = classify_relay_fetch::<()>(Err(()), false); + assert!(matches!(classified, RelayFetchResult::Silent)); + } + + #[test] + fn a_non_empty_result_is_an_answer_regardless_of_status() { + 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 classified = classify_relay_fetch::<()>(Ok(set), false); + assert!(matches!(classified, RelayFetchResult::Answered(_))); + } +} + #[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..9bcccc4ee5 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,45 @@ 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 answered and none had our listing. + Missing, + /// No relay answered; 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_relay_answered() { + 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 +446,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 +728,103 @@ 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) -> RelayHealth { + RelayHealth { + relays_queried: 5, + relays_answered: answered, + } + } + + #[test] + fn matching_mesh_id_means_present() { + let meshes = vec![mesh_with_id(Some("abc"), &[])]; + assert_eq!( + listing_presence(&meshes, health(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), Some("abc"), &[]), + ListingPresence::Missing + ); + // Empty results with a live relay are still a verdict. + assert_eq!( + listing_presence(&[], health(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), 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), 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), 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 From 35cb3c0e73a96cf8ecaf8063fccec7b282c83f82 Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:53:02 +0530 Subject: [PATCH 2/5] fix(discovery): count relays on completion evidence, not connection snapshots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drive one subscription across the pool and route the notification stream per relay instead of racing per-relay fetch_events futures: - EOSE observed for a relay is completion evidence an empty event set still counts as answered on; a relay that disconnects mid-fetch sends no EOSE, so a truncated round can no longer pose as a completed empty one the way a pre-fetch connection snapshot allowed. - Events accumulate outside any cancellable future, so a relay that delivered listings before the deadline keeps them even when it never finishes; it counts as answered — speech is evidence regardless of completion. - A subscription the relay Closed without EOSE is marked terminal so the round does not wait out the deadline on its behalf; it is a non-answer unless events arrived. - The subscription is always unsubscribed, including on the cached client the watchdog reuses, so no REQ leaks into later rounds. The settled handshake wait stays: a fresh one-shot client still needs its relays connected before the REQ can be delivered at all. --- .../src/network/nostr/discovery.rs | 298 ++++++++++-------- 1 file changed, 175 insertions(+), 123 deletions(-) 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 d3297b9a79..e7028864c0 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 @@ -94,48 +94,54 @@ impl RelayHealth { } } -/// One relay's raw fetch outcome: whether its connection was live when -/// the attempt started, and the deadline-wrapped per-relay fetch result. -type RelayFetchOutcome = ( - bool, - Result< - Result, nostr_sdk::prelude::Error>, - tokio::time::error::Elapsed, - >, -); +/// 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 completed the round trip: events, or an empty EOSE from - /// a connection that was live when the attempt started. + /// The relay completed the round trip (EOSE) or delivered events + /// before the round ended — either way it spoke. Answered(std::collections::BTreeSet), - /// The relay never spoke: silence until the deadline, or a fetch - /// error that means the request was never issued to it. + /// 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 fetch outcome. -/// -/// `relay_connected` is the relay's live connection status, consulted for -/// empty successes because nostr-sdk resolves relays it has given up on -/// to a fast `Ok(empty)`: only a connected relay's empty result means -/// "healthy relay, nothing stored" (EOSE). +/// Classify one relay's round from completion evidence. /// -/// An `Err` counts as silent, not spoken. In nostr-sdk 0.45.x per-relay -/// failures never surface as `Err` — the fetch collector logs them and -/// keeps collecting — so an `Err` here means the request never reached -/// the relay (target resolution, buffer limits). Counting it as answered -/// would inflate `relays_answered` in the unsafe direction if a future -/// SDK ever did propagate relay failures as `Err`. -pub(crate) fn classify_relay_fetch( - events: Result, E>, - relay_connected: bool, -) -> RelayFetchResult { - match events { - Ok(set) if !set.is_empty() => RelayFetchResult::Answered(set), - Ok(_) if relay_connected => RelayFetchResult::Answered(Default::default()), - Ok(_) | Err(_) => RelayFetchResult::Silent, +/// 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(round.events) + } else { + RelayFetchResult::Silent } } @@ -214,43 +220,6 @@ pub async fn discover( Ok(meshes) } -/// Turn per-relay fetch outcomes into counted classifications. -/// -/// Empty successes are checked against the relay's live connection -/// status (nostr-sdk resolves relays it has given up on to a fast -/// Ok(empty)), deadline silence stays silent, and a fetch error means -/// the request never issued (nostr-sdk 0.45.x swallows per-relay -/// failures inside the collector), so the relay did not speak. -fn classify_relay_round( - relay_urls: &[nostr_sdk::prelude::RelayUrl], - results: Vec, -) -> Vec { - let mut outcomes: Vec = Vec::with_capacity(results.len()); - for (url, (connected_at_start, result)) in relay_urls.iter().cloned().zip(results) { - match result { - Ok(Ok(relay_events)) => { - // The SDK also resolves a relay it has given up - // connecting to (or one mid-reconnect) to a fast - // Ok(empty) — a spoke-relay is only one whose connection - // was live when the attempt started. - outcomes.push(classify_relay_fetch::( - Ok(relay_events), - connected_at_start, - )); - } - Ok(Err(e)) => { - tracing::warn!("Nostr relay {url} fetch failed: {e}"); - outcomes.push(classify_relay_fetch::<()>(Err(()), false)); - } - Err(_) => { - tracing::debug!("Nostr relay {url} stayed silent until the deadline"); - outcomes.push(RelayFetchResult::Silent); - } - } - } - outcomes -} - /// Discover meshes and report how many relays answered. /// /// The fetch fans out per relay (one request each, 5 s timeout) so a @@ -279,39 +248,106 @@ pub async fn discover_with_health( let relay_urls: Vec = client.relays().await.keys().cloned().collect(); - let fetch_one = |url: nostr_sdk::prelude::RelayUrl| { - let nostr_filter = Filter::new() - .kind(Kind::Custom(MESH_SERVICE_KIND)) - .custom_tag(SingleLetterTag::LOWERCASE_K, "mesh-llm".to_string()) - .limit(100); - // The timeout is ours, not the SDK's: fetch_events resolves a - // silent relay to Ok(empty) at its own timeout, which would make - // an outage indistinguishable from an empty relay. Wrapping the - // un-timed future means only a relay that actually completed - // (EOSE or error) resolves before the deadline; silence surfaces - // as Err(Elapsed). - // Connection status is sampled BEFORE the fetch, describing the - // state the attempt started from; sampling after would let a - // gave-up relay that reconnects mid-round masquerade as having - // answered with its earlier fast Ok(empty). - async move { - let connected_at_start = client - .relay(&url) - .await - .ok() - .flatten() - .is_some_and(|relay| relay.status().is_connected()); - let outcome = tokio::time::timeout( - Duration::from_secs(5), - client.fetch_events(ReqTarget::single(url, vec![nostr_filter])), - ) - .await; - (connected_at_start, outcome) + // 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 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 results = futures_util::future::join_all(relay_urls.iter().cloned().map(fetch_one)).await; + 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, + }; + match notification { + ClientNotification::Event { + relay_url, + subscription_id: id, + event, + } if id == subscription_id => { + // This variant is client-deduplicated ("first time the + // event is seen"), so an event two relays both deliver + // attributes only to whichever arrived first. The merged + // result is unaffected (it deduplicates anyway), and the + // counting effect is confined to a relay whose only + // deliveries were duplicates — it can under-count toward + // Silent, never inflate toward Answered. + if let Some(round) = rounds.get_mut(&relay_url) { + round.events.insert(*event); + } + } + ClientNotification::Message { relay_url, message } => match *message { + 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; + } + } + _ => {} + }, + _ => {} + } + } + // 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 = classify_relay_round(&relay_urls, results); + 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(); @@ -527,41 +563,57 @@ mod relay_health_tests { } #[test] - fn an_empty_result_from_a_disconnected_relay_is_silence() { - // The SDK resolves relays it gave up connecting to a fast - // Ok(empty); without the connection check a sustained outage - // would read as every relay answering. - let classified = classify_relay_fetch::<()>(Ok(Default::default()), false); + 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)); - } - #[test] - fn an_empty_result_from_a_connected_relay_is_an_answer() { - // EOSE with nothing stored is a healthy, speaking relay. - let classified = classify_relay_fetch::<()>(Ok(Default::default()), true); - assert!(matches!(classified, RelayFetchResult::Answered(_))); + // 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 an_errored_fetch_never_reached_the_relay_and_is_silence() { - // In nostr-sdk 0.45.x per-relay failures are swallowed by the - // fetch collector; an Err means the request was never issued - // (target resolution, buffer limits). The relay did not speak. - let classified = classify_relay_fetch::<()>(Err(()), true); - assert!(matches!(classified, RelayFetchResult::Silent)); - let classified = classify_relay_fetch::<()>(Err(()), false); - assert!(matches!(classified, RelayFetchResult::Silent)); + 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(set) if set.is_empty())); } #[test] - fn a_non_empty_result_is_an_answer_regardless_of_status() { + 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 classified = classify_relay_fetch::<()>(Ok(set), false); - assert!(matches!(classified, RelayFetchResult::Answered(_))); + let unfinished = RelayRound { + events: set, + ..RelayRound::default() + }; + let classified = classify_relay_round_outcome(unfinished); + match classified { + RelayFetchResult::Answered(events) => assert_eq!(events.len(), 1), + other => panic!("expected Answered, got {other:?}"), + } } } From 14d93ef82b31aa9851607a2d9bf7afb46b1daed0 Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:18:40 +0530 Subject: [PATCH 3/5] fix(discovery): collect repeat deliveries from the raw relay message stream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClientNotification::Event is deduplicated against the client's event database, not per round: on the watchdog's cached client, a listing re-delivered in a later round was suppressed while its relay's EOSE still counted, producing an answered-with-nothing round that listing_presence read as Missing — a takeover for a listing that is present. Collect from the raw RelayMessage::Event in the Message arm instead: it is delivered on every receipt and carries the fully validated event (limits, filter match, expiry, signature). The notification handling is extracted into a pure apply_discovery_notification so the round-2 notification shape (raw event + EOSE, no deduped variant) is unit-testable; the new regression test fails if collection ever reverts to the deduped arm. --- .../src/network/nostr/discovery.rs | 139 +++++++++++++----- 1 file changed, 100 insertions(+), 39 deletions(-) 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 e7028864c0..0b4bf1d654 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 @@ -220,6 +220,54 @@ pub async fn discover( 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 => { + if let Some(round) = rounds.get_mut(&relay_url) { + round.events.insert(event.into_owned()); + } + } + 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 @@ -298,45 +346,7 @@ pub async fn discover_with_health( // are already accumulated and are kept. Ok(None) | Err(_) => break, }; - match notification { - ClientNotification::Event { - relay_url, - subscription_id: id, - event, - } if id == subscription_id => { - // This variant is client-deduplicated ("first time the - // event is seen"), so an event two relays both deliver - // attributes only to whichever arrived first. The merged - // result is unaffected (it deduplicates anyway), and the - // counting effect is confined to a relay whose only - // deliveries were duplicates — it can under-count toward - // Silent, never inflate toward Answered. - if let Some(round) = rounds.get_mut(&relay_url) { - round.events.insert(*event); - } - } - ClientNotification::Message { relay_url, message } => match *message { - 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; - } - } - _ => {} - }, - _ => {} - } + 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 @@ -562,6 +572,57 @@ mod relay_health_tests { assert_eq!(health.relays_answered, 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:?}"), + } + } + #[test] fn a_round_without_eose_or_events_is_silence() { // A relay that never connected, disconnected before EOSE, or From 018b1ea552d52389a1dd64a8a5fef30cc76dca2e Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:09:08 +0530 Subject: [PATCH 4/5] fix(discovery): require a completed query for absence, verify raw events MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review-round-3 findings: - Absence inference no longer rests on partial speech. A relay that delivered an unrelated event and disconnected before EOSE counted as answered, so listing_presence could return Missing — and the watchdog take over — with no completed query behind the absence. RelayHealth gains queries_completed (EOSE count); Missing now requires any_query_completed(), while partial events keep supporting positive matches and the CLI's spoke-based outage reporting. - Every raw event is verified before collection. The SDK's relay verification cache keys on the claimed event id and returns Ok on a cache hit without checking the signature (shared.rs verify_and_cache), so a relay can replay a cached id over altered content and reach the raw message stream. The collector now runs event.verify() — hash and signature against the content actually received — and drops invalid events. Regression tests: an unrelated event without a completed query is Unknown, not Missing; an event reusing a cached id with altered content is rejected while the legitimate repeat is kept. --- .../src/network/nostr/discovery.rs | 142 +++++++++++++++--- .../src/network/nostr/publish.rs | 38 +++-- 2 files changed, 152 insertions(+), 28 deletions(-) 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 0b4bf1d654..209ca931f7 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 @@ -81,17 +81,30 @@ impl MeshFilter { pub struct RelayHealth { /// Relays the discovery client tried to query. pub relays_queried: usize, - /// Relays that completed the round trip — an EOSE, possibly empty. - /// Silence-until-deadline and never-issued requests do not count. + /// 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 absence-based decisions. + /// 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. @@ -118,9 +131,13 @@ impl RelayRound { /// One relay's fetch outcome, normalized for counting and merging. #[derive(Debug)] pub(crate) enum RelayFetchResult { - /// The relay completed the round trip (EOSE) or delivered events - /// before the round ended — either way it spoke. - Answered(std::collections::BTreeSet), + /// 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. @@ -139,7 +156,10 @@ pub(crate) enum RelayFetchResult { /// completed empty one. pub(crate) fn classify_relay_round_outcome(round: RelayRound) -> RelayFetchResult { if round.eose || !round.events.is_empty() { - RelayFetchResult::Answered(round.events) + RelayFetchResult::Answered { + events: round.events, + completed_query: round.eose, + } } else { RelayFetchResult::Silent } @@ -156,10 +176,15 @@ pub(crate) fn merge_relay_fetch_results( ) -> (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(relay_events) => { + RelayFetchResult::Answered { + events: relay_events, + completed_query, + } => { relays_answered += 1; + queries_completed += usize::from(completed_query); events.extend(relay_events); } RelayFetchResult::Silent => {} @@ -170,6 +195,7 @@ pub(crate) fn merge_relay_fetch_results( RelayHealth { relays_queried, relays_answered, + queries_completed, }, ) } @@ -244,8 +270,22 @@ fn apply_discovery_notification( subscription_id: id, event, } if *id == *subscription_id => { - if let Some(round) = rounds.get_mut(&relay_url) { - round.events.insert(event.into_owned()); + 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 => { @@ -521,7 +561,10 @@ mod relay_health_tests { .expect("sign"); set.insert(event); } - RelayFetchResult::Answered(set) + RelayFetchResult::Answered { + events: set, + completed_query: true, + } } #[test] @@ -538,7 +581,8 @@ mod relay_health_tests { health, RelayHealth { relays_queried: 3, - relays_answered: 1 + relays_answered: 1, + queries_completed: 1 } ); assert!(events.is_empty()); @@ -549,6 +593,7 @@ mod relay_health_tests { let (_, health) = merge_relay_fetch_results(5, (0..5).map(|_| RelayFetchResult::Silent).collect()); assert!(!health.any_relay_answered()); + assert!(!health.any_query_completed()); } #[test] @@ -564,12 +609,19 @@ mod relay_health_tests { let (events, health) = merge_relay_fetch_results( 2, vec![ - RelayFetchResult::Answered(first), - RelayFetchResult::Answered(second), + 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 @@ -616,13 +668,62 @@ mod relay_health_tests { let round = rounds.remove(&relay_url).expect("round to exist"); let classified = classify_relay_round_outcome(round); match classified { - RelayFetchResult::Answered(events) => { + 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. + #[test] + fn an_event_reusing_a_cached_id_with_altered_content_is_rejected() { + 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 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"); + + let mut rounds = HashMap::new(); + rounds.insert(relay_url.clone(), RelayRound::default()); + + for event in [valid, forged] { + 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), + }), + }, + ); + } + + let round = rounds.remove(&relay_url).expect("round to exist"); + // Only the legitimate event survives; the forged replay is + // dropped by verification. + assert_eq!(round.events.len(), 1); + } + #[test] fn a_round_without_eose_or_events_is_silence() { // A relay that never connected, disconnected before EOSE, or @@ -652,7 +753,9 @@ mod relay_health_tests { ..RelayRound::default() }; let classified = classify_relay_round_outcome(completed_empty); - assert!(matches!(classified, RelayFetchResult::Answered(set) if set.is_empty())); + assert!( + matches!(classified, RelayFetchResult::Answered { events, completed_query: true } if events.is_empty()) + ); } #[test] @@ -672,8 +775,11 @@ mod relay_health_tests { }; let classified = classify_relay_round_outcome(unfinished); match classified { - RelayFetchResult::Answered(events) => assert_eq!(events.len(), 1), - other => panic!("expected Answered, got {other:?}"), + RelayFetchResult::Answered { + events, + completed_query: false, + } => assert_eq!(events.len(), 1), + other => panic!("expected Answered without completion, got {other:?}"), } } } 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 9bcccc4ee5..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 @@ -399,9 +399,12 @@ async fn watchdog_initial_delay() { pub(crate) enum ListingPresence { /// A current listing for our mesh was seen. Present, - /// At least one relay answered and none had our listing. + /// 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 answered; absence is not evidence. + /// No relay completed its query; absence is not evidence. Unknown, } @@ -413,7 +416,7 @@ fn listing_presence( ) -> ListingPresence { if mesh_listing_present(meshes, mesh_id, served) { ListingPresence::Present - } else if health.any_relay_answered() { + } else if health.any_query_completed() { ListingPresence::Missing } else { ListingPresence::Unknown @@ -755,18 +758,33 @@ mod listing_presence_tests { } } - fn health(answered: usize) -> RelayHealth { + 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), Some("abc"), &[]), + listing_presence(&meshes, health(5, 5), Some("abc"), &[]), ListingPresence::Present ); } @@ -775,12 +793,12 @@ mod listing_presence_tests { fn absence_with_answers_means_missing() { let meshes = vec![mesh_with_id(Some("other"), &[])]; assert_eq!( - listing_presence(&meshes, health(5), Some("abc"), &[]), + 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), Some("abc"), &[]), + listing_presence(&[], health(1, 1), Some("abc"), &[]), ListingPresence::Missing ); } @@ -789,7 +807,7 @@ mod listing_presence_tests { fn absence_with_no_answers_is_unknown_not_missing() { let meshes = vec![mesh_with_id(Some("other"), &[])]; assert_eq!( - listing_presence(&meshes, health(0), Some("abc"), &[]), + listing_presence(&meshes, health(0, 0), Some("abc"), &[]), ListingPresence::Unknown ); } @@ -802,7 +820,7 @@ mod listing_presence_tests { // 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), Some("abc"), &[]); + let outage = listing_presence(&meshes, health(0, 0), Some("abc"), &[]); assert_ne!(outage, ListingPresence::Missing); assert_eq!(outage, ListingPresence::Unknown); @@ -819,7 +837,7 @@ mod listing_presence_tests { 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), None, &served), + listing_presence(&meshes, health(3, 3), None, &served), ListingPresence::Present ); } From 6d77bad164d33d8a2f68263fd555318a6a5949f5 Mon Sep 17 00:00:00 2001 From: iamthesvn <112808417+iamthesvn@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:30:08 +0530 Subject: [PATCH 5/5] test(discovery): isolate the forged event in its own round MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cached-id regression shared a round between the legitimate and forged events; with the same created_at second and the same claimed id the two compare Ord::Equal in the BTreeSet, so the forged insert was a no-op even without verification — the test pinned the collision, not the verify() call. Each event now goes to a fresh round: the forged replay alone must leave the round empty. --- .../src/network/nostr/discovery.rs | 57 ++++++++++++------- 1 file changed, 36 insertions(+), 21 deletions(-) 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 209ca931f7..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 @@ -679,12 +679,36 @@ mod relay_health_tests { /// 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 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(); @@ -701,27 +725,18 @@ mod relay_health_tests { value["id"] = serde_json::to_value(valid.id).expect("id json"); let forged: Event = serde_json::from_value(value).expect("deserialize"); - let mut rounds = HashMap::new(); - rounds.insert(relay_url.clone(), RelayRound::default()); + // The legitimate event is collected. + let accepted = round_with(&id, &relay_url, valid); + assert_eq!(accepted.events.len(), 1); - for event in [valid, forged] { - 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), - }), - }, - ); - } - - let round = rounds.remove(&relay_url).expect("round to exist"); - // Only the legitimate event survives; the forged replay is - // dropped by verification. - assert_eq!(round.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]