From a397132223819253aab16a4d5c731dd6e340cfb1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 23 Sep 2026 17:38:31 +0200 Subject: [PATCH] Tolerate Idunn's activation-publication gap in the daemon's own Warming path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Soul's diagnosis: Idunn publishes Expected and starts the unit before it observes the running process on a later tick and publishes the activation (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses every Warming presence this daemon publishes ("no exact current activation and provider anchor"), and the daemon's single initial publish_warming() call, and every heartbeat inside wait_for_write_lease, propagated that refusal through `?` and killed the process. Muninn tolerates the same gap by re-publishing every 2s and only logging failures (Muninn/crates/muninn-daemon/src/main.rs); this cut matches that posture in Ghostlight, touching only the daemon. 1. initialize_production_admission now retries the initial publish_warming() at a 2s cadence (matching Muninn), bounded by the same 120s window wait_for_write_lease already used — pulled into one named constant, WRITE_LEASE_WAIT_TIMEOUT, reused by both rather than inventing a second value. Each retried publish is a genuinely new message, not a duplicate Odin would drop: signed_record increments publisher_sequence and refreshes observed_at_unix_millis on every call (verified by reading it, not assumed). Every failed attempt is logged at warn with its error; the loop exits only when the window expires, and returns the accepted presence so it carries forward into wait_for_write_lease's recent_warming_proofs exactly as the single call used to. The retry policy is retry_until_deadline, generic over the attempt closure and a sleep/clock seam (no trait hierarchy on the publisher) so it's unit-testable without waiting real time out: production passes tokio::time::sleep and Instant::now, a test passes a no-op sleep paired with a fake clock that only advances when the sleep seam is called. 2. wait_for_write_lease's own heartbeat publish no longer propagates a failure through `?`; it logs a warning and keeps waiting, exactly like the initial-publish retry, until the wait's own outer deadline. 3. Tests (crates/ghostlight-dungeon/src/runtime.rs, idunn_health.rs): - retry_until_deadline_returns_the_first_accepted_value: refused twice then accepted succeeds and returns the accepted value, via a fake clock — runs in 0.00s, no real waiting. - retry_until_deadline_fails_with_the_last_error_after_the_window: always-refused fails once the fake clock crosses the deadline, carrying the last attempt's own error. - a_failed_heartbeat_does_not_abort_the_wait_for_lease: a real fixture publisher pointed at a closed port (127.0.0.1:9, the existing fixture convention) so every publish fails fast; proves the wait survives past one heartbeat interval and only ends at its own outer timeout, not the heartbeat's own error. This one uses real timing (~6s) since wait_for_write_lease's internal loop has no clock seam and adding one was out of scope for this cut; verified by mutation that it would have caught the old bug (see below). Mutations, all verified and reverted (diff-clean after): - retry_until_deadline: made the first failure unconditionally fatal (`if true || now() >= deadline`) -> both new retry tests fail, the first on attempt 1 instead of retrying to attempt 3. Restored. - wait_for_write_lease's heartbeat: restored the old `?`-propagating form -> a_failed_heartbeat_does_not_abort_the_wait_for_lease fails in ~5.6s with "publishing Warming heartbeat ... timed out connecting" (the pre-fix symptom), instead of running to the 6s outer deadline. Restored. Decisions made without a further ruling: - Named the shared timeout constant WRITE_LEASE_WAIT_TIMEOUT (both the initial-publish retry and wait_for_write_lease's own timeout parameter use it) rather than threading one Duration value through both call sites by hand. - Put retry_until_deadline in runtime.rs, beside initialize_production_admission, its only caller — not in idunn_health.rs, which owns the publisher/protocol, not retry policy. - The heartbeat-tolerance test uses real timing rather than adding a clock seam to wait_for_write_lease's own internal loop; that loop's shape (poll write-lease file + sleep 100ms + heartbeat check) is unrelated to this fix and reworking it for a seam felt like scope creep against the operator's instruction to avoid a trait hierarchy. cargo test -p ghostlight-dungeon --bin ghostlight-dungeon: 190 passed, 0 failed, 4 ignored (was 186 before this pass; +3 new tests here, +1 from Self's own commits since the last pass). Co-Authored-By: Claude Sonnet 5 --- crates/ghostlight-dungeon/src/idunn_health.rs | 54 ++++++- crates/ghostlight-dungeon/src/runtime.rs | 148 +++++++++++++++++- 2 files changed, 193 insertions(+), 9 deletions(-) diff --git a/crates/ghostlight-dungeon/src/idunn_health.rs b/crates/ghostlight-dungeon/src/idunn_health.rs index 4682f03..479b909 100644 --- a/crates/ghostlight-dungeon/src/idunn_health.rs +++ b/crates/ghostlight-dungeon/src/idunn_health.rs @@ -289,10 +289,24 @@ impl RuntimePresencePublisher { ); } if now >= next_heartbeat { - let heartbeat = self - .publish_warming() - .context("publishing Warming heartbeat while awaiting process lease")?; - remember_warming_proof(&mut recent_warming_proofs, heartbeat.canonical_sha256); + // A failed heartbeat is a warning, not a reason to abort the + // wait: Odin can refuse Warming for a while after Idunn + // starts the unit and before it publishes the activation + // (Idunn/src/control_plane.rs), the same gap the initial + // publish in `initialize_production_admission` retries + // through. The lease wait keeps polling either way; only the + // outer `deadline` above ends it. + match self.publish_warming() { + Ok(heartbeat) => { + remember_warming_proof(&mut recent_warming_proofs, heartbeat.canonical_sha256); + } + Err(error) => { + tracing::warn!( + %error, + "Warming heartbeat publish failed while awaiting process lease; still waiting" + ); + } + } next_heartbeat = now + WARMING_HEARTBEAT_INTERVAL; } tokio::time::sleep(Duration::from_millis(100)).await; @@ -1809,6 +1823,38 @@ pub(crate) mod tests { ); } + /// A failed heartbeat publish does not abort `wait_for_write_lease`. The + /// fixture publisher's endpoint (`127.0.0.1:9`) is closed, so every + /// publish — including the heartbeat this loop fires after + /// `WARMING_HEARTBEAT_INTERVAL` — fails fast. Before the fix that + /// failure propagated through `?` and the wait ended within about one + /// heartbeat interval with a "publishing Warming heartbeat" error. After + /// the fix it logs and keeps waiting for the write-lease file (which + /// this test never creates), so the wait instead runs to its own outer + /// timeout and fails with "timed out waiting for process write lease". + #[tokio::test] + async fn a_failed_heartbeat_does_not_abort_the_wait_for_lease() -> Result<()> { + let root = tempfile::tempdir()?; + let mut fixture = fixture(root.path())?; + let warming = PublishedRuntimePresence { + canonical_sha256: digest('w'), + }; + let outer_timeout = WARMING_HEARTBEAT_INTERVAL + Duration::from_secs(1); + let error = match fixture + .publisher + .wait_for_write_lease(&warming, outer_timeout) + .await + { + Ok(_) => panic!("wait_for_write_lease unexpectedly acquired a lease"), + Err(error) => error, + }; + assert!( + format!("{error:#}").contains("timed out waiting for process write lease"), + "wait ended with `{error:#}`, not the outer timeout — a heartbeat failure aborted it early" + ); + Ok(()) + } + /// Pure over (uid, gid, mode), so it runs on this Windows workstation too /// rather than sitting unexercised behind `#[cfg(target_os = "linux")]` /// the way `require_runtime_bundle`'s real-filesystem check has always diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index de94ef5..136b3c6 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -47,7 +47,7 @@ use std::{ net::SocketAddr, path::PathBuf, sync::Arc, - time::Duration, + time::{Duration, Instant}, }; use tokio::sync::{Mutex, Semaphore, broadcast, mpsc}; use tower_http::services::ServeDir; @@ -1916,17 +1916,73 @@ async fn maintain_session_refresh(state: AppState) -> anyhow::Result<()> { } } +/// Idunn publishes Expected and starts the unit before it observes the +/// running process on a later tick and publishes the activation +/// (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses +/// every Warming presence this daemon publishes ("no exact current +/// activation and provider anchor"). This is the bound both the initial +/// Warming publish retries against and `wait_for_write_lease`'s own timeout +/// — one constant, reused, not two. +const WRITE_LEASE_WAIT_TIMEOUT: Duration = Duration::from_secs(120); + +/// Muninn re-publishes its own Warming presence every 2s while tolerating +/// this same activation-publication gap (Muninn/crates/muninn-daemon/src/main.rs); +/// the initial-publish retry below matches that cadence. +const INITIAL_WARMING_RETRY_CADENCE: Duration = Duration::from_secs(2); + +/// Retries `attempt` at `cadence` until it returns `Ok` or `deadline` passes, +/// warning on every failed attempt and returning the last error once the +/// deadline is reached. `sleep` is a seam: production passes +/// `tokio::time::sleep`; a test can pass a no-op paired with a fake `now` so +/// the bounded-retry policy is provable without waiting the real window out. +async fn retry_until_deadline( + mut attempt: Attempt, + cadence: Duration, + deadline: Instant, + what: &str, + mut now: impl FnMut() -> Instant, + mut sleep: Sleep, +) -> anyhow::Result +where + Attempt: FnMut() -> anyhow::Result, + Sleep: FnMut(Duration) -> SleepFut, + SleepFut: std::future::Future, +{ + loop { + match attempt() { + Ok(value) => return Ok(value), + Err(error) => { + tracing::warn!(%error, "{what} failed; retrying"); + if now() >= deadline { + return Err(error).context(format!("{what} timed out")); + } + sleep(cadence).await; + } + } + } +} + async fn initialize_production_admission( bound_endpoint: SocketAddr, ) -> anyhow::Result> { let Some(mut publisher) = RuntimePresencePublisher::from_environment(bound_endpoint)? else { return Ok(None); }; - let warming = publisher - .publish_warming() - .context("publishing initial Warming runtime presence")?; + // Each `publish_warming()` call mints a fresh publisher_sequence and + // observed_at_unix_millis (idunn_health.rs's `signed_record`), so a + // retried publish is a new message Odin evaluates, never a duplicate it + // drops. + let warming = retry_until_deadline( + || publisher.publish_warming(), + INITIAL_WARMING_RETRY_CADENCE, + Instant::now() + WRITE_LEASE_WAIT_TIMEOUT, + "publishing initial Warming runtime presence", + Instant::now, + |duration| tokio::time::sleep(duration), + ) + .await?; let write_lease = publisher - .wait_for_write_lease(&warming, Duration::from_secs(120)) + .wait_for_write_lease(&warming, WRITE_LEASE_WAIT_TIMEOUT) .await .with_context(|| { format!( @@ -2147,6 +2203,88 @@ mod tests { use ghostlight::{InferenceFault, InferencePurpose}; use tower::ServiceExt; + /// A fake clock so the retry-until-deadline policy is provable without + /// waiting the real window out: `now()` only advances when the test's + /// `sleep` seam is called, exactly as it would in production (time + /// passes because we waited the cadence), but instantly here. + struct FakeClock { + now: std::cell::Cell, + } + + impl FakeClock { + fn new() -> Self { + Self { + now: std::cell::Cell::new(Instant::now()), + } + } + fn now(&self) -> Instant { + self.now.get() + } + fn advance(&self, by: Duration) { + self.now.set(self.now.get() + by); + } + } + + /// S2 (a): refused, then refused, then accepted — the loop must retry + /// past the refusals and return the value the successful attempt + /// produced, not an error. + #[tokio::test] + async fn retry_until_deadline_returns_the_first_accepted_value() { + let clock = FakeClock::new(); + let deadline = clock.now() + Duration::from_secs(120); + let mut calls = 0; + let result = retry_until_deadline( + || { + calls += 1; + if calls < 3 { + Err(anyhow::anyhow!("refused (attempt {calls})")) + } else { + Ok(format!("accepted on attempt {calls}")) + } + }, + Duration::from_secs(2), + deadline, + "test publish", + || clock.now(), + |cadence| { + clock.advance(cadence); + std::future::ready(()) + }, + ) + .await; + assert_eq!(result.unwrap(), "accepted on attempt 3"); + assert_eq!(calls, 3); + } + + /// S2 (b): always refused fails once the fake clock crosses the + /// deadline, carrying the last attempt's own error. + #[tokio::test] + async fn retry_until_deadline_fails_with_the_last_error_after_the_window() { + let clock = FakeClock::new(); + let deadline = clock.now() + Duration::from_secs(10); + let mut calls = 0; + let result: anyhow::Result<()> = retry_until_deadline( + || { + calls += 1; + Err(anyhow::anyhow!("refused (attempt {calls})")) + }, + Duration::from_secs(2), + deadline, + "test publish", + || clock.now(), + |cadence| { + clock.advance(cadence); + std::future::ready(()) + }, + ) + .await; + let error = result.unwrap_err(); + assert!(format!("{error:#}").contains("test publish timed out")); + assert!(format!("{error:#}").contains("refused (attempt")); + // Five 2s cadences cross a 10s deadline (0, 2, 4, 6, 8, 10 -> stop). + assert_eq!(calls, 6); + } + #[cfg(target_os = "linux")] #[test] fn managed_linux_runtime_requires_the_admitted_state_root_binding() {