diff --git a/crates/updater/src/controller_tests.rs b/crates/updater/src/controller_tests.rs index 63740bc3..2f86c44a 100644 --- a/crates/updater/src/controller_tests.rs +++ b/crates/updater/src/controller_tests.rs @@ -6363,12 +6363,13 @@ fn open_reservation_lock(path: &std::path::Path) -> Result Result<(), ()> { +fn lock_reservations_for(file: &std::fs::File, timeout: Duration) -> Result<(), ()> { use std::os::fd::AsRawFd; + let deadline = Instant::now() + timeout; loop { let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if rc == 0 { @@ -7168,45 +7169,43 @@ fn reservation_directory_rejects_a_symlink() { ); } -#[test] -fn reservation_lock_times_out_while_another_process_holds_it() { - use std::os::fd::AsRawFd; +#[tokio::test] +async fn reservation_lock_times_out_while_another_process_holds_it() { + use std::process::Stdio; + use tokio::io::AsyncReadExt; let dir = std::env::temp_dir().join(format!("port-lock-{:032x}", rand::random::())); let _cleanup = RemoveDir(dir.clone()); std::fs::create_dir_all(&dir).unwrap(); let lock_path = dir.join("lock"); std::fs::File::create(&lock_path).unwrap(); - // One process holds the lock: the shell takes it on fd 9, then `exec`s - // `sleep` with that open file description inherited. `flock sleep` - // would fork a `sleep` grandchild that the kill in `KillChildren::drop` - // never reaches, leaving it holding the lock and the test's pipes. - let holder = KillChildren(vec![ - std::process::Command::new("sh") - .arg("-c") - .arg(r#"exec 9>>"$1" && flock -x 9 && exec sleep 30"#) - .arg("sh") - .arg(&lock_path) - .spawn() - .unwrap(), - ]); - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(&lock_path) + // fd 9 remains locked in the shell until our end of its stdin closes. + let mut holder = tokio::process::Command::new("sh") + .arg("-c") + .arg(r#"exec 9>>"$1" && flock -x 9 && printf L && read -r release"#) + .arg("sh") + .arg(&lock_path) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .kill_on_drop(true) + .spawn() .unwrap(); - let blocked = Instant::now() + Duration::from_secs(5); - loop { - let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; - if rc != 0 { - break; - } - unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) }; - assert!(Instant::now() < blocked, "holder never took the lock"); - std::thread::sleep(Duration::from_millis(10)); - } - let result = lock_reservations_until(&file, Instant::now() + Duration::from_millis(200)); - assert!(result.is_err(), "lock wait should time out"); - drop(holder); + let ready = tokio::time::timeout( + Duration::from_secs(5), + holder.stdout.as_mut().unwrap().read_u8(), + ) + .await + .expect("holder never took the lock") + .unwrap(); + assert_eq!(ready, b'L'); + let file = open_reservation_lock(&lock_path).unwrap(); + assert!(lock_reservations_for(&file, Duration::from_millis(200)).is_err()); + assert!(holder.try_wait().unwrap().is_none()); + drop(holder.stdin.take()); + tokio::time::timeout(Duration::from_secs(5), holder.wait()) + .await + .expect("holder never released the lock") + .unwrap(); + lock_reservations_for(&file, Duration::ZERO).expect("released lock"); } #[test] @@ -7233,8 +7232,12 @@ fn a_dead_owner_is_dropped_and_an_unreadable_owner_is_kept() { assert!(load_reservations(&dir).is_empty()); } -#[tokio::test] +#[tokio::test(start_paused = true)] async fn health_bind_retries_only_while_the_port_is_busy() { + use std::future::{Future, poll_fn}; + use std::task::Poll; + use tokio::time::Instant; + let listener = bind_outside_ephemeral_range().await; let addr = listener.local_addr().unwrap(); let (_cancel, mut cancel_rx) = tokio::sync::oneshot::channel::<()>(); @@ -7249,7 +7252,7 @@ async fn health_bind_retries_only_while_the_port_is_busy() { assert!(missed.is_none()); let elapsed = started.elapsed(); assert!( - elapsed >= Duration::from_millis(50), + elapsed >= Duration::from_millis(80), "retry returned too quickly: {elapsed:?}" ); assert!( @@ -7258,33 +7261,38 @@ async fn health_bind_retries_only_while_the_port_is_busy() { ); let (cancel, mut cancel_rx) = tokio::sync::oneshot::channel::<()>(); - let retry = tokio::spawn(async move { - bind_health_retry( - &addr.to_string(), - "not ready", - Instant::now() + Duration::from_secs(5), - &mut cancel_rx, - ) - .await - }); - tokio::time::sleep(Duration::from_millis(20)).await; + let address = addr.to_string(); + let mut retry = std::pin::pin!(bind_health_retry( + &address, + "not ready", + Instant::now() + Duration::from_secs(5), + &mut cancel_rx, + )); + assert!( + poll_fn(|cx| Poll::Ready(retry.as_mut().poll(cx))) + .await + .is_pending() + ); cancel.send(()).unwrap(); let cancelled = tokio::time::timeout(Duration::from_millis(500), retry) .await - .unwrap() .unwrap(); assert!(cancelled.is_none(), "cancel must not leave a listener"); - drop(listener); let (_cancel, mut cancel_rx) = tokio::sync::oneshot::channel::<()>(); - let serve = bind_health_retry( - &addr.to_string(), + let mut retry = std::pin::pin!(bind_health_retry( + &address, "discord token rejected", Instant::now() + POLL, &mut cancel_rx, - ) - .await - .expect("bind after the port is released"); + )); + assert!( + poll_fn(|cx| Poll::Ready(retry.as_mut().poll(cx))) + .await + .is_pending() + ); + drop(listener); + let serve = retry.await.expect("bind after the port is released"); assert_launcher_health(addr, "discord token rejected").await; serve.abort(); let _ = serve.await; @@ -7366,8 +7374,10 @@ async fn failed_auth_retry_tick_refreshes_ready_reason_before_control_error() { tokio::fs::remove_dir_all(root).await.unwrap(); } -#[tokio::test] +#[tokio::test(start_paused = true)] async fn failed_auth_retry_boot_open_keeps_current_ready_reason() { + let rejected_at = tokio::time::Instant::now().into_std(); + tokio::time::resume(); let root = std::env::temp_dir().join(format!("retry-boot-{:032x}", rand::random::())); tokio::fs::create_dir_all(&root).await.unwrap(); let opts = DbOpenOptions { @@ -7396,7 +7406,7 @@ async fn failed_auth_retry_boot_open_keeps_current_ready_reason() { true, Some(jmodguard::launcher_child::DISCORD_TOKEN_REJECTED_EXIT_CODE), Duration::ZERO, - Instant::now(), + rejected_at, ); // The retry drops this listener and binds the same address. A reserved // port stays outside the ephemeral range across that gap. @@ -7421,11 +7431,11 @@ async fn failed_auth_retry_boot_open_keeps_current_ready_reason() { restart.not_ready_reason(), )); assert_launcher_health(addr, "discord token rejected").await; - restart.auth_retry_at = Some(Instant::now()); + let retry_at = restart.auth_retry_at.unwrap(); let mut health = Some(task); assert!( restart - .retry_auth_with_health(Instant::now(), &mut health, Some(&addr.to_string())) + .retry_auth_with_health(retry_at, &mut health, Some(&addr.to_string())) .await .unwrap() ); @@ -7446,6 +7456,13 @@ async fn failed_auth_retry_boot_open_keeps_current_ready_reason() { tokio::fs::remove_dir_all(root).await.unwrap(); } +fn expire_auth_hold(restart: &mut RestartPolicy) { + assert!(restart.auth_admission == AuthAdmission::Held); + // Make the scheduled retry due at its own observed rejection. + *restart.auth_retry_at.as_mut().expect("scheduled retry") = + restart.auth_rejected_at.expect("recorded rejection"); +} + #[tokio::test] async fn rejected_token_child_is_held_with_liveness_and_no_restart() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -7480,18 +7497,10 @@ async fn rejected_token_child_is_held_with_liveness_and_no_restart() { bot.start(&child, &"b".repeat(40), None).await.unwrap(); let bound = root.join("health-bound-health-bot"); tokio::time::timeout(Duration::from_secs(5), async { - while !bound.exists() { - assert!( - bot.running - .as_mut() - .unwrap() - .child - .try_wait() - .unwrap() - .is_none(), - "child exited before binding the configured health address" - ); - tokio::time::sleep(Duration::from_millis(10)).await; + tokio::select! { + status = bot.running.as_mut().unwrap().child.wait() => + panic!("child exited before binding the configured health address: {status:?}"), + () = wait_for_marker(&bound) => {} } }) .await @@ -7572,7 +7581,7 @@ async fn rejected_token_child_is_held_with_liveness_and_no_restart() { ["discord token rejected; bot held, fix token and restart container"] ); // Advance the policy clock to its deadline instead of waiting 30 minutes. - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); assert!(!bot.tick().await.unwrap()); if let Some(child) = bot.running.as_mut() { child.child.wait().await.unwrap(); @@ -7581,12 +7590,10 @@ async fn rejected_token_child_is_held_with_liveness_and_no_restart() { assert!(bot.restart.auth_admission == AuthAdmission::Held); assert_eq!(bot.restart.auth_failures, 2); assert_launcher_health(addr, "discord token rejected").await; - let next = bot - .restart - .auth_retry_at - .unwrap() - .duration_since(Instant::now()); - assert!(next > Duration::from_secs(3590) && next <= Duration::from_secs(3600)); + assert_eq!( + bot.restart.auth_retry_at.unwrap() - bot.restart.auth_rejected_at.unwrap(), + Duration::from_secs(3600) + ); assert_eq!( *logs.lock().unwrap(), [ @@ -7600,13 +7607,15 @@ async fn rejected_token_child_is_held_with_liveness_and_no_restart() { tokio::fs::remove_file(root.join("exit-code-health-bot")) .await .unwrap(); - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); assert!(!bot.tick().await.unwrap()); - let deadline = Instant::now() + Duration::from_secs(2); - while !bot.report_ready().await.unwrap() { - assert!(Instant::now() < deadline, "retry child never ready"); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(2), async { + let ready = &bot.running.as_ref().unwrap().ready_file; + wait_for_marker(ready).await; + assert!(bot.report_ready().await.unwrap()); + }) + .await + .expect("retry child never ready"); assert!(bot.restart.auth_admission == AuthAdmission::Allowed); assert_eq!(bot.restart.auth_failures, 0); assert!(bot.health.is_none(), "start must release the idle listener"); @@ -7826,12 +7835,10 @@ async fn independent_rejected_token_retries_desired_before_installed_and_doubles assert!(bot.restart.auth_admission == AuthAdmission::Held); assert!(bot.running.is_none()); assert_eq!(bot.restart.auth_failures, 1); - let first = bot - .restart - .auth_retry_at - .unwrap() - .duration_since(Instant::now()); - assert!(first > Duration::from_secs(1790) && first <= Duration::from_secs(1800)); + assert_eq!( + bot.restart.auth_retry_at.unwrap() - bot.restart.auth_rejected_at.unwrap(), + Duration::from_secs(1800) + ); assert_ne!( bot.control .component("bot") @@ -7842,7 +7849,7 @@ async fn independent_rejected_token_retries_desired_before_installed_and_doubles .digest, candidate.digest ); - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); bot.tick().await.unwrap(); // The exit file is already present, so this child can exit before tick // returns. Settlement then holds the token and clears `running`. A quiet @@ -7881,12 +7888,10 @@ async fn independent_rejected_token_retries_desired_before_installed_and_doubles assert!(bot.restart.auth_admission == AuthAdmission::Held); assert!(bot.running.is_none()); assert_eq!(bot.restart.auth_failures, 2); - let second = bot - .restart - .auth_retry_at - .unwrap() - .duration_since(Instant::now()); - assert!(second > Duration::from_secs(3590) && second <= Duration::from_secs(3600)); + assert_eq!( + bot.restart.auth_retry_at.unwrap() - bot.restart.auth_rejected_at.unwrap(), + Duration::from_secs(3600) + ); assert_eq!( bot.control .component("bot") @@ -8074,7 +8079,7 @@ async fn independent_rejected_token_cleared_selection_restores_installed() { .unwrap() .installed .unwrap(); - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); bot.tick().await.unwrap(); assert_eq!( bot.running @@ -8476,9 +8481,8 @@ async fn rejected_token_marker_survives_launcher_restart_during_hold() { ); // The hold clock is process-local. Reopening during the hold is the restart. let mut bot = reopen_supervisor(bot).await; - if bot.restart.auth_admission == AuthAdmission::Held { - bot.restart.auth_retry_at = Some(Instant::now()); - } + assert!(bot.restart.auth_admission == AuthAdmission::Allowed); + assert!(bot.restart.auth_retry_at.is_none()); tokio::fs::remove_file(root.join("exit-code-desired-bot")) .await .unwrap(); @@ -8541,9 +8545,8 @@ async fn cleared_rejected_token_selection_is_not_revived_after_restart() { .installed .unwrap(); let mut bot = reopen_supervisor(bot).await; - if bot.restart.auth_admission == AuthAdmission::Held { - bot.restart.auth_retry_at = Some(Instant::now()); - } + assert!(bot.restart.auth_admission == AuthAdmission::Allowed); + assert!(bot.restart.auth_retry_at.is_none()); bot.tick().await.unwrap(); assert_eq!( bot.running @@ -8695,7 +8698,7 @@ async fn second_token_rejection_after_restart_keeps_candidate() { tokio::fs::remove_file(root.join("exit-code-desired-bot")) .await .unwrap(); - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); bot.tick().await.unwrap(); assert_eq!( bot.running @@ -8822,8 +8825,8 @@ async fn recovered_candidate_readiness_timeout_rolls_back() { ); let elapsed = READY_TIMEOUT + Duration::from_secs(1); let child = bot.running.as_mut().unwrap(); - child.started_at = now() - elapsed.as_secs() as i64; - child.started = Instant::now() - elapsed; + child.started_at -= elapsed.as_secs() as i64; + child.started -= elapsed; bot.tick().await.unwrap(); assert_eq!( bot.running @@ -9049,15 +9052,16 @@ async fn selection_change_away_and_back_does_not_revive_rejected_candidate() { .unwrap() .is_none() ); - let deadline = Instant::now() + Duration::from_secs(5); - let starts = loop { - let starts = independent_exit_starts(&root).await; - if starts.len() >= 2 || Instant::now() >= deadline { - break starts; - } - tokio::time::sleep(Duration::from_millis(10)).await; - }; - assert_eq!(starts, ["desired-bot.start", "installed-bot.start"]); + tokio::time::timeout( + Duration::from_secs(5), + wait_for_publication(&root, || child_start_count(&root, "installed-bot") > 0), + ) + .await + .expect("installed child did not record its start"); + assert_eq!( + independent_exit_starts(&root).await, + ["desired-bot.start", "installed-bot.start"] + ); bot.stop_application().await.unwrap(); bot.end_idle().await.unwrap(); server.abort(); @@ -9188,7 +9192,7 @@ async fn rejected_marker_tracks_the_candidate_digest() { tokio::fs::write(root.join("hold-desired-bot-ready"), "") .await .unwrap(); - bot.restart.auth_retry_at = Some(Instant::now()); + expire_auth_hold(&mut bot.restart); bot.tick().await.unwrap(); assert_eq!( bot.running @@ -9308,8 +9312,8 @@ async fn selected_auth_rejection_survives_legacy_readiness_deadline() { let elapsed = READY_TIMEOUT + Duration::from_secs(1); if let Some(child) = bot.running.as_mut() { // Advance both child ages beyond the historical 120s deadline. - child.started_at = now() - elapsed.as_secs() as i64; - child.started = Instant::now() - elapsed; + child.started_at -= elapsed.as_secs() as i64; + child.started -= elapsed; } else { assert!( bot.restart.auth_admission == AuthAdmission::Held, @@ -10101,6 +10105,9 @@ async fn cold_start_refuses_truncated_registry_body() { tokio::io::AsyncReadExt::read(&mut stream, &mut request) .await .unwrap(); + // The request is established. On this current-thread runtime the + // virtual timer advances when the partial response stops making progress. + tokio::time::pause(); tokio::io::AsyncWriteExt::write_all( &mut stream, b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{", @@ -10109,6 +10116,7 @@ async fn cold_start_refuses_truncated_registry_body() { .unwrap(); // Let restore reach the response body before closing the connection. tokio::time::sleep(Duration::from_millis(100)).await; + tokio::time::resume(); if reset { stream.set_zero_linger().unwrap(); } @@ -11050,6 +11058,8 @@ async fn older_writer_boot_receipt_does_not_block_api_startup() { )); wait_for_ready_file(&service).await; + let receipt_time = service.running.as_ref().unwrap().started; + service.boot_receipts.fixed_now = Some(receipt_time); // Exercise the production ordering: retry diagnostics before readiness. // Make each poll retry-eligible without waiting for the backoff in real time. for _ in 0..3 { @@ -11089,8 +11099,7 @@ async fn older_writer_boot_receipt_does_not_block_api_startup() { wait_for_ready_file(&service).await; // Recovery must not inherit the maximum delay of an unsaved Record. service.boot_receipts.attempt = 6; - service.boot_receipts.schedule = - ReceiptSchedule::After(Instant::now() + Duration::from_secs(60)); + service.boot_receipts.defer(); // Managed readiness must proceed while the outage record is still deferred. let ready = service.tick_control().await; assert!( @@ -11115,8 +11124,29 @@ async fn older_writer_boot_receipt_does_not_block_api_startup() { )); assert!(service.readiness_receipt == ReadinessReceipt::Recorded); - assert!( - matches!(service.boot_receipts.schedule, ReceiptSchedule::After(at) if at <= Instant::now() + Duration::from_secs(1)) + let ReceiptSchedule::After(at) = service.boot_receipts.schedule else { + panic!("the unsupported Clear must remain scheduled"); + }; + assert_eq!(service.boot_receipts.attempt, 1); + assert_eq!(at, receipt_time + Duration::from_secs(1)); + let before = peer + .diagnostic_requests + .load(std::sync::atomic::Ordering::Relaxed); + service.boot_receipts.fixed_now = Some(at - Duration::from_nanos(1)); + service.tick_control().await.unwrap(); + assert_eq!( + peer.diagnostic_requests + .load(std::sync::atomic::Ordering::Relaxed), + before, + "the scheduled Clear must stay deferred before its deadline" + ); + service.boot_receipts.fixed_now = Some(at); + service.tick_control().await.unwrap(); + assert_eq!( + peer.diagnostic_requests + .load(std::sync::atomic::Ordering::Relaxed), + before + 1, + "the ready child must retry exactly one scheduled Clear at its deadline" ); // A later managed child must also report readiness when Clear is retried first. service.stop_application().await.unwrap(); diff --git a/crates/updater/src/main.rs b/crates/updater/src/main.rs index a4dfc02b..5cdf3a39 100644 --- a/crates/updater/src/main.rs +++ b/crates/updater/src/main.rs @@ -107,6 +107,9 @@ struct RestartPolicy { not_before: Option, auth_failures: u32, auth_retry_at: Option, + // Integration tests compare the scheduled hold with the actual exit observation. + #[cfg(test)] + auth_rejected_at: Option, } impl RestartPolicy { @@ -126,6 +129,10 @@ impl RestartPolicy { .saturating_mul(1_u32 << self.auth_failures.min(4)) .min(Duration::from_secs(6 * 3600)); self.auth_failures = self.auth_failures.saturating_add(1); + #[cfg(test)] + { + self.auth_rejected_at = Some(now); + } self.auth_retry_at = Some(now + delay); return; } @@ -239,19 +246,30 @@ enum ReceiptSchedule { struct ReceiptBackoff { attempt: u32, schedule: ReceiptSchedule, + #[cfg(test)] + fixed_now: Option, } impl ReceiptBackoff { + fn now(&self) -> Instant { + #[cfg(test)] + if let Some(now) = self.fixed_now { + return now; + } + Instant::now() + } + fn defer(&mut self) { let delay = Duration::from_secs(1_u64 << self.attempt.min(6)).min(Duration::from_secs(60)); self.attempt = self.attempt.saturating_add(1); - self.schedule = ReceiptSchedule::After(Instant::now() + delay); + self.schedule = ReceiptSchedule::After(self.now() + delay); } fn reset(&mut self) { - *self = Self::default(); + self.attempt = 0; + self.schedule = ReceiptSchedule::Ready; } fn waiting(&self) -> bool { - matches!(self.schedule, ReceiptSchedule::After(at) if Instant::now() < at) + matches!(self.schedule, ReceiptSchedule::After(at) if self.now() < at) } } @@ -577,7 +595,7 @@ fn addr_in_use(error: &anyhow::Error) -> bool { async fn bind_health_retry( addr: &str, reason: &'static str, - deadline: Instant, + deadline: tokio::time::Instant, cancel: &mut tokio::sync::oneshot::Receiver<()>, ) -> Option>> { let mut delay = Duration::from_millis(10); @@ -588,8 +606,9 @@ async fn bind_health_retry( jmodguard::health::serve_listener_as_with_reason(listener, "launcher", reason), )); } - Err(error) if addr_in_use(&error) && Instant::now() < deadline => { - let pause = delay.min(deadline.saturating_duration_since(Instant::now())); + Err(error) if addr_in_use(&error) && tokio::time::Instant::now() < deadline => { + let pause = + delay.min(deadline.saturating_duration_since(tokio::time::Instant::now())); if pause.is_zero() { tracing::warn!("launcher health bind stayed busy: {error:#}"); return None; @@ -673,7 +692,7 @@ async fn watch_child_health_from( if let Some(serve) = bind_health_retry( &bind, readiness_for_exit(code), - Instant::now() + POLL, + tokio::time::Instant::now() + POLL, &mut cancel, ) .await