From 502eed9028c8905937783c7353829f1e78bb685c Mon Sep 17 00:00:00 2001 From: Jimmy <1fe240cd1a8cf775f6f3060f115e5a303181f3abf28ad4cb0c2515f4a02b36a8@meshllm.communities.buzz.xyz> Date: Sat, 29 Aug 2026 09:04:19 +1000 Subject: [PATCH] fix(mesh): close admission restart loop Apply one persisted cooldown and in-memory latch to both admission-mode restart paths, retain throttling across clock rollback, and cover the composed self-only hysteresis wiring. Make the shared Tauri clippy recipe feature-enable mesh support so local checks and CI stay aligned. Co-authored-by: Jimmy <1fe240cd1a8cf775f6f3060f115e5a303181f3abf28ad4cb0c2515f4a02b36a8@meshllm.communities.buzz.xyz> Signed-off-by: Jimmy <1fe240cd1a8cf775f6f3060f115e5a303181f3abf28ad4cb0c2515f4a02b36a8@meshllm.communities.buzz.xyz> --- .github/workflows/ci.yml | 4 - Justfile | 4 +- desktop/src-tauri/src/mesh_llm/coordinator.rs | 149 +++++++++++------- .../src/mesh_llm/coordinator_admission.rs | 97 ++++++++++-- 4 files changed, 179 insertions(+), 75 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 87c45a8b4a..00474ce0ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,10 +214,6 @@ jobs: run: just desktop-tauri-test env: CMAKE_POLICY_VERSION_MINIMUM: "3.5" - - name: Desktop Mesh clippy - run: cargo clippy --manifest-path desktop/src-tauri/Cargo.toml --workspace --all-targets --features mesh-llm -- -D warnings - env: - CMAKE_POLICY_VERSION_MINIMUM: "3.5" - name: Desktop Mesh admission tests run: cargo test --manifest-path desktop/src-tauri/Cargo.toml --features mesh-llm --lib env: diff --git a/Justfile b/Justfile index c2eaf2ed5e..038f575bad 100644 --- a/Justfile +++ b/Justfile @@ -210,8 +210,10 @@ _ensure-migrations: _ensure-services ./scripts/seed-local-community.sh # Run clippy on the desktop Tauri Rust crate +# Mesh support is part of the shipped desktop contract, so local `just check` +# and CI both lint the same feature-enabled graph. desktop-tauri-clippy: _ensure-sidecar-stubs - cargo clippy --manifest-path {{desktop_tauri_manifest}} --workspace --all-targets -- -D warnings + cargo clippy --manifest-path {{desktop_tauri_manifest}} --workspace --all-targets --features mesh-llm -- -D warnings # Check the desktop Tauri Rust crate compiles desktop-tauri-check: _ensure-sidecar-stubs diff --git a/desktop/src-tauri/src/mesh_llm/coordinator.rs b/desktop/src-tauri/src/mesh_llm/coordinator.rs index 75ecc4c10b..5de0cd2c86 100644 --- a/desktop/src-tauri/src/mesh_llm/coordinator.rs +++ b/desktop/src-tauri/src/mesh_llm/coordinator.rs @@ -12,8 +12,8 @@ use nostr::Tag; use tauri::{AppHandle, Manager}; use super::coordinator_admission::{ - clear_mode_recovery_restart, mark_mode_recovery_restart, mode_reconcile_action, - mode_recovery_restart_is_throttled, ModeEvidence, ModeReconcileAction, ModeReconcileState, + clear_mode_restart, mode_reconcile_action, request_mode_restart, ModeEvidence, + ModeReconcileAction, ModeReconcileState, }; use crate::app_state::AppState; @@ -342,11 +342,42 @@ async fn observe_open_runtime_relay(state: &AppState, relay_url: &str) -> OpenRu classify_open_runtime_observation(mode, closed_roster) } +#[derive(Debug, PartialEq, Eq)] +enum SelfOnlyModeAction { + Keep, + AwaitConfirm, + RestartProcess, +} + +fn reconcile_self_only_mode( + state: &mut ModeReconcileState, + query: &Result>, String>, +) -> SelfOnlyModeAction { + match query { + Ok(None) => match mode_reconcile_action(state, Ok(ModeEvidence::Open), false) { + ModeReconcileAction::Keep => SelfOnlyModeAction::Keep, + ModeReconcileAction::AwaitConfirm => SelfOnlyModeAction::AwaitConfirm, + ModeReconcileAction::RestartProcess => SelfOnlyModeAction::RestartProcess, + }, + Err(_) => { + let _ = mode_reconcile_action(state, Err(()), false); + SelfOnlyModeAction::Keep + } + Ok(Some(_)) => { + let _ = mode_reconcile_action(state, Ok(ModeEvidence::Closed), false); + SelfOnlyModeAction::Keep + } + } +} + async fn reconcile_roster( app: &AppHandle, pending_shrink: &mut Option>, mode_reconcile: &mut ModeReconcileState, ) -> Result<(), String> { + if mode_reconcile.restart_requested() { + return Ok(()); + } let state = app.state::(); let current_request = { let runtime = state.mesh_llm_runtime.lock().await; @@ -368,9 +399,6 @@ async fn reconcile_roster( .as_deref() .map(str::to_owned) .unwrap_or_else(|| crate::relay::relay_ws_url_with_override(&state)); - if current_owners.is_none() { - clear_mode_recovery_restart(app); - } let Some(current_owners) = current_owners else { let observation = observe_open_runtime_relay(&state, &relay_url).await; let evidence = match &observation { @@ -391,19 +419,32 @@ async fn reconcile_roster( "buzz-mesh: relay membership mode changed; awaiting confirmation before restarting Buzz" ), ModeReconcileAction::RestartProcess => { - match &observation { - OpenRuntimeObservation::ClosedWithRoster => eprintln!( - "buzz-mesh: relay repeatedly reports membership enforcement; restarting Buzz to apply its allowlist" - ), - OpenRuntimeObservation::ClosedWithoutRoster(error) => eprintln!( - "buzz-mesh: relay repeatedly reports membership enforcement but its roster is unavailable; restarting Buzz fail-closed: {error}" - ), - OpenRuntimeObservation::Unknown(error) => eprintln!( - "buzz-mesh: open-relay mode remained unknown across two polls; restarting Buzz fail-closed: {error}" - ), - OpenRuntimeObservation::Open => {} + let reason = match &observation { + OpenRuntimeObservation::ClosedWithRoster => "open-to-closed", + OpenRuntimeObservation::ClosedWithoutRoster(_) => { + "open-to-closed-without-roster" + } + OpenRuntimeObservation::Unknown(_) => "open-mode-unknown", + OpenRuntimeObservation::Open => return Ok(()), + }; + if !request_mode_restart(app, mode_reconcile, reason)? { + eprintln!( + "buzz-mesh: mode-policy restart is already pending or throttled after a recent attempt; keeping the running policy" + ); + } else { + match &observation { + OpenRuntimeObservation::ClosedWithRoster => eprintln!( + "buzz-mesh: relay repeatedly reports membership enforcement; restarting Buzz to apply its allowlist" + ), + OpenRuntimeObservation::ClosedWithoutRoster(error) => eprintln!( + "buzz-mesh: relay repeatedly reports membership enforcement but its roster is unavailable; restarting Buzz fail-closed: {error}" + ), + OpenRuntimeObservation::Unknown(error) => eprintln!( + "buzz-mesh: open-relay mode remained unknown across two polls; restarting Buzz fail-closed: {error}" + ), + OpenRuntimeObservation::Open => {} + } } - app.request_restart(); } } *pending_shrink = None; @@ -424,33 +465,27 @@ async fn reconcile_roster( .await .map(Some) }; + if matches!(query, Ok(Some(_))) { + // A successful closed-roster read is decisive non-restarting mode + // evidence, so a prior cross-process mode-restart throttle may clear. + clear_mode_restart(app); + } if current_owners.is_empty() { - match &query { - Ok(None) => { - match mode_reconcile_action(mode_reconcile, Ok(ModeEvidence::Open), false) { - ModeReconcileAction::Keep => return Ok(()), - ModeReconcileAction::AwaitConfirm => { - eprintln!( - "buzz-mesh: isolated startup fallback observed an open relay; awaiting confirmation before restarting Buzz" + match reconcile_self_only_mode(mode_reconcile, &query) { + SelfOnlyModeAction::Keep => {} + SelfOnlyModeAction::AwaitConfirm => { + eprintln!( + "buzz-mesh: isolated startup fallback observed an open relay; awaiting confirmation before restarting Buzz" + ); + return Ok(()); + } + SelfOnlyModeAction::RestartProcess => { + if !request_mode_restart(app, mode_reconcile, "self-only-to-open")? { + eprintln!( + "buzz-mesh: open-mode recovery restart is already pending or throttled after a recent attempt; keeping the self-only fallback" ); - return Ok(()); - } - ModeReconcileAction::RestartProcess => { - if mode_recovery_restart_is_throttled(app)? { - eprintln!( - "buzz-mesh: open-mode recovery restart is throttled after a recent attempt; keeping the self-only fallback" - ); - return Ok(()); - } - mark_mode_recovery_restart(app)?; - } } - } - Err(_) => { - let _ = mode_reconcile_action(mode_reconcile, Err(()), false); - } - Ok(Some(_)) => { - let _ = mode_reconcile_action(mode_reconcile, Ok(ModeEvidence::Closed), false); + return Ok(()); } } } else { @@ -714,21 +749,27 @@ mod tests { ); } - // Regression: a transient NIP-11 probe failure at startup on an OPEN relay - // falls back to the enforcing path and starts the node with a self-only - // allowlist. If reconcile then treated `Ok(None)` as an unconditional - // `Keep`, that node would sit at "1 NODE" until an app restart — the - // original open-relay bug, reintroduced by a single HTTP blip. A self-only - // roster admits nobody else, so restarting to run unenforced relaxes - // nothing that was protecting anyone. #[test] - fn open_relay_recovers_a_fallback_isolated_node() { - let self_only: Vec = Vec::new(); - let action = roster_reconcile_action(&self_only, None, Ok(None)); + fn self_only_wiring_never_restarts_after_one_open_observation() { + let mut state = ModeReconcileState::default(); + let query = Ok(None); assert_eq!( - action, - RosterReconcileAction::RestartProcess, - "a fallback-isolated node on an open relay must restart into open mesh" + reconcile_self_only_mode(&mut state, &query), + SelfOnlyModeAction::AwaitConfirm + ); + } + + #[test] + fn self_only_wiring_restarts_after_two_open_observations() { + let mut state = ModeReconcileState::default(); + let query = Ok(None); + assert_eq!( + reconcile_self_only_mode(&mut state, &query), + SelfOnlyModeAction::AwaitConfirm + ); + assert_eq!( + reconcile_self_only_mode(&mut state, &query), + SelfOnlyModeAction::RestartProcess ); } diff --git a/desktop/src-tauri/src/mesh_llm/coordinator_admission.rs b/desktop/src-tauri/src/mesh_llm/coordinator_admission.rs index 19806d770a..54d8ccc77b 100644 --- a/desktop/src-tauri/src/mesh_llm/coordinator_admission.rs +++ b/desktop/src-tauri/src/mesh_llm/coordinator_admission.rs @@ -2,43 +2,54 @@ use std::time::Duration; use tauri::{AppHandle, Manager}; -/// Prevent a flaky startup mode probe from creating an unbounded whole-app -/// restart loop while recovering a self-only fallback into open mode. -const MODE_RECOVERY_RESTART_COOLDOWN: Duration = Duration::from_secs(10 * 60); -const MODE_RECOVERY_RESTART_MARKER: &str = "mesh-mode-recovery-restart"; +/// Prevent a flaky mode probe from creating an unbounded whole-app restart +/// loop while changing admission policy. +const MODE_RESTART_COOLDOWN: Duration = Duration::from_secs(10 * 60); +const MODE_RESTART_MARKER: &str = "mesh-mode-recovery-restart"; -fn mode_recovery_restart_marker(app: &AppHandle) -> Result { +fn mode_restart_marker(app: &AppHandle) -> Result { Ok(app .path() .app_data_dir() .map_err(|error| format!("failed to resolve app data directory: {error}"))? - .join(MODE_RECOVERY_RESTART_MARKER)) + .join(MODE_RESTART_MARKER)) } -pub(super) fn mode_recovery_restart_is_throttled(app: &AppHandle) -> Result { - let marker = mode_recovery_restart_marker(app)?; +fn restart_marker_is_throttled( + modified: std::time::SystemTime, + now: std::time::SystemTime, +) -> bool { + // A clock rollback makes the marker appear to be in the future. Fail safe: + // retain the throttle rather than disabling the only cross-process bound. + now.duration_since(modified) + .map_or(true, |elapsed| elapsed < MODE_RESTART_COOLDOWN) +} + +fn mode_restart_is_throttled(app: &AppHandle) -> Result { + let marker = mode_restart_marker(app)?; let modified = match std::fs::metadata(marker).and_then(|metadata| metadata.modified()) { Ok(modified) => modified, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(error) => return Err(format!("failed to read mesh restart marker: {error}")), }; - Ok(modified - .elapsed() - .is_ok_and(|elapsed| elapsed < MODE_RECOVERY_RESTART_COOLDOWN)) + Ok(restart_marker_is_throttled( + modified, + std::time::SystemTime::now(), + )) } -pub(super) fn mark_mode_recovery_restart(app: &AppHandle) -> Result<(), String> { - let marker = mode_recovery_restart_marker(app)?; +fn mark_mode_restart(app: &AppHandle, reason: &str) -> Result<(), String> { + let marker = mode_restart_marker(app)?; if let Some(parent) = marker.parent() { std::fs::create_dir_all(parent) .map_err(|error| format!("failed to create app data directory: {error}"))?; } - std::fs::write(marker, b"self-only-to-open\n") + std::fs::write(marker, format!("{reason}\n")) .map_err(|error| format!("failed to write mesh restart marker: {error}")) } -pub(super) fn clear_mode_recovery_restart(app: &AppHandle) { - if let Ok(marker) = mode_recovery_restart_marker(app) { +pub(super) fn clear_mode_restart(app: &AppHandle) { + if let Ok(marker) = mode_restart_marker(app) { match std::fs::remove_file(marker) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} @@ -57,6 +68,22 @@ pub(super) enum ModeEvidence { pub(super) struct ModeReconcileState { pending: Option, consecutive_unknown: u8, + restart_requested: bool, +} + +impl ModeReconcileState { + pub(super) fn restart_requested(&self) -> bool { + self.restart_requested + } + + pub(super) fn latch_restart(&mut self) -> bool { + if self.restart_requested { + false + } else { + self.restart_requested = true; + true + } + } } #[derive(Debug, PartialEq, Eq)] @@ -66,6 +93,22 @@ pub(super) enum ModeReconcileAction { RestartProcess, } +pub(super) fn request_mode_restart( + app: &AppHandle, + state: &mut ModeReconcileState, + reason: &str, +) -> Result { + if state.restart_requested || mode_restart_is_throttled(app)? { + return Ok(false); + } + mark_mode_restart(app, reason)?; + if !state.latch_restart() { + return Ok(false); + } + app.request_restart(); + Ok(true) +} + /// Require two consecutive mode observations before restarting the whole app. /// Unknown observations preserve a running policy once, but a second /// consecutive unknown while admission is unenforced restarts fail-closed. @@ -108,6 +151,28 @@ pub(super) fn mode_reconcile_action( mod tests { use super::*; + #[test] + fn restart_latch_only_arms_once() { + let mut state = ModeReconcileState::default(); + assert!(state.latch_restart()); + assert!(state.restart_requested()); + assert!(!state.latch_restart()); + } + + #[test] + fn clock_rollback_keeps_restart_throttled() { + let now = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(100); + let future_marker = now + Duration::from_secs(1); + assert!(restart_marker_is_throttled(future_marker, now)); + } + + #[test] + fn old_restart_marker_is_not_throttled() { + let marker = std::time::SystemTime::UNIX_EPOCH; + let now = marker + MODE_RESTART_COOLDOWN + Duration::from_secs(1); + assert!(!restart_marker_is_throttled(marker, now)); + } + #[test] fn transition_requires_two_matching_observations() { let mut state = ModeReconcileState::default();