From 6f225ee466a55dcab057ea48cfd187ad5cdc0397 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 18:36:34 +0100 Subject: [PATCH] STRA-338 size-fn: leleka-deploy: e2e tests split into scenario helpers, wide messages with named arguments --- crates/deploy/src/app/quick_health.rs | 16 +- .../deploy/src/expert_profile/provisioning.rs | 8 +- crates/deploy/src/steps/downloads.rs | 7 +- crates/deploy/src/supervisor/startup.rs | 9 +- crates/deploy/src/units.rs | 5 +- crates/deploy/src/watchdog.rs | 8 +- crates/deploy/src/winfront/session.rs | 11 +- crates/deploy/tests/e2e/dry_run_and_usage.rs | 54 ++-- .../tests/e2e/expert_profile_install.rs | 285 +++++++++--------- crates/deploy/tests/e2e/reconfigure_flow.rs | 37 ++- .../deploy/tests/e2e/supervisor_lifecycle.rs | 47 ++- crates/deploy/tests/e2e/up_flow.rs | 99 ++++-- 12 files changed, 357 insertions(+), 229 deletions(-) diff --git a/crates/deploy/src/app/quick_health.rs b/crates/deploy/src/app/quick_health.rs index 06c4bd04..882c9395 100644 --- a/crates/deploy/src/app/quick_health.rs +++ b/crates/deploy/src/app/quick_health.rs @@ -83,7 +83,13 @@ fn report_shard(paths: &Paths, stamps: &VerifyStamps, index: usize, health: &mut "stamped (verified in its present state)" } _ => { - health.notes.push(format!("shard {index} is not stamped: the next start hashes it (minutes); `leleka verify` renews the stamp")); + health.notes.push(format!( + concat!( + "shard {index} is not stamped: the next start hashes it (minutes); ", + "`leleka verify` renews the stamp" + ), + index = index + )); "not stamped" } }; @@ -193,8 +199,12 @@ pub(super) fn report_logs_and_requests(paths: &Paths, config: &RunConfig, health .count(); if recent.len() >= 10 && failed * 5 > recent.len() { health.notes.push(format!( - "{failed} of the last {} requests failed or were rejected: see `leleka logs --level warn --since 1h`", - recent.len() + concat!( + "{failed} of the last {} requests failed or were rejected: ", + "see `leleka logs --level warn --since 1h`" + ), + recent.len(), + failed = failed )); } } diff --git a/crates/deploy/src/expert_profile/provisioning.rs b/crates/deploy/src/expert_profile/provisioning.rs index e2a023ee..5cfe38f8 100644 --- a/crates/deploy/src/expert_profile/provisioning.rs +++ b/crates/deploy/src/expert_profile/provisioning.rs @@ -129,8 +129,12 @@ fn install_local(request: &Request, local: &Path, part: &Path) -> Result Result, Failure> match (runtime_token, gateway_token) { (Some(a), Some(b)) if valid_token(a) && valid_token(b) && a != b => Ok(env), _ => Err(setup_failure(format!( - "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} values of 32..4096 printable ASCII bytes", - paths.env_file().display() + concat!( + "{} must define two different {RUNTIME_TOKEN_ENV}/{GATEWAY_TOKEN_ENV} ", + "values of 32..4096 printable ASCII bytes" + ), + paths.env_file().display(), + RUNTIME_TOKEN_ENV = RUNTIME_TOKEN_ENV, + GATEWAY_TOKEN_ENV = GATEWAY_TOKEN_ENV ))), } } diff --git a/crates/deploy/src/units.rs b/crates/deploy/src/units.rs index 661fc81b..a1d3b68d 100644 --- a/crates/deploy/src/units.rs +++ b/crates/deploy/src/units.rs @@ -87,7 +87,10 @@ fn service_section( unit.push_str(&limits_and_logging(scope)); unit.push_str(&format!("ExecStart={bin} run --config {config}\n")); // A failed start must be looked at: the first start copies 55 GB. Exit 2 is a configuration error. - unit.push_str("Restart=on-failure\nRestartSec=30\nRestartSteps=6\nRestartMaxDelaySec=600\nRestartPreventExitStatus=2\n"); + unit.push_str(concat!( + "Restart=on-failure\nRestartSec=30\nRestartSteps=6\n", + "RestartMaxDelaySec=600\nRestartPreventExitStatus=2\n" + )); // The supervisor turns SIGTERM into a graceful stop of the API (drain), the gateway and the engine. unit.push_str("KillSignal=SIGTERM\nTimeoutStopSec=180\nKillMode=mixed\n\n"); Ok(unit) diff --git a/crates/deploy/src/watchdog.rs b/crates/deploy/src/watchdog.rs index 5cf580e3..a1c043a3 100644 --- a/crates/deploy/src/watchdog.rs +++ b/crates/deploy/src/watchdog.rs @@ -144,8 +144,12 @@ impl Watchdog { match active_s { Some(seconds) if seconds >= self.limits.max_request.as_secs_f64() => { Verdict::RestartEngine(format!( - "a request has been active for {seconds:.0} s, beyond the longest allowed ({} s): the engine makes no progress", - self.limits.max_request.as_secs() + concat!( + "a request has been active for {seconds:.0} s, beyond the longest allowed ({} s): ", + "the engine makes no progress" + ), + self.limits.max_request.as_secs(), + seconds = seconds )) } _ => Verdict::Healthy, diff --git a/crates/deploy/src/winfront/session.rs b/crates/deploy/src/winfront/session.rs index b8689745..f76b6cc5 100644 --- a/crates/deploy/src/winfront/session.rs +++ b/crates/deploy/src/winfront/session.rs @@ -81,8 +81,15 @@ fn refuse_drvfs_assets(session: &Session) -> Option { return None; } note(&format!( - "--assets {assets} is a Windows drive seen from WSL (9p): mapped and direct reads of the 140 GB model are far too slow there. Put the model volume on the WSL disk, e.g. --assets {}/leleka-assets (copy the files with `wsl -d {} cp` or from \\\\wsl.localhost\\{}\\...)", - session.home, session.bridge.distro, session.bridge.distro + concat!( + "--assets {assets} is a Windows drive seen from WSL (9p): mapped and direct reads of the 140 GB ", + "model are far too slow there. Put the model volume on the WSL disk, e.g. --assets ", + "{}/leleka-assets (copy the files with `wsl -d {} cp` or from \\\\wsl.localhost\\{}\\...)" + ), + session.home, + session.bridge.distro, + session.bridge.distro, + assets = assets )); Some(2) } diff --git a/crates/deploy/tests/e2e/dry_run_and_usage.rs b/crates/deploy/tests/e2e/dry_run_and_usage.rs index 76432cb8..7160d55e 100644 --- a/crates/deploy/tests/e2e/dry_run_and_usage.rs +++ b/crates/deploy/tests/e2e/dry_run_and_usage.rs @@ -7,30 +7,29 @@ use std::process::Command as Process; // ----------------------------------------------------------------------------------------------------------- // the command line -#[test] -fn dry_run_prints_the_plan_and_changes_nothing() { - let fixture = Fixture::new("dry"); - let bin = fixture.root.join("bin"); - fixture.install_fake_binaries(&bin); - let output = Process::new(LELEKA) - .args([ - "up", - "--dry-run", - "--profile", - "rtx5090-32g", - "--mode", - "foreground", - "--assets", - ]) +/// `leleka up --dry-run [extra] --profile rtx5090-32g --mode foreground` on the fixture's directories. +fn dry_run(fixture: &Fixture, bin: &std::path::Path, extra: &[&str]) -> std::process::Output { + Process::new(LELEKA) + .args(["up", "--dry-run"]) + .args(extra) + .args(["--profile", "rtx5090-32g", "--mode", "foreground", "--assets"]) .arg(&fixture.dirs.assets) .arg("--state-dir") .arg(&fixture.dirs.state) .arg("--prefix") .arg(&fixture.dirs.prefix) .arg("--bin-src") - .arg(&bin) + .arg(bin) .output() - .unwrap(); + .unwrap() +} + +#[test] +fn dry_run_prints_the_plan_and_changes_nothing() { + let fixture = Fixture::new("dry"); + let bin = fixture.root.join("bin"); + fixture.install_fake_binaries(&bin); + let output = dry_run(&fixture, &bin, &[]); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); assert!( @@ -54,26 +53,7 @@ fn dry_run_prints_the_plan_and_changes_nothing() { assert!(!path.exists(), "--dry-run created {}", path.display()); } // --json is one parseable document with the steps. - let output = Process::new(LELEKA) - .args([ - "up", - "--dry-run", - "--json", - "--profile", - "rtx5090-32g", - "--mode", - "foreground", - "--assets", - ]) - .arg(&fixture.dirs.assets) - .arg("--state-dir") - .arg(&fixture.dirs.state) - .arg("--prefix") - .arg(&fixture.dirs.prefix) - .arg("--bin-src") - .arg(&bin) - .output() - .unwrap(); + let output = dry_run(&fixture, &bin, &["--json"]); let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(json["profile"], "rtx5090-32g"); assert!( diff --git a/crates/deploy/tests/e2e/expert_profile_install.rs b/crates/deploy/tests/e2e/expert_profile_install.rs index df1fc84b..c106e29b 100644 --- a/crates/deploy/tests/e2e/expert_profile_install.rs +++ b/crates/deploy/tests/e2e/expert_profile_install.rs @@ -4,7 +4,7 @@ use crate::harness::*; use leleka_deploy::{ app::run_up, config::RunConfig, - plan::{FsState, plan_steps}, + plan::{Context, FsState, Step, plan_steps}, profile::Profile, steps::gather_fs, }; @@ -12,147 +12,158 @@ use std::fs; #[tokio::test] async fn up_installs_the_expert_profile_offline_and_reports_it() { - use leleka_deploy::expert_profile::{ - FileState, PROFILE_ENV, file_state, sha256_hex, tier_report, - }; - let fixture = Fixture::new("expert"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - // A profile that pins the digest of a small fixture, so that the flow runs without the real 192 KiB table. - let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); - let digest = sha256_hex(&table); - let mut profile = Profile::builtin("rtx3080-16g").unwrap(); - profile.expert_profile_sha256 = Some(digest.clone()); - let profile_file = fixture.root.join("profile.json"); - fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); - let local = fixture.root.join("table.bin"); - fs::write(&local, &table).unwrap(); - let paths = fixture.dirs.paths(); - let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); - let flags = [ - profile_file.display().to_string(), - local.display().to_string(), - ]; + let scene = Scene::new(); + scene.no_table_blocks_with_both_ways_out().await; + scene.local_copy_is_installed_and_reported_on().await; + scene.second_run_rewrites_nothing().await; + scene.a_changed_file_turns_the_report_off().await; + scene.the_opt_out_is_recorded_and_reported().await; +} - // No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-fetch"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); - assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); - assert!( - step.state.why().contains("--expert-profile-file") - && step.state.why().contains("--no-expert-tier") - ); +/// The offline scenario: a profile that pins the digest of a small fixture, so that the flow runs without the real table. +struct Scene { + fixture: Fixture, + bin_src: std::path::PathBuf, + cublas: std::path::PathBuf, + mtp: std::path::PathBuf, + profile_file: String, + local: String, + digest: String, + table_path: std::path::PathBuf, +} - // With the local copy: installed, verified, configured, reported ON. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--expert-profile-file", &flags[1]], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "todo" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - assert_eq!(file_state(&table_path, &digest), FileState::Valid); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert_eq!( - config.engine_env.get(PROFILE_ENV), - Some(&table_path.display().to_string()) - ); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - report.on && report.line().starts_with("expert tier ON"), - "{}", - report.line() - ); +impl Scene { + fn new() -> Scene { + use leleka_deploy::expert_profile::sha256_hex; + let fixture = Fixture::new("expert"); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + let table = b"STRP-fixture: a stand-in for the ranked expert table".to_vec(); + let digest = sha256_hex(&table); + let mut profile = Profile::builtin("rtx3080-16g").unwrap(); + profile.expert_profile_sha256 = Some(digest.clone()); + let profile_file = fixture.root.join("profile.json"); + fs::write(&profile_file, serde_json::to_string(&profile).unwrap()).unwrap(); + let local = fixture.root.join("table.bin"); + fs::write(&local, &table).unwrap(); + let table_path = fixture.dirs.assets.join("data/expert-profile.bin"); + Scene { + profile_file: profile_file.display().to_string(), + local: local.display().to_string(), + fixture, + bin_src, + cublas, + mtp, + digest, + table_path, + } + } - // Second run: done, nothing rewritten. - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "done" - ); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + /// The plan of an `up` with these extra flags. + async fn plan(&self, extra: &[&str]) -> (Context, Vec) { + let opts = up_options_with( + &self.fixture, + &self.bin_src, + &self.cublas, + &self.mtp, + &self.profile_file, + extra, + ); + let ctx = healthy_context(&opts); + let steps = plan_steps(&ctx, &gather_fs(&ctx).await); + (ctx, steps) + } - // The file changes behind the service's back: the report turns OFF and the start drops the switches. - fs::write(&table_path, b"corrupted").unwrap(); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.line().starts_with("WARNING expert tier OFF"), - "{}", - report.line() - ); - let (env, _) = leleka_deploy::expert_profile::start_environment(&config, &fixture.dirs.assets); - assert!(!env.contains_key(PROFILE_ENV)); - // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). - let opts = up_options_with(&fixture, &bin_src, &cublas, &mtp, &flags[0], &[]); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!( - steps - .iter() - .find(|s| s.id == "expert-profile") - .unwrap() - .state - .tag(), - "BLOCKED" - ); - assert!( - run_up(&ctx, &steps) - .await - .unwrap_err() - .contains("expert-profile") - ); + /// No table, offline, no override: the plan blocks with both ways out, before anything is downloaded. + async fn no_table_blocks_with_both_ways_out(&self) { + let (_, steps) = self.plan(&["--no-fetch"]).await; + let step = steps.iter().find(|s| s.id == "expert-profile").unwrap(); + assert_eq!(step.state.tag(), "BLOCKED", "{step:?}"); + assert!( + step.state.why().contains("--expert-profile-file") + && step.state.why().contains("--no-expert-tier") + ); + } - // The explicit opt-out is recorded and reported as such. - let opts = up_options_with( - &fixture, - &bin_src, - &cublas, - &mtp, - &flags[0], - &["--no-expert-tier"], - ); - let ctx = healthy_context(&opts); - let steps = plan_steps(&ctx, &gather_fs(&ctx).await); - assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); - let config = RunConfig::read(&paths.run_config()).unwrap(); - assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); - let report = tier_report(&config, &fixture.dirs.assets); - assert!( - !report.on && report.opted_out && report.line().contains("explicit opt-out"), - "{}", - report.line() - ); + /// With the local copy: installed, verified, configured, reported ON. + async fn local_copy_is_installed_and_reported_on(&self) { + use leleka_deploy::expert_profile::{FileState, PROFILE_ENV, file_state, tier_report}; + let (ctx, steps) = self.plan(&["--expert-profile-file", &self.local]).await; + assert_eq!(expert_step_tag(&steps), "todo"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + assert_eq!(file_state(&self.table_path, &self.digest), FileState::Valid); + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + assert_eq!( + config.engine_env.get(PROFILE_ENV), + Some(&self.table_path.display().to_string()) + ); + let report = tier_report(&config, &self.fixture.dirs.assets); + assert!( + report.on && report.line().starts_with("expert tier ON"), + "{}", + report.line() + ); + } + + /// Second run: done, nothing rewritten. + async fn second_run_rewrites_nothing(&self) { + let (ctx, steps) = self.plan(&["--expert-profile-file", &self.local]).await; + assert_eq!(expert_step_tag(&steps), "done"); + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + } + + /// The file changes behind the service's back: the report turns OFF and the start drops the switches. + async fn a_changed_file_turns_the_report_off(&self) { + use leleka_deploy::expert_profile::{PROFILE_ENV, start_environment, tier_report}; + let assets = &self.fixture.dirs.assets; + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + fs::write(&self.table_path, b"corrupted").unwrap(); + let report = tier_report(&config, assets); + assert!( + !report.on && report.line().starts_with("WARNING expert tier OFF"), + "{}", + report.line() + ); + let (env, _) = start_environment(&config, assets); + assert!(!env.contains_key(PROFILE_ENV)); + // `up` without an override refuses to guess: the wrong file blocks the plan (it is never silently ignored). + let (ctx, steps) = self.plan(&[]).await; + assert_eq!(expert_step_tag(&steps), "BLOCKED"); + assert!( + run_up(&ctx, &steps) + .await + .unwrap_err() + .contains("expert-profile") + ); + } + + /// The explicit opt-out is recorded and reported as such. + async fn the_opt_out_is_recorded_and_reported(&self) { + use leleka_deploy::expert_profile::{PROFILE_ENV, tier_report}; + let (ctx, steps) = self.plan(&["--no-expert-tier"]).await; + assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); + let config = RunConfig::read(&self.fixture.dirs.paths().run_config()).unwrap(); + assert!(!config.expert_tier && !config.engine_env.contains_key(PROFILE_ENV)); + let report = tier_report(&config, &self.fixture.dirs.assets); + assert!( + !report.on && report.opted_out && report.line().contains("explicit opt-out"), + "{}", + report.line() + ); + } +} + +/// The state tag of the `expert-profile` step. +fn expert_step_tag(steps: &[Step]) -> &str { + steps + .iter() + .find(|s| s.id == "expert-profile") + .unwrap() + .state + .tag() } #[tokio::test] diff --git a/crates/deploy/tests/e2e/reconfigure_flow.rs b/crates/deploy/tests/e2e/reconfigure_flow.rs index 47666b3b..88ae82ce 100644 --- a/crates/deploy/tests/e2e/reconfigure_flow.rs +++ b/crates/deploy/tests/e2e/reconfigure_flow.rs @@ -4,6 +4,7 @@ use crate::harness::*; use leleka_deploy::profile::{KarSource, Profile}; use leleka_deploy::reconfigure::{Outcome, Request, State, read_outcome, write_request}; use leleka_deploy::resources::Preset; +use leleka_deploy::config::RunConfig; use serde_json::json; use std::{ fs, @@ -61,6 +62,14 @@ fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { "a planned restart is not a crash" ); assert_eq!(fixture.http_status("/ready"), 200); + check_new_engine_arguments(&service); + check_not_persisted_and_same_budget_is_a_noop(&service, &before); + service.stop(); +} + +/// The second engine has the new budget and is handed the first one's verified sealed descriptor. +fn check_new_engine_arguments(service: &Service) { + let fixture = &service.fixture; let starts = service.starts(); assert_eq!(starts.len(), 2, "{starts:?}"); assert!( @@ -81,6 +90,10 @@ fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { ); let engine_log = fs::read_to_string(fixture.dirs.paths().logs().join("engine.log")).unwrap(); assert_eq!(engine_log.matches("kar fd ").count(), 2, "{engine_log}"); +} + +fn check_not_persisted_and_same_budget_is_a_noop(service: &Service, before: &str) { + let fixture = &service.fixture; // not persisted: the file still has the old budget assert_eq!( fs::read_to_string(fixture.dirs.paths().run_config()).unwrap(), @@ -99,7 +112,6 @@ fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() { same.message ); assert_eq!(service.starts().len(), 2); - service.stop(); } #[test] @@ -132,6 +144,12 @@ fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { assert_eq!(config.profile.gpu_budget_bytes, 3 * GIB); assert_eq!(config.profile.context_tokens, 4096); assert_eq!(config.preset, Preset::Workstation); + check_persisted_numbers_survive(&service, gateway, api, &config); + service.stop(); +} + +fn check_persisted_numbers_survive(service: &Service, gateway: u64, api: u64, config: &RunConfig) { + let fixture = &service.fixture; assert!( config.base_profile.is_some(), "the unmodified profile is kept to undo the preset" @@ -167,7 +185,6 @@ fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() { && last.contains("--context-tokens 4096"), "{last}" ); - service.stop(); } #[test] @@ -205,6 +222,12 @@ fn settings_alone_are_recorded_and_persisted_without_a_restart() { "no restart" ); assert_eq!(service.starts().len(), 1); + check_unpersisted_and_invalid_documents(&service); + service.stop(); +} + +fn check_unpersisted_and_invalid_documents(service: &Service) { + let fixture = &service.fixture; // not persisted: in force for this supervisor only let quiet = ask( fixture, @@ -222,7 +245,6 @@ fn settings_alone_are_recorded_and_persisted_without_a_restart() { ); assert_eq!(bad.state, State::Refused); assert!(bad.message.contains("cpu_workers"), "{}", bad.message); - service.stop(); } #[test] @@ -254,6 +276,12 @@ fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_th "the engine was not stopped" ); assert!(pid_alive(engine)); + check_failed_new_engine_restores_the_old_one(&service, engine); + service.stop(); +} + +fn check_failed_new_engine_restores_the_old_one(service: &Service, engine: u64) { + let fixture = &service.fixture; // a budget the new engine cannot start with: the previous engine is started again with the previous numbers fs::write( fixture.fake_dir().join("fail-engine-budget"), @@ -293,7 +321,6 @@ fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_th let config = leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap(); assert_eq!(config.profile.gpu_budget_bytes, 15 * GIB); - service.stop(); } #[test] @@ -376,4 +403,4 @@ fn when_not_even_the_previous_engine_comes_back_the_service_fails_with_an_answer } mod service; -use service::{ask, request, start}; +use service::{Service, ask, request, start}; diff --git a/crates/deploy/tests/e2e/supervisor_lifecycle.rs b/crates/deploy/tests/e2e/supervisor_lifecycle.rs index 2c1b0061..861abadf 100644 --- a/crates/deploy/tests/e2e/supervisor_lifecycle.rs +++ b/crates/deploy/tests/e2e/supervisor_lifecycle.rs @@ -24,13 +24,20 @@ pub(super) fn lifecycle(source: KarSource) { let mut supervisor = start_supervisor(&fixture, &config, fd); let ready = fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready"); + let pids = check_ready(&fixture, &ready, source); + let again = check_engine_restart(&fixture, pids); + check_restart_calls(&fixture, source); + // The sealed descriptor was reused, not copied again (one process held it the whole time). + assert!(!supervisor.try_wait().unwrap().is_some()); + check_clean_stop(&fixture, &mut supervisor, &again, pids); +} + +/// The ready status: no restarts, the API answers, the archive form is in the engine log, the status file is private. +/// Returns the pids of the engine, the gateway and the API. +fn check_ready(fixture: &Fixture, ready: &serde_json::Value, source: KarSource) -> (u64, u64, u64) { + let paths = fixture.dirs.paths(); assert_eq!(ready["engine_restarts"], 0); assert_eq!(fixture.http_status("/ready"), 200); - let (engine_pid, gateway_pid, api_pid) = ( - ready["engine_pid"].as_u64().unwrap(), - ready["gateway_pid"].as_u64().unwrap(), - ready["api_pid"].as_u64().unwrap(), - ); let engine_log = fs::read_to_string(paths.logs().join("engine.log")).unwrap(); match source { KarSource::Memfd => assert!(engine_log.contains("kar fd "), "{engine_log}"), @@ -49,8 +56,18 @@ pub(super) fn lifecycle(source: KarSource) { .unwrap() .contains(KEY) ); + ( + ready["engine_pid"].as_u64().unwrap(), + ready["gateway_pid"].as_u64().unwrap(), + ready["api_pid"].as_u64().unwrap(), + ) +} - // Kill the engine: the API reports not ready, the supervisor restarts it and loads again. +/// Kill the engine: the API reports not ready, the supervisor restarts it and loads again. +fn check_engine_restart( + fixture: &Fixture, + (engine_pid, gateway_pid, api_pid): (u64, u64, u64), +) -> serde_json::Value { signal(engine_pid, "KILL"); let again = fixture.wait_for("engine restart", Duration::from_secs(60), |s| { s["phase"] == "ready" && s["engine_restarts"] == 1 @@ -67,6 +84,10 @@ pub(super) fn lifecycle(source: KarSource) { "the API must survive an engine restart" ); assert_eq!(fixture.http_status("/ready"), 200); + again +} + +fn check_restart_calls(fixture: &Fixture, source: KarSource) { let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap(); assert_eq!(calls.matches("leleka-inference ").count(), 2, "{calls}"); assert_eq!(calls.matches("load-mtp").count(), 2, "{calls}"); @@ -91,13 +112,19 @@ pub(super) fn lifecycle(source: KarSource) { "{}", starts[1] ); - // The sealed descriptor was reused, not copied again (one process held it the whole time). - assert!(!supervisor.try_wait().unwrap().is_some()); +} - // SIGTERM drains and stops everything with status 0. +/// SIGTERM drains and stops everything with status 0. +fn check_clean_stop( + fixture: &Fixture, + supervisor: &mut std::process::Child, + again: &serde_json::Value, + (_, gateway_pid, api_pid): (u64, u64, u64), +) { + let paths = fixture.dirs.paths(); let new_engine = again["engine_pid"].as_u64().unwrap(); signal(u64::from(supervisor.id()), "TERM"); - let status = wait_exit(&mut supervisor, Duration::from_secs(60)) + let status = wait_exit(supervisor, Duration::from_secs(60)) .expect("the supervisor must exit after SIGTERM"); assert!(status.success(), "exit {status:?}\n{}", fixture.logs()); assert_eq!(fixture.status().unwrap()["phase"], "stopped"); diff --git a/crates/deploy/tests/e2e/up_flow.rs b/crates/deploy/tests/e2e/up_flow.rs index 829186b2..7afab037 100644 --- a/crates/deploy/tests/e2e/up_flow.rs +++ b/crates/deploy/tests/e2e/up_flow.rs @@ -11,18 +11,48 @@ use std::{fs, os::unix::fs::PermissionsExt}; #[tokio::test] async fn up_is_idempotent_resumable_and_never_rotates_secrets() { - let fixture = Fixture::new("up"); - let bin_src = fixture.root.join("release/bin"); - fixture.install_fake_binaries(&bin_src); - // The fakes find their shared state through the *installed* bin directory. - let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); - fake_libraries(&cublas); - mtp_source(&mtp); - let opts = up_options(&fixture, &bin_src, &cublas, &mtp, &[]); - let paths = fixture.dirs.paths(); + let scene = Scene::new("up"); + let opts = scene.options(&[]); + let env_first = first_run_builds_everything(&scene, &opts).await; + second_run_does_nothing(&scene, &opts, &env_first).await; + a_lost_archive_is_rebuilt(&scene, &opts).await; + reverify_forces_the_verification(&scene).await; +} - // First run: everything is a todo, then everything exists. - let ctx = healthy_context(&opts); +/// The directories and fakes of one `up` scenario. +struct Scene { + fixture: Fixture, + bin_src: std::path::PathBuf, + cublas: std::path::PathBuf, + mtp: std::path::PathBuf, +} + +impl Scene { + fn new(label: &str) -> Scene { + let fixture = Fixture::new(label); + let bin_src = fixture.root.join("release/bin"); + fixture.install_fake_binaries(&bin_src); + // The fakes find their shared state through the *installed* bin directory. + let (cublas, mtp) = (fixture.root.join("cublas"), fixture.root.join("mtp-src")); + fake_libraries(&cublas); + mtp_source(&mtp); + Scene { + fixture, + bin_src, + cublas, + mtp, + } + } + + fn options(&self, extra: &[&str]) -> leleka_deploy::cli::UpOptions { + up_options(&self.fixture, &self.bin_src, &self.cublas, &self.mtp, extra) + } +} + +/// First run: everything is a todo, then everything exists. Returns the environment file it wrote. +async fn first_run_builds_everything(scene: &Scene, opts: &leleka_deploy::cli::UpOptions) -> String { + let paths = scene.fixture.dirs.paths(); + let ctx = healthy_context(opts); let fs0 = gather_fs(&ctx).await; let steps = plan_steps(&ctx, &fs0); assert!( @@ -46,6 +76,12 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { ] { assert!(file.exists(), "{what}: {} missing", file.display()); } + check_modes_config_and_calls(scene) +} + +/// Private environment file, read-only archive, the profile of the run and the tools called once. Returns the environment file. +fn check_modes_config_and_calls(scene: &Scene) -> String { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); assert_eq!( fs::metadata(paths.env_file()).unwrap().permissions().mode() & 0o777, 0o600 @@ -59,21 +95,25 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(config.profile.name, "rtx3080-16g"); let env_first = fs::read_to_string(paths.env_file()).unwrap(); assert!( - env_first.contains(&format!("LD_LIBRARY_PATH={}", cublas.display())), + env_first.contains(&format!("LD_LIBRARY_PATH={}", scene.cublas.display())), "{env_first}" ); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "api-key init") + count_calls(fixture, "model fetch"), + count_calls(fixture, "ensure-sharded-streamed"), + count_calls(fixture, "api-key init") ), (0, 1, 1), "the archive step fetches and verifies the shards itself" ); + env_first +} - // Second run: the plan has nothing to do and no tool is invoked again. - let ctx = healthy_context(&opts); +/// Second run: the plan has nothing to do and no tool is invoked again. +async fn second_run_does_nothing(scene: &Scene, opts: &leleka_deploy::cli::UpOptions, env_first: &str) { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); + let ctx = healthy_context(opts); let fs1 = gather_fs(&ctx).await; let steps = plan_steps(&ctx, &fs1); for step in &steps { @@ -87,10 +127,10 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "model verify"), - count_calls(&fixture, "ensure-sharded-streamed"), - count_calls(&fixture, "extract-tokenizer") + count_calls(fixture, "model fetch"), + count_calls(fixture, "model verify"), + count_calls(fixture, "ensure-sharded-streamed"), + count_calls(fixture, "extract-tokenizer") ), (0, 0, 1, 1) ); @@ -99,11 +139,14 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { env_first, "tokens must never rotate" ); +} - // Resumable: a lost archive is rebuilt, everything else is left alone. +/// Resumable: a lost archive is rebuilt, everything else is left alone. +async fn a_lost_archive_is_rebuilt(scene: &Scene, opts: &leleka_deploy::cli::UpOptions) { + let (fixture, paths) = (&scene.fixture, scene.fixture.dirs.paths()); fs::set_permissions(paths.kar(), fs::Permissions::from_mode(0o600)).unwrap(); fs::remove_file(paths.kar()).unwrap(); - let ctx = healthy_context(&opts); + let ctx = healthy_context(opts); let steps = plan_steps(&ctx, &gather_fs(&ctx).await); assert_eq!( steps.iter().find(|s| s.id == "kar").unwrap().state.tag(), @@ -116,14 +159,16 @@ async fn up_is_idempotent_resumable_and_never_rotates_secrets() { assert_eq!(run_up(&ctx, &steps).await.unwrap(), 0); assert_eq!( ( - count_calls(&fixture, "model fetch"), - count_calls(&fixture, "ensure-sharded-streamed") + count_calls(fixture, "model fetch"), + count_calls(fixture, "ensure-sharded-streamed") ), (0, 2) ); +} - // --reverify forces the verification again. - let reverify = up_options(&fixture, &bin_src, &cublas, &mtp, &["--reverify"]); +/// `--reverify` forces the verification again. +async fn reverify_forces_the_verification(scene: &Scene) { + let reverify = scene.options(&["--reverify"]); let ctx = healthy_context(&reverify); let steps = plan_steps(&ctx, &gather_fs(&ctx).await); assert_eq!(