diff --git a/crates/updater/src/controller_tests.rs b/crates/updater/src/controller_tests.rs index 1304c14d..63740bc3 100644 --- a/crates/updater/src/controller_tests.rs +++ b/crates/updater/src/controller_tests.rs @@ -161,13 +161,17 @@ fn main() { let maintenance = std::env::var("JMODGUARD_UPDATE_MAINTENANCE").as_deref() == Ok("1"); let event = |suffix: &str| { let mut log = std::fs::OpenOptions::new().create(true).append(true).open(root.join("events")).unwrap(); - writeln!(log, "{name}.{suffix}").unwrap(); + log.write_all(format!("{name}.{suffix}\n").as_bytes()).unwrap(); }; // Optional real maintenance socket for outage liveness regressions. let maintenance_listener = if maintenance && root.join(format!("bind-maintenance-{name}")).exists() { let bind = std::fs::read_to_string(root.join(format!("bind-maintenance-{name}"))).unwrap(); let listener = std::net::TcpListener::bind(bind.trim()).unwrap(); listener.set_nonblocking(true).unwrap(); + let ready = std::path::PathBuf::from(std::env::var("JMODGUARD_READY_FILE").unwrap()); + let pending = ready.with_extension("tmp"); + std::fs::write(&pending, listener.local_addr().unwrap().to_string()).unwrap(); + std::fs::rename(pending, ready).unwrap(); Some(listener) } else { None }; if !maintenance { @@ -214,8 +218,9 @@ fn main() { } while root.join(format!("hold-{name}-ready")).exists() && !STOP.load(Ordering::SeqCst) { std::thread::sleep(std::time::Duration::from_millis(5)); } if STOP.load(Ordering::SeqCst) { event("stop"); return; } - std::fs::write(std::env::var("JMODGUARD_READY_FILE").unwrap(), "ready").unwrap(); + // The supervisor may start the dependent child as soon as the marker exists. event("ready"); + std::fs::write(std::env::var("JMODGUARD_READY_FILE").unwrap(), "ready").unwrap(); } while !STOP.load(Ordering::SeqCst) { if let Some(listener) = &maintenance_listener @@ -387,6 +392,31 @@ async fn restart(service: &mut Supervisor) { service.restart_target = None; } +async fn tick_after_ready(service: &mut Supervisor) { + wait_for_ready_file(service).await; + assert!(!service.tick().await.unwrap()); +} + +async fn advanced_upgrade( + control: &UpdateControl, + previous: &db::ServiceUpgrade, +) -> db::ServiceUpgrade { + let next = control.upgrade().await.unwrap().unwrap(); + assert_ne!( + serde_json::to_value(previous).unwrap(), + serde_json::to_value(&next).unwrap(), + "paired ticks made no progress" + ); + next +} + +async fn tick_pair_member(service: &mut Supervisor) { + if service.running.is_some() && service.readiness_receipt == ReadinessReceipt::Pending { + wait_for_ready_file(service).await; + } + assert!(!service.tick().await.unwrap()); +} + #[tokio::test] async fn paired_processes_restore_across_every_phase_and_recover_forward_after_failure() { let root = @@ -496,15 +526,14 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f .is_none() ); tokio::fs::remove_file(delayed_baked).await.unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while bot.readiness_receipt == ReadinessReceipt::Pending - || api.readiness_receipt == ReadinessReceipt::Pending - { - assert!(Instant::now() < deadline); - bot.tick().await.unwrap(); - api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(15)).await; - } + tokio::time::timeout(Duration::from_secs(5), async { + tick_after_ready(&mut bot).await; + tick_after_ready(&mut api).await; + assert_eq!(bot.readiness_receipt, ReadinessReceipt::Recorded); + assert_eq!(api.readiness_receipt, ReadinessReceipt::Recorded); + }) + .await + .expect("baked startup receipts"); for role in ["bot", "api"] { let restored = control.component(role).await.unwrap(); @@ -594,18 +623,17 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f let result = api.tick().await; (api, result) }); - let deadline = Instant::now() + Duration::from_secs(5); - loop { - if tokio::fs::read_to_string(root.join("events")) - .await - .unwrap() - .contains("old-api.stopping") - { - break; - } - assert!(Instant::now() < deadline); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout( + Duration::from_secs(5), + wait_for_publication(&root, || { + std::fs::read_to_string(root.join("events")) + .unwrap() + .lines() + .any(|line| line == "old-api.stopping") + }), + ) + .await + .expect("API entered its graceful stop"); restart(&mut bot).await; control .join_upgrade(&operation.id, "bot", &bot.instance) @@ -616,40 +644,39 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f stopped.unwrap(); assert!(control.upgrade().await.unwrap().unwrap().error.is_none()); let mut restarted = HashSet::new(); - let deadline = Instant::now() + Duration::from_secs(30); - loop { - let op = control.upgrade().await.unwrap().unwrap(); - assert!(Instant::now() < deadline, "stalled operation: {op:?}"); - if op.phase == Phase::Complete { - break; - } - let phase = format!("{:?}", op.phase); - if restarted.insert(phase) { - restart(&mut bot).await; - restart(&mut api).await; - bot.control = UpdateControl::open(&opts).unwrap().unwrap(); - api.control = UpdateControl::open(&opts).unwrap().unwrap(); - } - bot.tick().await.unwrap(); - if control.schema_version().await.unwrap() == db::CORE_SCHEMA_VERSION - && bot - .running - .as_ref() - .is_some_and(|child| child.release.is_some()) - { - // Future application migration is deliberately simulated, using a - // real primary SQLite write after actual API stop/reap and bot spawn. - assert!(api.running.is_none()); - db.with_conn(|conn| { - conn.pragma_update(None, "user_version", db::CORE_SCHEMA_VERSION + 1)?; - Ok(()) - }) - .await - .unwrap(); + tokio::time::timeout(Duration::from_secs(30), async { + let mut op = control.upgrade().await.unwrap().unwrap(); + while op.phase != Phase::Complete { + let phase = format!("{:?}", op.phase); + if restarted.insert(phase) { + restart(&mut bot).await; + restart(&mut api).await; + bot.control = UpdateControl::open(&opts).unwrap().unwrap(); + api.control = UpdateControl::open(&opts).unwrap().unwrap(); + } + tick_pair_member(&mut bot).await; + if control.schema_version().await.unwrap() == db::CORE_SCHEMA_VERSION + && bot + .running + .as_ref() + .is_some_and(|child| child.release.is_some()) + { + // Future application migration is deliberately simulated, using a + // real primary SQLite write after actual API stop/reap and bot spawn. + assert!(api.running.is_none()); + db.with_conn(|conn| { + conn.pragma_update(None, "user_version", db::CORE_SCHEMA_VERSION + 1)?; + Ok(()) + }) + .await + .unwrap(); + } + tick_pair_member(&mut api).await; + op = advanced_upgrade(&control, &op).await; } - api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(15)).await; - } + }) + .await + .expect("stalled paired upgrade after launcher restart"); assert_eq!(restarted.len(), 5); assert!(Db::open_with(opts.clone()).is_err()); assert_eq!( @@ -714,9 +741,19 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f restart(&mut api).await; bot.tick().await.unwrap(); api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(50)).await; bot.tick().await.unwrap(); api.tick().await.unwrap(); + let refused = control.upgrade().await.unwrap().unwrap(); + assert!( + refused + .error + .as_deref() + .unwrap() + .contains("installed application cannot open database") + ); + assert_eq!(refused.bot.stopped, db::UpgradeProof::Confirmed); + assert_eq!(refused.api.stopped, db::UpgradeProof::Confirmed); + assert!(bot.running.is_none() && api.running.is_none()); let events = tokio::fs::read_to_string(root.join("events")) .await .unwrap(); @@ -724,38 +761,9 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f events.matches("old-api.start").count() + events.matches("old-bot.start").count(), old_starts ); - // A permanent new API startup failure after migration must leave recovery - // alive and require both real children stopped before owner retry. - for failure in ["fail-new-api", "hold-new-api-ready"] { - tokio::fs::write(root.join(failure), "fail").await.unwrap(); - restart(&mut api).await; - api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(50)).await; - if failure == "hold-new-api-ready" { - api.running.as_mut().unwrap().started_at = now() - READY_TIMEOUT.as_secs() as i64 - 1; - } - api.tick().await.unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let failed = loop { - bot.tick().await.unwrap(); - api.tick().await.unwrap(); - let failed = control.upgrade().await.unwrap().unwrap(); - assert!( - Instant::now() < deadline, - "failed operation did not quiesce: {failed:?}" - ); - if failed.error.is_some() - && failed.irreversible - && failed.bot.stopped == db::UpgradeProof::Confirmed - && failed.api.stopped == db::UpgradeProof::Confirmed - { - break failed; - } - tokio::time::sleep(Duration::from_millis(15)).await; - }; - assert!(api.maintenance.is_some()); - assert!(control.abort_upgrade(&failed.id).await.is_err()); - tokio::fs::remove_file(root.join(failure)).await.unwrap(); + // The refused cold restore already failed this operation. Recover that + // error before injecting either API failure into a running selection. + let recover = async |bot: &mut Supervisor, api: &mut Supervisor| { let stamp = now(); for release in [&bot_release, &api_release] { control @@ -769,17 +777,68 @@ async fn paired_processes_restore_across_every_phase_and_recover_forward_after_f .await .unwrap(); } - control + let mut op = control .request_upgrade(&bot_release.digest, &api_release.digest, true, now()) .await .unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - while control.upgrade().await.unwrap().unwrap().phase != Phase::Complete { - assert!(Instant::now() < deadline); + tokio::time::timeout(Duration::from_secs(10), async { + while op.phase != Phase::Complete { + tick_pair_member(bot).await; + tick_pair_member(api).await; + op = advanced_upgrade(&control, &op).await; + } + }) + .await + .expect("forward recovery did not complete"); + }; + recover(&mut bot, &mut api).await; + // A permanent new API startup failure after migration must leave recovery + // alive and require both real children stopped before owner retry. + for failure in ["fail-new-api", "hold-new-api-ready"] { + tokio::fs::write(root.join(failure), "fail").await.unwrap(); + restart(&mut api).await; + let starts = child_start_count(&root, "new-api"); + api.tick().await.unwrap(); + let failed = tokio::time::timeout(Duration::from_secs(10), async { + if failure == "hold-new-api-ready" { + wait_for_publication(&root, || child_start_count(&root, "new-api") > starts).await; + api.running.as_mut().unwrap().started_at = + now() - READY_TIMEOUT.as_secs() as i64 - 1; + } else if let Some(child) = &mut api.running { + assert_eq!(child.child.wait().await.unwrap().code(), Some(7)); + } + api.tick().await.unwrap(); + if failure == "fail-new-api" { + *api.restart + .not_before + .as_mut() + .expect("child crash backoff") -= POLL; + } + // Both cold launchers rejoin. The second join invalidates the + // first launcher's stop proof, which its next tick must restore. bot.tick().await.unwrap(); api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(15)).await; - } + bot.tick().await.unwrap(); + control.upgrade().await.unwrap().unwrap() + }) + .await + .expect("failed operation did not quiesce"); + let cause = if failure == "fail-new-api" { + "application exited: exit status: 7" + } else { + "replacement child readiness timed out" + }; + assert!( + failed.error.as_deref().unwrap().contains(cause), + "{failed:?}" + ); + assert!(failed.irreversible); + assert_eq!(failed.bot.stopped, db::UpgradeProof::Confirmed); + assert_eq!(failed.api.stopped, db::UpgradeProof::Confirmed); + assert!(api.maintenance.is_some()); + assert!(control.abort_upgrade(&failed.id).await.is_err()); + tokio::fs::remove_file(root.join(failure)).await.unwrap(); + recover(&mut bot, &mut api).await; } assert_ne!(control.upgrade().await.unwrap().unwrap().id, operation.id); restart(&mut bot).await; @@ -820,12 +879,13 @@ async fn independent_update_requires_launcher_before_spawn_and_retains_app_on_do let db = Db::open(&root.join("core.db"), 2).unwrap(); let control = UpdateControl::from_application(&db); let mut bot = controller("bot", baked, registry.clone(), control.clone(), &root); - let deadline = Instant::now() + Duration::from_secs(5); - while bot.readiness_receipt == ReadinessReceipt::Pending { - assert!(Instant::now() < deadline); - bot.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(5), async { + assert!(!bot.tick().await.unwrap()); + tick_after_ready(&mut bot).await; + assert_eq!(bot.readiness_receipt, ReadinessReceipt::Recorded); + }) + .await + .expect("baked bot startup"); let seen = control.component("bot").await.unwrap().observed.unwrap(); control.running("api", None, seen, now()).await.unwrap(); control @@ -946,12 +1006,27 @@ async fn independent_update_requires_launcher_before_spawn_and_retains_app_on_do .unwrap(); bot.launcher_revision = db::LAUNCHER_REVISION; // re-exec simulated; ELF children are real restart(&mut bot).await; - let deadline = Instant::now() + Duration::from_secs(5); - while control.component("bot").await.unwrap().installed.is_none() { - assert!(Instant::now() < deadline); + tokio::time::timeout(Duration::from_secs(5), async { assert!(!bot.tick().await.unwrap()); - tokio::time::sleep(Duration::from_millis(10)).await; - } + // If the baked child was already ready on the restore tick, that tick + // also staged the candidate. Otherwise publish its receipt first. + if bot.running.as_ref().unwrap().release.is_none() { + tick_after_ready(&mut bot).await; + } + tick_after_ready(&mut bot).await; + assert_eq!( + control + .component("bot") + .await + .unwrap() + .installed + .unwrap() + .digest, + release.digest + ); + }) + .await + .expect("managed application did not activate"); // A newer baked controller can already satisfy an earlier queued launcher // request. Settle that request without claiming the requested bytes ran. let state = control.component("bot").await.unwrap(); @@ -1028,50 +1103,43 @@ async fn independent_spawn_failure_settles_once() { let control = UpdateControl::from_application(&db); let mut bot = controller("bot", old_bot, registry.clone(), control.clone(), &root); let mut api = controller("api", old_api, registry, control.clone(), &root); - let deadline = Instant::now() + Duration::from_secs(10); - while bot.readiness_receipt == ReadinessReceipt::Pending - || api.readiness_receipt == ReadinessReceipt::Pending - { - assert!(Instant::now() < deadline); - bot.tick().await.unwrap(); - api.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(10)).await; - } - api.running.as_mut().unwrap().started_at = now() - 100; - control - .running( - "api", - None, - deployment_observation( - api.running.as_ref().unwrap(), - &api.base_sha, - &api.base_abi, - api.enabled, - &api.baked_compatibility, - ), - now(), - ) - .await - .unwrap(); - control - .checked("api", "latest", Some(candidate.clone()), None, now()) - .await - .unwrap(); - db::request_component_install(&db, "api", &candidate.digest, now()) - .await - .unwrap(); - // Spawn errors are tolerated so the durable-settlement oracle can run. - let _ = api.tick().await; - while api.readiness_receipt == ReadinessReceipt::Pending - || control.component("api").await.unwrap().desired.is_some() - { - assert!( - Instant::now() < deadline, - "failed request kept retrying instead of settling" - ); - let _ = api.tick().await; - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(10), async { + assert!(!bot.tick().await.unwrap()); + assert!(!api.tick().await.unwrap()); + tick_after_ready(&mut bot).await; + tick_after_ready(&mut api).await; + assert_eq!(bot.readiness_receipt, ReadinessReceipt::Recorded); + assert_eq!(api.readiness_receipt, ReadinessReceipt::Recorded); + api.running.as_mut().unwrap().started_at = now() - 100; + control + .running( + "api", + None, + deployment_observation( + api.running.as_ref().unwrap(), + &api.base_sha, + &api.base_abi, + api.enabled, + &api.baked_compatibility, + ), + now(), + ) + .await + .unwrap(); + control + .checked("api", "latest", Some(candidate.clone()), None, now()) + .await + .unwrap(); + db::request_component_install(&db, "api", &candidate.digest, now()) + .await + .unwrap(); + assert!(!api.tick().await.unwrap()); + tick_after_ready(&mut api).await; + assert_eq!(api.readiness_receipt, ReadinessReceipt::Recorded); + assert!(control.component("api").await.unwrap().desired.is_none()); + }) + .await + .expect("startup and failed install must settle"); let installed = control.component("api").await.unwrap(); assert_eq!(installed.state, "failed"); assert!(installed.installed.is_none()); @@ -1165,12 +1233,13 @@ async fn newer_launcher_cancellation_restores_baked_schema_and_observation() { &root, ); bot.baked_compatibility = contract; - let deadline = Instant::now() + Duration::from_secs(5); - while bot.readiness_receipt == ReadinessReceipt::Pending { - assert!(Instant::now() < deadline); - bot.tick().await.unwrap(); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(5), async { + assert!(!bot.tick().await.unwrap()); + tick_after_ready(&mut bot).await; + assert_eq!(bot.readiness_receipt, ReadinessReceipt::Recorded); + }) + .await + .expect("baked bot startup"); let seen = control.component("bot").await.unwrap().observed.unwrap(); assert_eq!(seen.max_schema, 15); // A launcher newer than its image publishes the baked image's own build. @@ -1695,14 +1764,10 @@ async fn ready_failure_of_another_release_leaves_complete_upgrade() { ) .await .unwrap(); - let deadline = Instant::now() + Duration::from_secs(2); - loop { - if child.child.try_wait().unwrap().is_some() { - break; - } - assert!(Instant::now() < deadline, "fixture child did not exit"); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(2), child.child.wait()) + .await + .expect("fixture child did not exit") + .unwrap(); let mut bot = offline_controller("bot", control.clone(), &root); bot.running = Some(child); let error = bot.tick().await.unwrap_err(); @@ -2236,55 +2301,41 @@ fn read_only_options(path: &Path) -> DbOpenOptions { } } -async fn application_exchange(port_file: &Path, request_target: &str) -> String { - let started = Instant::now(); - let port = loop { - if let Ok(text) = tokio::fs::read_to_string(port_file).await - && let Ok(port) = text.trim().parse::() - { - break port; - } - assert!( - started.elapsed() < Duration::from_secs(10), - "application did not publish its port" - ); - tokio::time::sleep(Duration::from_millis(20)).await; - }; - let started = Instant::now(); - loop { - if let Ok(mut stream) = tokio::net::TcpStream::connect(("127.0.0.1", port)).await { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let request = format!( - "{request_target} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n" - ); - stream.write_all(request.as_bytes()).await.unwrap(); - let mut body = String::new(); - let _ = stream.read_to_string(&mut body).await; - if body.contains("200") || body.contains("404") { - return body; - } - } - assert!( - started.elapsed() < Duration::from_secs(10), - "application route was not served" - ); - tokio::time::sleep(Duration::from_millis(20)).await; - } +async fn application_exchange(ready: &Path, request_target: &str) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + tokio::time::timeout(Duration::from_secs(10), async { + // The child binds the listener and publishes port and mode before its ready file. + wait_for_marker(ready).await; + let port: u16 = tokio::fs::read_to_string(ready.with_extension("port")) + .await + .unwrap() + .parse() + .unwrap(); + let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)) + .await + .unwrap(); + let request = + format!("{request_target} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + response + }) + .await + .expect("application route was not served") } -async fn application_route(port_file: &Path) -> String { - let started = Instant::now(); - loop { - let body = application_exchange(port_file, "GET /api/me").await; - if body.contains("200") { - return body; - } - assert!( - started.elapsed() < Duration::from_secs(10), - "application route was not served" - ); - tokio::time::sleep(Duration::from_millis(20)).await; - } +async fn application_route(ready: &Path) -> String { + let response = application_exchange(ready, "GET /api/me").await; + assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}"); + response +} + +fn elapse_startup_retry(service: &mut Supervisor) { + let ReceiptSchedule::After(at) = &mut service.activation_receipts.schedule else { + panic!("unsaved startup receipt should have scheduled a retry"); + }; + *at -= Duration::from_secs(1); } async fn api_without_a_writer(binary: &Path, root: &Path, db_path: &Path) { @@ -2321,7 +2372,7 @@ async fn api_without_a_writer(binary: &Path, root: &Path, db_path: &Path) { .expect("normal application was not started") .ready_file .clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); let mode = tokio::fs::read_to_string(ready.with_extension("mode")) .await @@ -2401,7 +2452,7 @@ async fn api_role_serves_immediately_and_stores_startup_receipts_once_the_bot_is service.pending_startup = planned; assert!(!service.tick().await.unwrap()); let ready = service.running.as_ref().unwrap().ready_file.clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); assert_eq!(service.pending_startup.len(), 2); assert!( @@ -2424,7 +2475,7 @@ async fn api_role_serves_immediately_and_stores_startup_receipts_once_the_bot_is .await .unwrap() ); - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); assert!(!service.tick().await.unwrap()); assert!(service.pending_startup.is_empty()); assert_eq!( @@ -2516,9 +2567,12 @@ async fn api_role_startup_receipts_log_one_info_line_per_unreachable_link_attemp let (bytes, capture) = capture_all_logs(); // Two attempts on consecutive polls, as every deploy produces. assert!(!service.tick().await.unwrap()); - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); // #609: the healthy production swap was still waiting at 32s and 49s. - service.startup_link_down_since = Some(Instant::now() - Duration::from_secs(49)); + *service + .startup_link_down_since + .as_mut() + .expect("ongoing outage") -= Duration::from_secs(49); assert!(!service.tick().await.unwrap()); drop(capture); assert_eq!( @@ -2532,7 +2586,7 @@ async fn api_role_startup_receipts_log_one_info_line_per_unreachable_link_attemp .expect("normal application was not started") .ready_file .clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); let logs = captured(&bytes); let lines = logs @@ -2721,9 +2775,9 @@ async fn api_role_serves_reads_while_a_superseded_launcher_clear_waits_for_the_w .expect("normal application was not started") .ready_file .clone(); - let health = application_exchange(&ready.with_extension("port"), "GET /health").await; + let health = application_exchange(&ready, "GET /health").await; assert!(health.contains("200"), "{health}"); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); let mode = tokio::fs::read_to_string(ready.with_extension("mode")) .await @@ -2752,17 +2806,12 @@ async fn api_role_serves_reads_while_a_superseded_launcher_clear_waits_for_the_w .await .unwrap() ); - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); assert!(!service.tick().await.unwrap()); - assert!( - service - .control - .component("api") - .await - .unwrap() - .desired_launcher - .is_none() - ); + let saved = service.control.component("api").await.unwrap(); + assert!(service.pending_startup.is_empty()); + assert_eq!(saved.launcher_sha256.as_deref(), Some(hash.as_str())); + assert!(saved.desired_launcher.is_none()); assert!(!service.tick().await.unwrap()); assert!( service @@ -2843,9 +2892,9 @@ async fn api_role_serves_reads_while_an_uncontracted_launcher_clear_waits_for_th .expect("normal application was not started") .ready_file .clone(); - let health = application_exchange(&ready.with_extension("port"), "GET /health").await; + let health = application_exchange(&ready, "GET /health").await; assert!(health.contains("200"), "{health}"); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); let mode = tokio::fs::read_to_string(ready.with_extension("mode")) .await @@ -2874,17 +2923,12 @@ async fn api_role_serves_reads_while_an_uncontracted_launcher_clear_waits_for_th .await .unwrap() ); - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); assert!(!service.tick().await.unwrap()); - assert!( - service - .control - .component("api") - .await - .unwrap() - .desired_launcher - .is_none() - ); + let saved = service.control.component("api").await.unwrap(); + assert!(service.pending_startup.is_empty()); + assert_eq!(saved.launcher_sha256.as_deref(), Some(hash.as_str())); + assert!(saved.desired_launcher.is_none()); assert!(!service.tick().await.unwrap()); assert!( service @@ -2985,14 +3029,10 @@ async fn crash_running_child(service: &mut Supervisor) -> u32 { .expect("normal application was not started"); let pid = child.child.id().expect("child pid"); child.child.start_kill().expect("crash child"); - let deadline = Instant::now() + Duration::from_secs(2); - loop { - if child.child.try_wait().unwrap().is_some() { - break; - } - assert!(Instant::now() < deadline, "crashed child did not exit"); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(2), child.child.wait()) + .await + .expect("fixture child did not exit") + .unwrap(); pid } @@ -3015,7 +3055,7 @@ async fn replaced_uncontracted_clear_drains_and_restarts_a_crashed_child() { // supervision a stuck clear used to skip. service.enabled = false; claim_writer(&bot).await; - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); let error = service.tick().await.unwrap_err(); assert!( error.to_string().contains("application exited"), @@ -3035,7 +3075,11 @@ async fn replaced_uncontracted_clear_drains_and_restarts_a_crashed_child() { desired.launcher.unwrap().revision, db::LAUNCHER_REVISION + 1 ); - tokio::time::sleep(POLL).await; + *service + .restart + .not_before + .as_mut() + .expect("child crash backoff") -= POLL; assert!(!service.tick().await.unwrap()); let restarted = service .running @@ -3043,7 +3087,7 @@ async fn replaced_uncontracted_clear_drains_and_restarts_a_crashed_child() { .expect("crashed child was not restarted"); assert_ne!(restarted.child.id(), Some(crashed)); let ready = restarted.ready_file.clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); assert_eq!( service @@ -3081,7 +3125,7 @@ async fn lost_uncontracted_clear_reply_drains_and_restarts_a_crashed_child() { assert_ne!(queued.digest, ""); let crashed = crash_running_child(&mut service).await; claim_writer(&bot).await; - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); let error = service.tick().await.unwrap_err(); assert!( error.to_string().contains("application exited"), @@ -3098,7 +3142,11 @@ async fn lost_uncontracted_clear_reply_drains_and_restarts_a_crashed_child() { .desired_launcher .is_none() ); - tokio::time::sleep(POLL).await; + *service + .restart + .not_before + .as_mut() + .expect("child crash backoff") -= POLL; assert!(!service.tick().await.unwrap()); let restarted = service .running @@ -3106,7 +3154,7 @@ async fn lost_uncontracted_clear_reply_drains_and_restarts_a_crashed_child() { .expect("crashed child was not restarted"); assert_ne!(restarted.child.id(), Some(crashed)); let ready = restarted.ready_file.clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); assert!(service.pending_startup.is_empty()); assert!( @@ -3210,7 +3258,7 @@ async fn superseded_clear_receipt_retires_when_no_row_matches() { // that replacement while the crashed child is restarted. service.enabled = false; claim_writer(&bot).await; - tokio::time::sleep(Duration::from_millis(1_100)).await; + elapse_startup_retry(&mut service); let error = service.tick().await.unwrap_err(); assert!( error.to_string().contains("application exited"), @@ -3236,7 +3284,11 @@ async fn superseded_clear_receipt_retires_when_no_row_matches() { .digest, replacement.digest ); - tokio::time::sleep(POLL).await; + *service + .restart + .not_before + .as_mut() + .expect("child crash backoff") -= POLL; assert!(!service.tick().await.unwrap()); let restarted = service .running @@ -3244,7 +3296,7 @@ async fn superseded_clear_receipt_retires_when_no_row_matches() { .expect("crashed child was not restarted"); assert_ne!(restarted.child.id(), Some(crashed)); let ready = restarted.ready_file.clone(); - let body = application_route(&ready.with_extension("port")).await; + let body = application_route(&ready).await; assert!(body.contains("{\"ok\":true}"), "{body}"); assert_eq!( service @@ -3384,10 +3436,7 @@ async fn baked_bot_migrates_queued_protocol3_core_baseline_without_starting_api_ ); // The fixture stands in for the maintenance API (whose /health route is // application code) and answers on a real socket while it is alive. - let reserved_health = bind_reclaimable_health_port().await; - let addr = reserved_health.local_addr().unwrap(); - drop(reserved_health); - tokio::fs::write(root.join("bind-maintenance-baked-bot"), addr.to_string()) + tokio::fs::write(root.join("bind-maintenance-baked-bot"), "127.0.0.1:0") .await .unwrap(); // Until the bot migrates, the API waits without a tick error: the main @@ -3398,9 +3447,18 @@ async fn baked_bot_migrates_queued_protocol3_core_baseline_without_starting_api_ assert!(!ticks.0.unwrap() && !ticks.1.unwrap()); assert!(api.running.is_none()); tokio::time::timeout(POLL, async { - while !launcher_health_responds(addr).await { - tokio::time::sleep(Duration::from_millis(10)).await; - } + let ready = &api + .maintenance + .as_ref() + .expect("live maintenance child") + .ready_file; + wait_for_marker(ready).await; + let addr = tokio::fs::read_to_string(ready) + .await + .unwrap() + .parse() + .unwrap(); + assert!(read_launcher_health(addr).await); }) .await .expect("the launcher keeps a live maintenance child while waiting"); @@ -3411,9 +3469,11 @@ async fn baked_bot_migrates_queued_protocol3_core_baseline_without_starting_api_ assert_eq!(logs, [waiting], "stale_meta={stale_meta}"); // Past the bound the wait becomes a tick error again, without the // owner recovery advice. The wait keeps its original start. - let overdue = Instant::now() - .checked_sub(CORE_MIGRATION_WAIT + Duration::from_secs(1)) - .unwrap(); + let overdue = api + .core_migration_wait + .expect("migration wait already started") + - CORE_MIGRATION_WAIT + - Duration::from_secs(1); api.core_migration_wait = Some(overdue); let error = format!("{:#}", api.tick().await.unwrap_err()); assert!( @@ -3453,12 +3513,13 @@ async fn baked_bot_migrates_queued_protocol3_core_baseline_without_starting_api_ tokio::fs::remove_file(root.join("hold-baked-bot-ready")) .await .unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while bot.readiness_receipt == ReadinessReceipt::Pending { - assert!(Instant::now() < deadline); - bot.report_ready().await.unwrap(); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(5), async { + wait_for_ready_file(&bot).await; + assert!(bot.report_ready().await.unwrap()); + assert_eq!(bot.readiness_receipt, ReadinessReceipt::Recorded); + }) + .await + .expect("migrated bot readiness receipt"); let after = control.component("bot").await.unwrap(); assert_eq!(after.desired, before.desired); assert_eq!(after.candidate, before.candidate); @@ -3847,15 +3908,15 @@ async fn stale_schema_selections_without_upgrade_are_refused_once_after_migratio tokio::fs::remove_file(root.join("hold-baked-bot-ready")) .await .unwrap(); - let deadline = Instant::now() + Duration::from_secs(5); - while bot.readiness_receipt == ReadinessReceipt::Pending - || api.readiness_receipt == ReadinessReceipt::Pending - { - assert!(Instant::now() < deadline); - bot.report_ready().await.unwrap(); - api.report_ready().await.unwrap(); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tokio::time::timeout(Duration::from_secs(5), async { + for service in [&mut bot, &mut api] { + wait_for_ready_file(service).await; + assert!(service.report_ready().await.unwrap()); + assert_eq!(service.readiness_receipt, ReadinessReceipt::Recorded); + } + }) + .await + .expect("migrated child readiness receipts"); for role in ["bot", "api"] { let queued = control.component(role).await.unwrap(); assert!( @@ -3928,23 +3989,12 @@ async fn stale_schema_selections_without_upgrade_are_refused_once_after_migratio db::request_component_install(&install_db, "bot", &release.digest, now()) .await .unwrap(); - let apply_deadline = Instant::now() + Duration::from_secs(10); - while control - .component("bot") - .await - .unwrap() - .installed - .as_ref() - .map(|installed| &installed.digest) - != Some(&release.digest) - { - assert!( - Instant::now() < apply_deadline, - "compatible selection did not apply" - ); + tokio::time::timeout(Duration::from_secs(10), async { assert!(!bot.tick().await.unwrap()); - tokio::time::sleep(Duration::from_millis(10)).await; - } + tick_after_ready(&mut bot).await; + }) + .await + .expect("compatible selection did not apply"); let applied = control.component("bot").await.unwrap(); assert_eq!(applied.state, "running"); assert_eq!(applied.installed.unwrap().digest, release.digest); @@ -3971,26 +4021,26 @@ async fn stale_schema_selections_without_upgrade_are_refused_once_after_migratio } async fn launcher_health_responds(addr: std::net::SocketAddr) -> bool { + tokio::time::timeout(Duration::from_millis(200), read_launcher_health(addr)) + .await + .unwrap_or(false) +} + +async fn read_launcher_health(addr: std::net::SocketAddr) -> bool { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - tokio::time::timeout(Duration::from_millis(200), async { - let Ok(mut stream) = tokio::net::TcpStream::connect(addr).await else { - return false; - }; - if stream - .write_all(b"GET /health HTTP/1.0\r\n\r\n") - .await - .is_err() - { - return false; - } - let mut buf = [0u8; 64]; - let Ok(n) = stream.read(&mut buf).await else { - return false; - }; - std::str::from_utf8(&buf[..n]).is_ok_and(|text| text.starts_with("HTTP/1.1 200")) - }) - .await - .unwrap_or(false) + let Ok(mut stream) = tokio::net::TcpStream::connect(addr).await else { + return false; + }; + if stream + .write_all(b"GET /health HTTP/1.0\r\n\r\n") + .await + .is_err() + { + return false; + } + const OK: &[u8] = b"HTTP/1.1 200"; + let mut prefix = [0; OK.len()]; + stream.read_exact(&mut prefix).await.is_ok() && prefix == OK } async fn assert_launcher_health(addr: std::net::SocketAddr, reason: &str) { @@ -4303,7 +4353,10 @@ fn child_start_count(root: &std::path::Path, name: &str) -> usize { .count() } -fn watch_fixture_renames(root: &Path) -> std::io::Result> { +fn watch_fixture_changes( + root: &Path, + mask: u32, +) -> std::io::Result> { use std::os::unix::ffi::OsStrExt; let path = std::ffi::CString::new(root.as_os_str().as_bytes())?; @@ -4315,7 +4368,7 @@ fn watch_fixture_renames(root: &Path) -> std::io::Result bool) { + use std::io::Read; + let changes = watch_fixture_changes(dir, libc::IN_MOVED_TO | libc::IN_CLOSE_WRITE).unwrap(); + let mut events = [0; 4096]; + while !published() { + changes + .async_io(tokio::io::Interest::READABLE, |mut file| { + file.read(&mut events) + }) + .await + .unwrap(); + } +} + +async fn wait_for_marker(marker: &Path) { + wait_for_publication(marker.parent().unwrap(), || marker.exists()).await; +} + async fn wait_for_ready_file(service: &Supervisor) { - let ready = service.running.as_ref().expect("child").ready_file.clone(); - tokio::time::timeout(Duration::from_secs(10), async { - while tokio::fs::metadata(&ready).await.is_err() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("child ready file"); + let ready = &service.running.as_ref().expect("child").ready_file; + tokio::time::timeout(Duration::from_secs(10), wait_for_marker(ready)) + .await + .expect("child ready file"); } async fn install_for_outage(