STRA-338 size-fn2: leleka-deploy test functions within the limits (64 -> 0 test functions over 30 lines; helpers are not tests, test names, ids and assertions unchanged; e2e_windows checks moved to tests/e2e_windows/checks.rs)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 19:48:01 +01:00
parent e0034c61f3
commit 5198b90da5
40 changed files with 820 additions and 549 deletions
+26 -10
View File
@@ -3,18 +3,34 @@
use super::render_machine;
use serde_json::json;
fn operator_figures() -> serde_json::Value {
json!({
"phase": "decode",
"gpu": {
"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607,
"power_w": 480.0, "sm_clock_mhz": 2900
},
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
"ram": {
"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000,
"process_pinned_mib": 3000, "swap_used_mib": 0
},
"throughput": {
"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0,
"decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5,
"decode_tok_s_live": 135.2
},
"cache": {
"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104,
"last_prompt_tokens": 179968
},
"context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65}
})
}
#[test]
fn the_machine_view_names_every_figure_the_operator_asked_for() {
let text = render_machine(&json!({
"phase": "decode",
"gpu": {"util_pct": 91, "mem_util_pct": 40, "vram_used_mib": 30000, "vram_total_mib": 32607, "power_w": 480.0, "sm_clock_mhz": 2900},
"cpu": {"cores": 32, "process_busy_cores": 7.4, "system_busy_pct": 31.0},
"ram": {"total_mib": 122880, "available_mib": 70000, "process_rss_mib": 55000, "process_pinned_mib": 3000, "swap_used_mib": 0},
"throughput": {"prefill_tok_s_last": 5050.0, "prefill_tok_s_avg": 5010.0, "prefill_tok_s_lifetime": 5030.0,
"decode_tok_s_last": 131.0, "decode_tok_s_avg": 129.0, "decode_tok_s_lifetime": 128.5, "decode_tok_s_live": 135.2},
"cache": {"hit_ratio": 0.87, "token_hit_ratio": 0.91, "last_reused_tokens": 175104, "last_prompt_tokens": 179968},
"context": {"live_tokens": 179968, "max_tokens": 262144, "used_pct": 68.65}
}));
let text = render_machine(&operator_figures());
for needle in [
"engine load (decode)",
"91% busy",
+21 -9
View File
@@ -9,6 +9,18 @@ fn logs_and_report_take_their_own_flags_and_the_locating_ones() {
} else {
"/var/lib/x"
};
check_logs_filters(state);
assert!(
matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api"))
);
assert!(parse_as(false, &["logs", "--tail", "0"]).is_err());
assert!(parse_as(false, &["logs", "--tail", "x"]).is_err());
assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err());
assert!(parse_as(false, &["logs", "--bogus"]).is_err());
check_report_flags();
}
fn check_logs_filters(state: &str) {
let Ok(Command::Logs(options, logs)) = parse_as(
false,
&[
@@ -36,14 +48,6 @@ fn logs_and_report_take_their_own_flags_and_the_locating_ones() {
(Some(20), Some("15m"), Some("warn"), Some("0b1c2d3e"))
);
assert_eq!(options.dirs.state, PathBuf::from(state));
assert!(
matches!(parse_as(false, &["logs", "-f", "--source", "api"]), Ok(Command::Logs(_, l)) if l.follow && l.source.as_deref() == Some("api"))
);
assert!(parse_as(false, &["logs", "--tail", "0"]).is_err());
assert!(parse_as(false, &["logs", "--tail", "x"]).is_err());
assert!(parse_as(false, &["logs", "-f", "--request", "abcdef"]).is_err());
assert!(parse_as(false, &["logs", "--bogus"]).is_err());
check_report_flags();
}
fn check_report_flags() {
@@ -132,6 +136,11 @@ fn flags_accept_both_forms_and_reject_mistakes() {
.unwrap() else {
panic!()
};
check_both_form_values(&options);
check_mistakes_are_rejected();
}
fn check_both_form_values(options: &UpOptions) {
assert_eq!(options.dirs.assets, PathBuf::from("/data/l"));
assert_eq!(
(
@@ -144,7 +153,6 @@ fn flags_accept_both_forms_and_reject_mistakes() {
(1, ModeChoice::Foreground, true, true, false)
);
assert_eq!(options.ports.api, "127.0.0.1:9000");
check_mistakes_are_rejected();
}
fn check_mistakes_are_rejected() {
@@ -255,6 +263,10 @@ fn other_commands() {
assert_eq!((config, kar_fd), (PathBuf::from("/s/leleka.json"), Some(3)));
assert!(parse_as(false, &["run"]).is_err());
assert!(parse_as(false, &["frobnicate"]).is_err());
check_exec_and_seal_commands();
}
fn check_exec_and_seal_commands() {
assert!(matches!(
parse_as(false, &["exec-inherit", "--", "x"]).unwrap(),
Command::ExecInherit(_)
@@ -31,6 +31,10 @@ fn reconfigure_collects_the_settings_and_locates_the_service_with_the_up_flags()
assert_eq!(value["prefix_cache_tail"], "reply");
assert_eq!(value["prefix_cache_mib"], "20480");
assert_eq!(value["spec_min_p"], 0.5);
check_reconfigure_refusals();
}
fn check_reconfigure_refusals() {
assert!(
parse_as(false, &["reconfigure"])
.unwrap_err()
+7 -3
View File
@@ -173,6 +173,13 @@ fn generated_configs_are_consistent() {
);
assert_eq!(strata["runtime"]["max_context"], 262144);
assert_eq!(strata["runtime"]["max_output_tokens"], 32768);
check_output_ceiling_below_a_small_context();
// No secret is ever part of a generated config.
let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config);
assert!(!text.to_ascii_lowercase().contains("secret"));
}
fn check_output_ceiling_below_a_small_context() {
// A context of 8K needs a ceiling below it, or `strata-next check-config` refuses the file (the laptop profile used to have one).
let mut small = config_of("rtx3080-16g");
small.profile.context_tokens = 8192;
@@ -181,9 +188,6 @@ fn generated_configs_are_consistent() {
config_of("rtx3080-16g").strata_json()["runtime"]["max_output_tokens"],
32768
);
// No secret is ever part of a generated config.
let text = to_file_text(&strata) + &to_file_text(&daemon) + &to_file_text(&config);
assert!(!text.to_ascii_lowercase().contains("secret"));
}
#[test]
+6 -2
View File
@@ -271,10 +271,14 @@ mod tests {
);
inputs.volume_missing.clear();
assert_eq!(next_command(&inputs), None);
check_route_a_findings_never_block(&mut inputs);
}
fn check_route_a_findings_never_block(inputs: &mut Inputs) {
// Route A findings are reported but never block the native route.
inputs.wsl_found = false;
assert_eq!(next_command(&inputs), None);
let findings = advise(&inputs);
assert_eq!(next_command(inputs), None);
let findings = advise(inputs);
assert_eq!(
findings.last().unwrap().fix.as_deref(),
Some("wsl --install -d Ubuntu")
@@ -66,7 +66,15 @@ fn the_embedded_table_is_installed_offline_before_any_download() {
provision(&request, &mut never).unwrap(),
Outcome::AlreadyPresent
);
// an explicit file wins over the embedded table
check_explicit_file_wins_over_the_embedded_table(&dir, &request, &mut never);
let _ = std::fs::remove_dir_all(dir);
}
fn check_explicit_file_wins_over_the_embedded_table(
dir: &Path,
request: &Request,
never: &mut impl FnMut(&str, &Path) -> Result<(), String>,
) {
let other = dir.join("other.bin");
std::fs::write(&other, EMBEDDED).unwrap();
let second = dir.join("second").join("p.bin");
@@ -74,13 +82,12 @@ fn the_embedded_table_is_installed_offline_before_any_download() {
&Request {
dest: &second,
local: Some(&other),
..request
..*request
},
&mut never,
never,
)
.unwrap();
assert!(matches!(outcome, Outcome::Installed { origin, .. } if origin.ends_with("other.bin")));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
@@ -103,21 +110,27 @@ fn an_embedded_table_that_fails_its_digest_falls_back_to_the_download() {
moved_aside: None
}
);
// ... and without a source the failure names the embedded table
let _ = std::fs::remove_file(&dest);
check_without_a_source_the_failure_names_the_embedded_table(&request, &mut fetch);
let _ = std::fs::remove_dir_all(dir);
}
fn check_without_a_source_the_failure_names_the_embedded_table(
request: &Request,
fetch: &mut impl FnMut(&str, &Path) -> Result<(), String>,
) {
let _ = std::fs::remove_file(request.dest);
let error = provision(
&Request {
sources: &[],
..request
..*request
},
&mut fetch,
fetch,
)
.unwrap_err();
assert!(
error.contains("embedded") && error.contains("is not the expected"),
"{error}"
);
let _ = std::fs::remove_dir_all(dir);
}
/// Live check of the pinned sources (needs network and curl): `cargo test -p leleka-deploy -- --ignored pinned_sources`.
@@ -19,7 +19,17 @@ fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() {
embedded: None,
sources: &["https://one.test/p.bin", "https://two.test/p.bin"],
};
let outcome = provision(&request, &mut fetch).unwrap();
check_installed_then_left_alone(&request, &mut fetch, &calls);
let _ = std::fs::remove_dir_all(dir);
}
fn check_installed_then_left_alone(
request: &Request,
fetch: &mut impl FnMut(&str, &Path) -> Result<(), String>,
calls: &RefCell<Vec<String>>,
) {
let dest = request.dest;
let outcome = provision(request, fetch).unwrap();
assert_eq!(
outcome,
Outcome::Installed {
@@ -27,18 +37,14 @@ fn a_download_is_verified_then_installed_and_a_present_file_is_left_alone() {
moved_aside: None
}
);
assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE);
assert_eq!(std::fs::read(dest).unwrap(), FIXTURE);
assert!(
!with_suffix(&dest, ".part").exists(),
!with_suffix(dest, ".part").exists(),
"the staging file is gone"
);
// Second run: nothing is fetched.
assert_eq!(
provision(&request, &mut fetch).unwrap(),
Outcome::AlreadyPresent
);
assert_eq!(provision(request, fetch).unwrap(), Outcome::AlreadyPresent);
assert_eq!(calls.borrow().len(), 1);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
@@ -113,15 +119,26 @@ fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() {
panic!("offline: no download may be attempted")
};
check_wrong_local_file_is_refused(&dest, &bad, &digest, &mut never);
check_good_local_file_installs(&dest, &good, &digest, &mut never);
check_missing_local_file(&dir, &digest, &mut never);
let _ = std::fs::remove_dir_all(dir);
}
fn check_good_local_file_installs(
dest: &Path,
good: &Path,
digest: &str,
never: &mut impl FnMut(&str, &Path) -> Result<(), String>,
) {
let outcome = provision(
&Request {
dest: &dest,
expected: &digest,
local: Some(&good),
dest,
expected: digest,
local: Some(good),
embedded: None,
sources: &["https://x.test/p"],
},
&mut never,
never,
)
.unwrap();
assert!(matches!(
@@ -131,9 +148,7 @@ fn a_local_file_is_installed_offline_and_a_wrong_one_is_refused() {
..
}
));
assert_eq!(std::fs::read(&dest).unwrap(), FIXTURE);
check_missing_local_file(&dir, &digest, &mut never);
let _ = std::fs::remove_dir_all(dir);
assert_eq!(std::fs::read(dest).unwrap(), FIXTURE);
}
fn check_wrong_local_file_is_refused(
+10 -6
View File
@@ -175,11 +175,8 @@ mod tests {
assert!(parse_response(b"SMTP/1.0 200\r\n\r\n").is_err());
}
#[tokio::test]
async fn gets_json_from_a_local_listener_and_sends_the_bearer_header() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
fn serve_one_ready_response(listener: TcpListener) -> tokio::task::JoinHandle<String> {
tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buffer = vec![0u8; 2048];
let count = stream.read(&mut buffer).await.unwrap();
@@ -196,7 +193,14 @@ mod tests {
.await
.unwrap();
request
});
})
}
#[tokio::test]
async fn gets_json_from_a_local_listener_and_sends_the_bearer_header() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = serve_one_ready_response(listener);
let response = get(address, "/ready", Some("tok-123"), Duration::from_secs(5))
.await
.unwrap();
+9 -5
View File
@@ -210,13 +210,18 @@ mod tests {
}
}
assert!(total > 50_000);
check_generations_hold_whole_lines_in_order(&p, policy);
std::fs::remove_dir_all(d).unwrap();
}
fn check_generations_hold_whole_lines_in_order(p: &Path, policy: Policy) {
// Generations exist, are bounded, hold whole lines, and the newest generation ends before the live file starts.
let first = std::fs::read_to_string(generation(&p, 1)).unwrap();
let first = std::fs::read_to_string(generation(p, 1)).unwrap();
assert!(first.len() as u64 <= policy.limit);
assert!(first.lines().all(|l| l.starts_with("line ")), "{first:?}");
assert!(generation(&p, 2).exists());
assert!(!generation(&p, 3).exists());
let live = std::fs::read_to_string(&p).unwrap();
assert!(generation(p, 2).exists());
assert!(!generation(p, 3).exists());
let live = std::fs::read_to_string(p).unwrap();
let last_of_first: u32 = first.lines().last().unwrap()[5..10].parse().unwrap();
if let Some(first_live) = live.lines().next() {
let n: u32 = first_live[5..10].parse().unwrap();
@@ -224,7 +229,6 @@ mod tests {
}
// The very last line is in the live file or the newest generation.
assert!(live.contains("line 01999") || first.contains("line 01999"));
std::fs::remove_dir_all(d).unwrap();
}
#[test]
+21 -9
View File
@@ -215,6 +215,10 @@ fn since_takes_durations_and_times() {
parse_utc_ms("2026-11-02T08:00:00Z").unwrap()
);
assert!(parse_since("yesterday", now).is_err());
check_filter_refusals(now);
}
fn check_filter_refusals(now: u64) {
assert!(
filter_from(
&LogsArgs {
@@ -290,9 +294,7 @@ fn the_report_holds_no_secret_no_text_and_no_home_directory() {
assert!(text.len() < 8 * 1024, "{} bytes", text.len());
}
#[test]
fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() {
let dir = scratch("report");
fn report_options_with_one_request(dir: &Path) -> crate::cli::UpOptions {
let state = dir.join("state");
std::fs::create_dir_all(state.join("logs")).unwrap();
std::fs::write(
@@ -305,10 +307,16 @@ fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() {
.unwrap();
let dirs = crate::layout::Dirs {
prefix: dir.join("prefix"),
state: state.clone(),
state,
assets: dir.join("assets"),
};
let opts = crate::cli::tests_options(dirs);
crate::cli::tests_options(dirs)
}
#[test]
fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() {
let dir = scratch("report");
let opts = report_options_with_one_request(&dir);
let out = dir.join("out.json");
let without_opt_in = ReportArgs {
out: Some(out.display().to_string()),
@@ -329,10 +337,7 @@ fn the_report_is_written_only_with_the_opt_in_and_never_over_a_network() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_status_line_summarises_the_last_quarter_hour() {
let dir = scratch("statusline");
let now = now_ms();
fn write_three_recent_requests(dir: &Path, now: u64) {
let line = |i: u64, fin: &str| {
api_line(
&format!("req-{i}"),
@@ -352,6 +357,13 @@ fn the_status_line_summarises_the_last_quarter_hour() {
),
)
.unwrap();
}
#[test]
fn the_status_line_summarises_the_last_quarter_hour() {
let dir = scratch("statusline");
let now = now_ms();
write_three_recent_requests(&dir, now);
let text = recent_requests_line(&dir, now).unwrap();
assert!(
text.contains("3 in the last 15 min (1 failed)")
+21 -13
View File
@@ -34,16 +34,32 @@ fn options(extra: &[&str]) -> UpOptions {
}
}
fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context {
let paths = opts.dirs.paths();
let gpu = Gpu {
fn test_gpu(gpu_name: &str, sm: u32) -> Gpu {
Gpu {
index: 0,
name: gpu_name.into(),
driver: "595.99.02".into(),
vram_total_mib: if sm == 120 { 32607 } else { 16384 },
vram_free_mib: if sm == 120 { 32000 } else { 15500 },
sm: Some(sm),
};
}
}
fn run_config_of(profile: &Result<Profile, String>, opts: &UpOptions) -> Option<RunConfig> {
profile.as_ref().ok().map(|p| {
RunConfig::new(
&opts.dirs,
opts.ports.clone(),
0,
p.clone(),
BTreeMap::new(),
)
})
}
fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context {
let paths = opts.dirs.paths();
let gpu = test_gpu(gpu_name, sm);
let facts = finished_host(gpu.clone());
let profile = resolve(opts.profile.as_deref(), Some(&gpu));
let expert_profile = expert_state(&profile, &opts);
@@ -53,15 +69,7 @@ fn context(opts: UpOptions, mode: Mode, gpu_name: &str, sm: u32) -> Context {
expert_profile,
..Needs::default()
};
let config = profile.as_ref().ok().map(|p| {
RunConfig::new(
&opts.dirs,
opts.ports.clone(),
0,
p.clone(),
BTreeMap::new(),
)
});
let config = run_config_of(&profile, &opts);
let report = profile.as_ref().ok().map(|p| evaluate(&facts, p, &needs));
Context {
service_user: "leleka".into(),
@@ -50,6 +50,10 @@ fn the_expert_profile_step_covers_every_state_and_never_stays_silent() {
matches!(&local, StepState::Todo(why) if why.contains("/mnt/usb/expert-profile.bin")),
"{local:?}"
);
check_a_wrong_digest_is_blocked_or_replaced_and_the_opt_out_skips();
}
fn check_a_wrong_digest_is_blocked_or_replaced_and_the_opt_out_skips() {
// a file with another digest is never used silently: blocked, or replaced (moved aside) on request
let wrong = expert_step(&[], ExpertProfileState::WrongDigest);
assert!(
@@ -128,8 +132,12 @@ fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() {
with_tier.needs.expert_profile,
Some(ExpertProfileState::Absent)
);
check_the_opt_out_is_recorded(&gathered(&["--no-expert-tier"]));
let _ = std::fs::remove_dir_all(dir);
}
fn check_the_opt_out_is_recorded(without: &Context) {
// The opt-out leaves the switches out and is recorded, so `status` can say "explicit opt-out".
let without = gathered(&["--no-expert-tier"]);
let config = without.config.as_ref().unwrap();
assert!(
!config.expert_tier
@@ -141,7 +149,6 @@ fn the_gathered_environment_names_the_table_unless_the_tier_is_opted_out() {
without.needs.expert_profile,
Some(ExpertProfileState::OptedOut)
);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
+14 -2
View File
@@ -60,7 +60,11 @@ fn fresh_server_plans_every_step() {
state_of(&steps, id)
);
}
let text = render_plan(&ctx, &steps).replace('\\', "/");
check_the_plan_text_names_the_derivation(&ctx, &steps);
}
fn check_the_plan_text_names_the_derivation(ctx: &Context, steps: &[Step]) {
let text = render_plan(ctx, steps).replace('\\', "/");
let derive = concat!(
"model ensure-sharded-streamed qwen-iq3-s --source-dir /data/leleka/model ",
"--output /data/leleka/qwen-iq3-s-l2-v4.kar --levels 2"
@@ -136,6 +140,10 @@ fn the_archive_step_covers_the_shards_and_trust_archive_does_not() {
.why()
.contains("inside the archive step")
);
check_trusting_needs_an_archive_to_trust();
}
fn check_trusting_needs_an_archive_to_trust() {
let trusted = context(
options(&["--trust-archive"]),
Mode::Foreground,
@@ -156,9 +164,13 @@ fn the_archive_step_covers_the_shards_and_trust_archive_does_not() {
.contains("inside the archive step")
);
assert!(state_of(&steps, "kar").why().contains("--trust-archive"));
check_trusting_without_an_archive_trusts_nothing(&trusted);
}
fn check_trusting_without_an_archive_trusts_nothing(trusted: &Context) {
// Trusting needs an archive to trust.
let steps = plan_steps(
&trusted,
trusted,
&FsState {
binaries_source_ok: true,
..FsState::default()
+18 -14
View File
@@ -15,23 +15,27 @@ fn mode_resolution() {
Mode::Systemd(UnitScopeTag::System)
);
facts.root = false;
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, true),
Mode::Systemd(UnitScopeTag::User)
);
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, false),
Mode::Foreground
);
facts.systemd_system = false;
assert_eq!(
resolve_mode(ModeChoice::Auto, &facts, true),
Mode::Foreground
);
assert_eq!(resolve_mode(ModeChoice::None, &facts, true), Mode::None);
check_user_and_foreground_choices(&mut facts);
let _ = Dirs {
prefix: "/".into(),
state: "/".into(),
assets: "/".into(),
};
}
fn check_user_and_foreground_choices(facts: &mut Facts) {
assert_eq!(
resolve_mode(ModeChoice::Auto, facts, true),
Mode::Systemd(UnitScopeTag::User)
);
assert_eq!(
resolve_mode(ModeChoice::Auto, facts, false),
Mode::Foreground
);
facts.systemd_system = false;
assert_eq!(
resolve_mode(ModeChoice::Auto, facts, true),
Mode::Foreground
);
assert_eq!(resolve_mode(ModeChoice::None, facts, true), Mode::None);
}
@@ -2,9 +2,7 @@
use super::*;
#[test]
fn laptop_under_default_wsl_memory_gets_wslconfig_advice() {
let profile = Profile::builtin("rtx3080-16g").unwrap();
fn wsl_laptop_with_12_gib() -> Facts {
let mut facts = server_facts();
facts.wsl = true;
facts.gpus[0] = Gpu {
@@ -20,6 +18,13 @@ fn laptop_under_default_wsl_memory_gets_wslconfig_advice() {
available: 9 * GIB,
swap_total: 0,
};
facts
}
#[test]
fn laptop_under_default_wsl_memory_gets_wslconfig_advice() {
let profile = Profile::builtin("rtx3080-16g").unwrap();
let mut facts = wsl_laptop_with_12_gib();
let mut n = needs();
n.binary_has_sm86 = Some(true);
let report = evaluate(&facts, &profile, &n);
@@ -69,6 +69,14 @@ fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd()
assert_eq!(level_of(&report, "platform"), Level::Pass);
assert_eq!(level_of(&report, "gpu"), Level::Pass);
assert_eq!(level_of(&report, "memfd"), Level::Pass);
check_present_dlls_pass_and_the_server_profile_needs_memfd(&mut facts, &profile, &needs);
}
fn check_present_dlls_pass_and_the_server_profile_needs_memfd(
facts: &mut Facts,
profile: &Profile,
needs: &Needs,
) {
facts.libs.insert(
"libcublas.so.12".into(),
Some("C:/cuda/cublas64_12.dll".into()),
@@ -81,11 +89,11 @@ fn a_windows_laptop_is_judged_natively_with_dll_names_and_no_systemd_or_memfd()
"libcuda.so.1".into(),
Some("C:/Windows/System32/nvcuda.dll".into()),
);
let report = evaluate(&facts, &profile, &needs);
let report = evaluate(facts, profile, needs);
assert!(!report.failed(), "{}", report.render());
// The server profile holds the archive in a sealed memfd: refused with the reason.
let server = Profile::builtin("rtx5090-32g").unwrap();
let report = evaluate(&facts, &server, &needs);
let report = evaluate(facts, &server, needs);
assert_eq!(level_of(&report, "memfd"), Level::Fail);
assert!(
report
@@ -25,6 +25,10 @@ fn the_builtin_profiles_carry_the_memory_budget_into_engine_arguments_and_enviro
assert_eq!(env["LELEKA_MEMORY_SOFT_FLOOR_MIB"], "4096");
assert_eq!(env["LELEKA_MEMORY_HARD_FLOOR_MIB"], "2048");
assert_eq!(env["LELEKA_MEMORY_LOCK"], "try");
check_the_laptop_archive_is_a_file_and_every_builtin_validates();
}
fn check_the_laptop_archive_is_a_file_and_every_builtin_validates() {
let laptop = Profile::builtin("rtx3080-16g").unwrap();
assert_eq!(
laptop.memory.env()["LELEKA_MEMORY_LOCK"],
@@ -52,6 +56,11 @@ fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_
// a cache that fits the cap with room to spare: 245k tokens x 14,208 B + ~4 nodes of ~127 MiB is about 4 GiB
let session_245k = 245_000u64 * 14_208 + 4 * (127 << 20);
assert!(session_245k < 6144 << 20, "{session_245k}");
check_only_an_explicit_nonzero_value_is_a_cap(&server);
check_the_memfd_profiles_keep_an_explicit_cap();
}
fn check_only_an_explicit_nonzero_value_is_a_cap(server: &Profile) {
// `auto`, `0`, off and unset are not caps
for (value, cap) in [
(Some("auto"), None),
@@ -63,6 +72,9 @@ fn the_5090_profile_carries_an_explicit_prefix_cap_so_freed_ram_cannot_grow_the_
memory.prefix_cache_mib = value.map(str::to_owned);
assert_eq!(memory.prefix_cache_cap_mib(), cap, "{value:?}");
}
}
fn check_the_memfd_profiles_keep_an_explicit_cap() {
// the dedicated memfd profile must keep an explicit cap; the laptop (file archive, mapped experts) is a different machine
for profile in Profile::builtins()
.iter()
+39 -31
View File
@@ -103,39 +103,47 @@ fn a_sparse_memfd_holds_a_third_of_the_archive_and_lowers_the_ram_the_profile_as
#[test]
fn the_extents_pin_is_the_compiled_one_or_an_explicit_operator_value_and_never_silent() {
let none = |_: &str| None;
let with = |value: &str| {
let value = value.to_owned();
move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone())
};
let hex64 = "ab".repeat(32);
let zeros = "00".repeat(32);
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
if compiled == [0u8; 32] {
// not measured yet: the sparse form refuses to start without an explicit value, and says how to get one
let error = extents_sha256(&none).unwrap_err();
assert!(
error.contains("kar_census") && error.contains("--hash-extents"),
"{error}"
);
assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex"));
assert!(
extents_sha256(&with("abcd"))
.unwrap_err()
.contains("64 hex")
);
assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero"));
let (pin, source) = extents_sha256(&with(&hex64)).unwrap();
assert_eq!((pin, source), ([0xab; 32], PinSource::Operator));
check_an_unmeasured_pin_needs_an_explicit_value();
} else {
// measured: the binary's value wins and an environment value cannot override it
assert_eq!(
extents_sha256(&none).unwrap(),
(compiled, PinSource::Compiled)
);
assert_eq!(
extents_sha256(&with(&hex64)).unwrap(),
(compiled, PinSource::Compiled)
);
check_a_measured_pin_wins_over_the_environment(compiled);
}
}
fn pin_environment(value: &str) -> impl Fn(&str) -> Option<String> {
let value = value.to_owned();
move |key: &str| (key == "LELEKA_KAR_EXTENTS_SHA256").then(|| value.clone())
}
fn check_an_unmeasured_pin_needs_an_explicit_value() {
// not measured yet: the sparse form refuses to start without an explicit value, and says how to get one
let with = pin_environment;
let error = extents_sha256(&|_: &str| None).unwrap_err();
assert!(
error.contains("kar_census") && error.contains("--hash-extents"),
"{error}"
);
assert!(extents_sha256(&with("zz")).unwrap_err().contains("64 hex"));
assert!(
extents_sha256(&with("abcd"))
.unwrap_err()
.contains("64 hex")
);
let zeros = "00".repeat(32);
assert!(extents_sha256(&with(&zeros)).unwrap_err().contains("zero"));
let (pin, source) = extents_sha256(&with(&"ab".repeat(32))).unwrap();
assert_eq!((pin, source), ([0xab; 32], PinSource::Operator));
}
fn check_a_measured_pin_wins_over_the_environment(compiled: [u8; 32]) {
// measured: the binary's value wins and an environment value cannot override it
assert_eq!(
extents_sha256(&|_: &str| None).unwrap(),
(compiled, PinSource::Compiled)
);
assert_eq!(
extents_sha256(&pin_environment(&"ab".repeat(32))).unwrap(),
(compiled, PinSource::Compiled)
);
}
+14
View File
@@ -63,6 +63,20 @@ fn big_host() -> Facts {
host(32, 121, 100, vec![gpu(32607, 32100)])
}
/// `plan` on the big server host with the archive resident, for a budget and a preset and no other setting.
fn plan_on_big_host(
config: &RunConfig,
budget: Option<u64>,
preset: Option<Preset>,
) -> Result<Planned, String> {
plan(
config,
&request(budget, preset, json!({})),
&big_host(),
true,
)
}
mod planning;
mod recording;
mod settings_ranges;
+18 -65
View File
@@ -5,13 +5,7 @@ use super::*;
#[test]
fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() {
let config = server_config();
let planned = plan(
&config,
&request(Some(24), None, json!({})),
&big_host(),
true,
)
.unwrap();
let planned = plan_on_big_host(&config, Some(24), None).unwrap();
assert!(!planned.unchanged);
assert_eq!(planned.config.profile.gpu_budget_bytes, 24 * GIB);
assert_eq!(
@@ -28,41 +22,30 @@ fn a_budget_change_is_planned_against_the_host_and_keeps_everything_else() {
config.profile.context_tokens
);
assert_eq!(planned.config.preset, Preset::Dedicated);
let args = planned
.config
.engine_args(crate::config::KarArg::Fd)
.join(" ");
check_the_budget_reaches_the_engine_args(&planned.config);
check_same_budget_is_a_noop(&planned.config);
}
fn check_the_budget_reaches_the_engine_args(planned: &RunConfig) {
let args = planned.engine_args(crate::config::KarArg::Fd).join(" ");
assert!(
args.contains(&format!("--gpu-budget {}", 24 * GIB)),
"{args}"
);
check_same_budget_is_a_noop(&planned.config);
}
/// The same budget again is a no-op, not a five-minute restart
/// (the shipped 5090 budget is 31,299 MiB, which a whole-GiB request cannot restate: the no-op is checked on the 24
/// GiB just planned).
fn check_same_budget_is_a_noop(planned: &RunConfig) {
let same = plan(
planned,
&request(Some(24), None, json!({})),
&big_host(),
true,
)
.unwrap();
let same = plan_on_big_host(planned, Some(24), None).unwrap();
assert!(same.unchanged, "the profile already has a 24 GiB budget");
}
#[test]
fn the_workstation_preset_applies_and_dedicated_undoes_it() {
let config = server_config();
let to_workstation = plan(
&config,
&request(None, Some(Preset::Workstation), json!({})),
&big_host(),
true,
)
.unwrap();
let to_workstation = plan_on_big_host(&config, None, Some(Preset::Workstation)).unwrap();
let ws = &to_workstation.config;
assert_eq!(ws.preset, Preset::Workstation);
assert_eq!(
@@ -76,23 +59,15 @@ fn the_workstation_preset_applies_and_dedicated_undoes_it() {
Some("15")
);
// back: the unmodified profile is restored from the recorded base
let back = plan(
ws,
&request(None, Some(Preset::Dedicated), json!({})),
&big_host(),
true,
)
.unwrap();
let back = plan_on_big_host(ws, None, Some(Preset::Dedicated)).unwrap();
assert_eq!(back.config.profile, config.profile);
assert_eq!(back.config.preset, Preset::Dedicated);
check_an_explicit_budget_wins_with_the_workstation_preset(&config);
}
fn check_an_explicit_budget_wins_with_the_workstation_preset(config: &RunConfig) {
// `--gpu-budget-gib N --preset workstation`: the explicit budget is what the engine gets, if the preset allows it
let both = plan(
&config,
&request(Some(24), Some(Preset::Workstation), json!({})),
&big_host(),
true,
)
.unwrap();
let both = plan_on_big_host(config, Some(24), Some(Preset::Workstation)).unwrap();
assert_eq!(both.config.profile.gpu_budget_bytes, 24 * GIB);
assert_eq!(both.config.preset, Preset::Workstation);
assert_eq!(both.config.profile.memory.soft_floor_mib, Some(16384));
@@ -103,34 +78,12 @@ fn an_old_installation_without_a_recorded_base_cannot_undo_the_workstation_prese
let mut config = server_config();
config.base_profile = None;
config.preset = Preset::Workstation;
let error = plan(
&config,
&request(None, Some(Preset::Dedicated), json!({})),
&big_host(),
true,
)
.unwrap_err();
let error = plan_on_big_host(&config, None, Some(Preset::Dedicated)).unwrap_err();
assert!(error.contains("leleka up --preset dedicated"), "{error}");
// staying on workstation, or going to it from dedicated, works without a base
assert!(
plan(
&config,
&request(Some(20), None, json!({})),
&big_host(),
true
)
.is_ok()
);
assert!(plan_on_big_host(&config, Some(20), None).is_ok());
config.preset = Preset::Dedicated;
assert!(
plan(
&config,
&request(None, Some(Preset::Workstation), json!({})),
&big_host(),
true
)
.is_ok()
);
assert!(plan_on_big_host(&config, None, Some(Preset::Workstation)).is_ok());
}
#[test]
@@ -4,14 +4,9 @@ use super::*;
#[test]
fn recording_settings_updates_the_profile_and_the_base_and_lets_an_explicit_worker_count_win() {
let mut config = plan(
&server_config(),
&request(None, Some(Preset::Workstation), json!({})),
&big_host(),
true,
)
.unwrap()
.config;
let mut config = plan_on_big_host(&server_config(), None, Some(Preset::Workstation))
.unwrap()
.config;
assert_eq!(
config.engine_env.get(CPU_WORKERS_ENV).map(String::as_str),
Some("15")
@@ -160,21 +160,46 @@ fn the_prefix_cache_can_be_switched_off_and_a_member_alone_turns_it_on() {
);
}
/// The refusal `plan` gives for a request on the server configuration, the archive being resident.
fn refused(request: Request, facts: &Facts) -> String {
plan(&server_config(), &request, facts, true).unwrap_err()
}
#[test]
fn unsafe_values_are_refused_by_the_planner() {
let config = server_config();
let refused = |request: Request, facts: &Facts, resident: bool| {
plan(&config, &request, facts, resident).unwrap_err()
};
check_budgets_beyond_the_card_or_the_range_are_refused();
check_a_busy_card_is_refused_only_once_the_engine_is_stopped();
check_the_workstation_preset_never_shrinks_silently();
// a bad runtime setting riding along refuses the whole request
assert!(
refused(
request(Some(24), None, json!({"cpu_workers": 99})),
&big_host()
)
.contains("cpu_workers")
);
// a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form
let small = host(32, 64, 10, vec![gpu(32607, 32100)]);
let error = refused(request(None, Some(Preset::Workstation), json!({})), &small);
assert!(
error.contains("file-backed form") || error.contains("leleka up"),
"{error}"
);
}
fn check_budgets_beyond_the_card_or_the_range_are_refused() {
// more than the card has
let error = refused(request(Some(40), None, json!({})), &big_host(), true);
let error = refused(request(Some(40), None, json!({})), &big_host());
assert!(error.contains("does not fit the 32607 MiB"), "{error}");
// not a budget at all
assert!(refused(request(Some(0), None, json!({})), &big_host(), true).contains("1..1024"));
assert!(refused(request(Some(5000), None, json!({})), &big_host(), true).contains("1..1024"));
assert!(refused(request(Some(0), None, json!({})), &big_host()).contains("1..1024"));
assert!(refused(request(Some(5000), None, json!({})), &big_host()).contains("1..1024"));
}
fn check_a_busy_card_is_refused_only_once_the_engine_is_stopped() {
// another process holds the card (checked once the engine is stopped)
let busy = host(32, 121, 100, vec![gpu(32607, 9000)]);
let error = refused(request(Some(24), None, json!({})), &busy, true);
let error = refused(request(Some(24), None, json!({})), &busy);
assert!(
error.contains("9000 MiB free") && error.contains("needs"),
"{error}"
@@ -182,46 +207,24 @@ fn unsafe_values_are_refused_by_the_planner() {
// the optimistic view, used before the engine is stopped, does not charge the engine's own VRAM
assert!(
plan(
&config,
&server_config(),
&request(Some(24), None, json!({})),
&optimistic(&busy),
true
)
.is_ok()
);
}
fn check_the_workstation_preset_never_shrinks_silently() {
// the workstation preset on a card that is mostly taken is a problem, not a silent shrink
let taken = host(32, 121, 100, vec![gpu(32607, 12000)]);
let error = refused(
request(None, Some(Preset::Workstation), json!({})),
&taken,
true,
);
let error = refused(request(None, Some(Preset::Workstation), json!({})), &taken);
assert!(error.contains("workstation preset"), "{error}");
// an explicit budget the preset cannot give
let error = refused(
request(Some(30), Some(Preset::Workstation), json!({})),
&big_host(),
true,
);
assert!(error.contains("asks for more"), "{error}");
// a bad runtime setting riding along refuses the whole request
assert!(
refused(
request(Some(24), None, json!({"cpu_workers": 99})),
&big_host(),
true
)
.contains("cpu_workers")
);
// a host too small to keep the sealed archive and the preset's free memory: refused rather than switched to the file form
let small = host(32, 64, 10, vec![gpu(32607, 32100)]);
let error = refused(
request(None, Some(Preset::Workstation), json!({})),
&small,
true,
);
assert!(
error.contains("file-backed form") || error.contains("leleka up"),
"{error}"
);
}
+5
View File
@@ -37,6 +37,11 @@ fn laptop() -> Profile {
Profile::builtin("rtx3080-16g").unwrap()
}
/// The plan of the full-copy server profile on the 5090 with 32100 MiB free.
fn server_plan(facts: &Facts, preset: Preset) -> ResourcePlan {
compute(facts, Some(&gpu(32607, 32100)), &server(), preset)
}
mod presets_and_workers;
mod ram_fit;
mod windows_presets;
@@ -29,13 +29,12 @@ fn the_prompt_chunk_follows_what_the_gpu_budget_can_lend() {
assert_eq!(apply_with(15), (Some(6144), Some(6144)));
assert_eq!(apply_with(12), (Some(3072), Some(3072)));
assert_eq!(apply_with(10), (Some(2048), Some(2048)));
check_the_server_profile_keeps_its_8192();
}
fn check_the_server_profile_keeps_its_8192() {
let mut server = server();
let plan = compute(
&host(32, 121, 100),
Some(&gpu(32607, 32100)),
&server,
Preset::Dedicated,
);
let plan = server_plan(&host(32, 121, 100), Preset::Dedicated);
apply(&plan, &mut server, &mut BTreeMap::new(), false);
assert_eq!(server.prefill_capacity, Some(8192));
}
@@ -54,16 +53,14 @@ fn workers_never_exceed_the_physical_cores_but_the_hosts_where_those_are_known()
Some(12),
"physical cores unknown: unchanged"
);
check_the_16_core_server_and_a_small_host();
}
fn check_the_16_core_server_and_a_small_host() {
let mut server_host = host(32, 121, 100);
server_host.cpu_physical_cores = 16;
assert_eq!(
compute(
&server_host,
Some(&gpu(32607, 32100)),
&server(),
Preset::Dedicated
)
.cpu_workers,
server_plan(&server_host, Preset::Dedicated).cpu_workers,
Some(15),
"the 16-core server is unchanged"
);
+17 -29
View File
@@ -56,38 +56,27 @@ fn check_fallback_drops_the_sparse_switch(sparse: &Profile, gpu: &crate::facts::
fn a_resident_sealed_archive_is_not_charged_to_the_footprint_twice() {
// the server with the 51.5 GiB memfd already resident: 121 GiB total, 66 GiB available (what the supervisor sees before the engine starts)
let resident = host(32, 121, 66);
let charged_twice = compute(
&resident,
Some(&gpu(32607, 32100)),
&server(),
Preset::Dedicated,
);
let charged_twice = server_plan(&resident, Preset::Dedicated);
assert!(
charged_twice.mapped_resident_gib.is_some(),
"without the correction the pinned form looks impossible"
);
let corrected = compute(
&with_resident_archive(&resident),
Some(&gpu(32607, 32100)),
&server(),
Preset::Dedicated,
);
let corrected = server_plan(&with_resident_archive(&resident), Preset::Dedicated);
assert_eq!(
corrected.mapped_resident_gib, None,
"the archive is already paid for: the engine's 54 GiB fit next to the 4 GiB target and the 2 GiB reserve"
);
assert!(corrected.ram_expected_free_after_bytes.is_some());
check_a_host_lacking_the_engine_memory_is_mapped_and_the_credit_saturates();
}
fn check_a_host_lacking_the_engine_memory_is_mapped_and_the_credit_saturates() {
// a host that really lacks the engine's own memory is still sent to the mapped form
let tiny = host(32, 121, 2);
assert!(
compute(
&with_resident_archive(&tiny),
Some(&gpu(32607, 32100)),
&server(),
Preset::Dedicated
)
.mapped_resident_gib
.is_some()
server_plan(&with_resident_archive(&tiny), Preset::Dedicated)
.mapped_resident_gib
.is_some()
);
// saturating, not wrapping
assert!(
@@ -116,18 +105,17 @@ fn the_file_form_of_the_server_profile_is_charged_the_engine_only_not_the_archiv
assert_eq!(plan.ram_expected_free_after_bytes, Some(46 * GIB));
// the same host is already too small for the memfd profile once it has to create the archive copy
assert!(
compute(
&host(32, 121, 100),
Some(&gpu(32607, 32100)),
&server(),
Preset::Dedicated
)
.mapped_resident_gib
.is_some()
server_plan(&host(32, 121, 100), Preset::Dedicated)
.mapped_resident_gib
.is_some()
);
check_a_host_that_cannot_hold_the_bank_is_mapped(&file);
}
fn check_a_host_that_cannot_hold_the_bank_is_mapped(file: &Profile) {
// a host that cannot hold the bank is sent to the mapped form, and the warning does not claim the archive moves
let small = host(32, 64, 50);
let plan = compute(&small, Some(&gpu(32607, 32100)), &file, Preset::Dedicated);
let plan = compute(&small, Some(&gpu(32607, 32100)), file, Preset::Dedicated);
assert!(plan.mapped_resident_gib.is_some());
assert!(
plan.warnings[0].contains("the experts are served from disk")
@@ -70,9 +70,14 @@ fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors()
"the workstation floors are not lowered to the dedicated Windows values"
);
assert_eq!(plan.mapped_working_set_gib, Some(8));
check_the_applied_floors_and_working_set(&plan);
check_dedicated_preset_is_unchanged(&windows);
}
fn check_the_applied_floors_and_working_set(plan: &ResourcePlan) {
let mut profile = laptop();
let mut env = BTreeMap::new();
apply(&plan, &mut profile, &mut env, false);
apply(plan, &mut profile, &mut env, false);
assert_eq!(
profile.memory.soft_floor_mib,
Some(8 * 1024),
@@ -83,7 +88,6 @@ fn the_windows_workstation_preset_leaves_the_desktop_more_and_keeps_its_floors()
env.get(MAPPED_WORKING_SET_ENV).map(String::as_str),
Some("8")
);
check_dedicated_preset_is_unchanged(&windows);
}
fn check_dedicated_preset_is_unchanged(windows: &Facts) {
+41 -22
View File
@@ -27,14 +27,22 @@ fn seal_is_exact_sealed_unlinked_and_cloexec() {
calls.last(),
Some(&(payload.len() as u64, payload.len() as u64))
);
check_a_reopened_descriptor_keeps_the_checked_properties(&sealed, &path, payload.len());
std::fs::remove_file(path).unwrap();
}
fn check_a_reopened_descriptor_keeps_the_checked_properties(
sealed: &File,
path: &Path,
length: usize,
) {
// A descriptor reopened through /proc keeps the properties the engine checks.
let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32;
let number = std::os::fd::AsRawFd::as_raw_fd(sealed) as u32;
let reopened = open_inherited(number).unwrap();
let meta = reopened.metadata().unwrap();
assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64);
assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err());
assert!(meta.nlink() == 0 && meta.len() == length as u64);
assert!(seal_file(path, Some(1), &mut |_, _| {}).is_err());
assert!(open_inherited(1).is_err());
std::fs::remove_file(path).unwrap();
}
#[test]
@@ -64,20 +72,28 @@ fn blocks_bytes(f: &File) -> u64 {
f.metadata().unwrap().blocks() * 512
}
fn sparse_test_payload(size: usize) -> Vec<u8> {
(0..size)
.map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1)
.collect()
}
fn sparse_test_extents() -> [Extent; 3] {
[
Extent::new(0, 8192),
Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096),
Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77),
]
}
#[test]
fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() {
let path = std::env::temp_dir().join(format!("leleka-sparse-{}", std::process::id()));
// Two full chunks and a bit, so extents span and split across the 32 MiB pieces.
let size = COPY_CHUNK * 2 + 4096 * 5 + 77;
let payload: Vec<u8> = (0..size)
.map(|n| (((n / 4096) as u8).wrapping_mul(31) ^ (n as u8)) | 1)
.collect();
let payload = sparse_test_payload(size);
std::fs::write(&path, &payload).unwrap();
let extents = [
Extent::new(0, 8192),
Extent::new(COPY_CHUNK as u64 - 4096, 3 * 4096),
Extent::new(COPY_CHUNK as u64 * 2 + 4096 * 3, 4096 * 2 + 77),
];
let extents = sparse_test_extents();
let want: u64 = extents.iter().map(|e| e.len).sum();
let mut calls = Vec::new();
let (mut sealed, identity) = seal_extents(&path, Some(size as u64), &extents, &mut |a, b| {
@@ -95,13 +111,20 @@ fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() {
assert!(meta.nlink() == 0 && meta.len() == size as u64);
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
check_only_the_extents_are_allocated_and_hold_the_source_bytes(&sealed, &extents, &payload);
std::fs::remove_file(path).unwrap();
}
fn check_only_the_extents_are_allocated_and_hold_the_source_bytes(
sealed: &File,
extents: &[Extent],
payload: &[u8],
) {
let size = payload.len();
// only the extents were allocated: pages of data, no page for any hole
let pages = |e: &Extent| (e.end().div_ceil(4096) - e.offset / 4096) * 4096;
assert_eq!(
blocks_bytes(&sealed),
extents.iter().map(pages).sum::<u64>()
);
assert!(blocks_bytes(&sealed) < size as u64 / 4);
assert_eq!(blocks_bytes(sealed), extents.iter().map(pages).sum::<u64>());
assert!(blocks_bytes(sealed) < size as u64 / 4);
// extents hold the source's bytes at the same offsets; holes read as zeros
let mut copy = vec![0u8; size];
sealed.read_exact_at(&mut copy, 0).unwrap();
@@ -116,11 +139,7 @@ fn a_sparse_seal_copies_only_the_extents_keeps_every_offset_and_leaves_holes() {
);
}
// reading the holes did not allocate them either
assert_eq!(
blocks_bytes(&sealed),
extents.iter().map(pages).sum::<u64>()
);
std::fs::remove_file(path).unwrap();
assert_eq!(blocks_bytes(sealed), extents.iter().map(pages).sum::<u64>());
}
#[test]
+7 -3
View File
@@ -70,6 +70,12 @@ fn provisions_the_pinned_table_from_upstream() {
assert_eq!(file_state(&dest, PINNED_SHA256), FileState::Valid);
assert_eq!(std::fs::metadata(&dest).unwrap().len(), PINNED_BYTES);
assert!(!dest.with_extension("bin.part").exists());
check_a_source_answering_something_else_fails_closed(&dir, tool, &log);
std::fs::remove_dir_all(dir).unwrap();
}
fn check_a_source_answering_something_else_fails_closed(dir: &Path, tool: &str, log: &Path) {
use crate::expert_profile::{PINNED_SHA256, Request, provision};
// A source that answers with something else fails closed: an https URL that is not the table.
let other = dir.join("other.bin");
let bad = Request {
@@ -81,13 +87,11 @@ fn provisions_the_pinned_table_from_upstream() {
"https://raw.githubusercontent.com/Niko1221/Strata/41cf05a06a25dd29103b7b27a2279a3f60c21876/LICENSE",
],
};
let error =
provision(&bad, &mut |url, part| download_small(tool, url, part, &log)).unwrap_err();
let error = provision(&bad, &mut |url, part| download_small(tool, url, part, log)).unwrap_err();
assert!(
error.contains("is not the expected") && !other.exists(),
"{error}"
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
+4
View File
@@ -38,6 +38,10 @@ fn operation_records_are_parsed_from_the_cli_output() {
Some(3)
);
assert_eq!(parse_operation_state("Error: x"), None);
check_the_tail_of_a_log();
}
fn check_the_tail_of_a_log() {
let dir = std::env::temp_dir().join(format!("leleka-tail-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
+4
View File
@@ -227,6 +227,10 @@ mod tests {
dog.observe(at(base, 110), &metrics(true, None)),
Verdict::Healthy
);
check_the_clock_restarts_after_recovery(base, &mut dog);
}
fn check_the_clock_restarts_after_recovery(base: Instant, dog: &mut Watchdog) {
// After recovery the 120 s count starts again.
assert!(matches!(
dog.observe(at(base, 120), &metrics(false, None)),
+24 -22
View File
@@ -51,15 +51,23 @@ fn dry_run_prints_the_plan_and_changes_nothing() {
stderr.contains("preflight (profile rtx5090-32g)"),
"{stderr}"
);
assert_no_directory_exists(&fixture, "--dry-run created");
check_json_is_one_document_with_the_steps(&fixture, &bin);
}
fn assert_no_directory_exists(fixture: &Fixture, what: &str) {
for path in [
&fixture.dirs.assets,
&fixture.dirs.state,
&fixture.dirs.prefix,
] {
assert!(!path.exists(), "--dry-run created {}", path.display());
assert!(!path.exists(), "{what} {}", path.display());
}
}
fn check_json_is_one_document_with_the_steps(fixture: &Fixture, bin: &std::path::Path) {
// --json is one parseable document with the steps.
let output = dry_run(&fixture, &bin, &["--json"]);
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!(
@@ -71,13 +79,9 @@ fn dry_run_prints_the_plan_and_changes_nothing() {
);
}
#[test]
fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
let fixture = Fixture::new("preflight-fail");
let bin = fixture.root.join("bin");
fixture.install_fake_binaries(&bin);
// The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check.
let output = Process::new(LELEKA)
/// The server profile on a 16 GB card (or on a host without a GPU) cannot pass the GPU memory check.
fn up_with_the_server_profile(fixture: &Fixture, bin: &std::path::Path) -> std::process::Output {
Process::new(LELEKA)
.args([
"up",
"--profile",
@@ -92,9 +96,17 @@ fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--bin-src")
.arg(&bin)
.arg(bin)
.output()
.unwrap();
.unwrap()
}
#[test]
fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
let fixture = Fixture::new("preflight-fail");
let bin = fixture.root.join("bin");
fixture.install_fake_binaries(&bin);
let output = up_with_the_server_profile(&fixture, &bin);
assert_eq!(output.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
@@ -102,17 +114,7 @@ fn a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it() {
"{stderr}"
);
assert!(stderr.contains("nothing was changed"), "{stderr}");
for path in [
&fixture.dirs.assets,
&fixture.dirs.state,
&fixture.dirs.prefix,
] {
assert!(
!path.exists(),
"a failed preflight created {}",
path.display()
);
}
assert_no_directory_exists(&fixture, "a failed preflight created");
}
#[test]
+24 -15
View File
@@ -44,6 +44,11 @@ fn a_hung_engine_is_killed_and_restarted_by_the_health_check() {
let hung_pid = ready["engine_pid"].as_u64().unwrap();
// The process lives and the API answers, but a request has been active for ten minutes.
fs::write(fixture.fake_dir().join("hang-decode"), "").unwrap();
check_the_stalled_engine_is_replaced_once(&fixture, hung_pid);
stop_cleanly(&mut supervisor);
}
fn check_the_stalled_engine_is_replaced_once(fixture: &Fixture, hung_pid: u64) {
let again = fixture.wait_for("restart after the stall", Duration::from_secs(60), |s| {
s["phase"] == "ready"
&& s["restarts_total"] == 1
@@ -63,7 +68,6 @@ fn a_hung_engine_is_killed_and_restarted_by_the_health_check() {
healthy["restarts_total"], 1,
"no second restart without a second stall"
);
stop_cleanly(&mut supervisor);
}
#[test]
@@ -91,7 +95,10 @@ fn engine_restarts_back_off_survive_failed_attempts_and_give_up_in_the_end() {
log.matches("the engine did not come back").count() >= 3,
"{log}"
);
check_a_restart_that_fails_once_is_just_a_slower_restart();
}
fn check_a_restart_that_fails_once_is_just_a_slower_restart() {
// A restart that fails once and then works is just a slower restart.
let (fixture, config) = file_service("backoff2");
tune(&config, |c| {
@@ -166,6 +173,11 @@ fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone()
after_api["restarts_total"], 0,
"an API restart is not an engine restart"
);
check_a_killed_gateway_is_restarted(&fixture, gateway, engine);
stop_cleanly(&mut supervisor);
}
fn check_a_killed_gateway_is_restarted(fixture: &Fixture, gateway: u64, engine: u64) {
signal(gateway, "KILL");
let after_gateway = fixture.wait_for("a new gateway", Duration::from_secs(30), |s| {
s["gateway_pid"].as_u64().is_some_and(|p| p != gateway)
@@ -176,20 +188,25 @@ fn a_killed_api_or_gateway_is_restarted_in_place_and_the_engine_is_left_alone()
std::thread::sleep(Duration::from_millis(200));
}
assert_eq!(fixture.http_status("/ready"), 200);
stop_cleanly(&mut supervisor);
}
#[test]
fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() {
let fixture = Fixture::new("fail");
/// The laptop profile with a file archive and the fake engine told to fail through the `marker` file.
fn failing_service(name: &str, marker: &str) -> (Fixture, std::path::PathBuf) {
let fixture = Fixture::new(name);
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
fs::write(fixture.fake_dir().join("fail-engine"), "").unwrap();
fs::write(fixture.fake_dir().join(marker), "").unwrap();
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
let config = fixture.write_state(profile);
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
(fixture, config)
}
#[test]
fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() {
let (fixture, config) = failing_service("fail", "fail-engine");
let mut supervisor = start_supervisor(&fixture, &config, None);
let status =
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must give up");
@@ -210,15 +227,7 @@ fn an_engine_that_cannot_start_fails_the_service_and_names_the_log() {
#[test]
fn a_refused_load_fails_fast_and_shows_the_engine_log() {
// The real engine stays alive when its load fails; only the operation record says so.
let fixture = Fixture::new("refused");
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
fs::create_dir_all(fixture.fake_dir()).unwrap();
fs::write(fixture.fake_dir().join("fail-load"), "").unwrap();
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
let config = fixture.write_state(profile);
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::write(fixture.dirs.paths().kar(), b"archive").unwrap();
let (fixture, config) = failing_service("refused", "fail-load");
let started = Instant::now();
let mut supervisor = start_supervisor(&fixture, &config, None);
let status =
@@ -169,9 +169,6 @@ fn expert_step_tag(steps: &[Step]) -> &str {
#[tokio::test]
async fn first_start_installs_the_embedded_expert_profile_without_a_network() {
use leleka_deploy::expert_profile::{
FileState, PINNED_BYTES, PINNED_SHA256, file_state, tier_report,
};
let fixture = Fixture::new("embedded");
let bin_src = fixture.root.join("release/bin");
fixture.install_fake_binaries(&bin_src);
@@ -198,6 +195,17 @@ async fn first_start_installs_the_embedded_expert_profile_without_a_network() {
"{step:?}"
);
leleka_deploy::steps::provision_expert_profile(&ctx).unwrap();
check_the_table_is_installed_and_the_replan_is_done(&fixture, &ctx, &opts);
}
fn check_the_table_is_installed_and_the_replan_is_done(
fixture: &Fixture,
ctx: &Context,
opts: &leleka_deploy::cli::UpOptions,
) {
use leleka_deploy::expert_profile::{
FileState, PINNED_BYTES, PINNED_SHA256, file_state, tier_report,
};
let table = fixture.dirs.assets.join("data/expert-profile.bin");
assert_eq!(file_state(&table, PINNED_SHA256), FileState::Valid);
assert_eq!(fs::metadata(&table).unwrap().len(), PINNED_BYTES);
@@ -209,7 +217,7 @@ async fn first_start_installs_the_embedded_expert_profile_without_a_network() {
report.line()
);
// Re-planned: nothing left to do.
let steps = plan_steps(&healthy_context(&opts), &FsState::default());
let steps = plan_steps(&healthy_context(opts), &FsState::default());
assert_eq!(
steps
.iter()
+65 -40
View File
@@ -14,6 +14,16 @@ use std::{
const GIB: u64 = 1 << 30;
fn assert_done(fixture: &Fixture, outcome: &Outcome) {
assert_eq!(
outcome.state,
State::Done,
"{}\n{}",
outcome.message,
fixture.logs()
);
}
#[test]
fn a_new_budget_restarts_only_the_engine_with_the_same_sealed_archive() {
let service = start("reconf-budget");
@@ -61,13 +71,7 @@ fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() {
),
Duration::from_secs(120),
);
assert_eq!(
outcome.state,
State::Done,
"{}\n{}",
outcome.message,
fixture.logs()
);
assert_done(fixture, &outcome);
assert!(outcome.persisted, "{}", outcome.message);
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
@@ -78,12 +82,18 @@ fn persist_writes_the_files_and_a_crash_restart_keeps_the_new_numbers() {
service.stop();
}
#[test]
fn settings_alone_are_recorded_and_persisted_without_a_restart() {
let service = start("reconf-record");
let fixture = &service.fixture;
let engine = service.first["engine_pid"].as_u64().unwrap();
let outcome = ask(
fn check_the_settings_are_in_the_persisted_config(fixture: &Fixture) {
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_eq!(
config.profile.memory.prefix_cache_tail.as_deref(),
Some("prompt")
);
assert_eq!(config.profile.spec_min_p, Some(0.25));
}
fn ask_to_record_settings(fixture: &Fixture) -> Outcome {
ask(
fixture,
&request(
"record",
@@ -93,20 +103,22 @@ fn settings_alone_are_recorded_and_persisted_without_a_restart() {
true,
),
Duration::from_secs(30),
);
)
}
#[test]
fn settings_alone_are_recorded_and_persisted_without_a_restart() {
let service = start("reconf-record");
let fixture = &service.fixture;
let engine = service.first["engine_pid"].as_u64().unwrap();
let outcome = ask_to_record_settings(fixture);
assert_eq!(
(outcome.state, outcome.persisted),
(State::Done, true),
"{}",
outcome.message
);
let config =
leleka_deploy::config::RunConfig::read(&fixture.dirs.paths().run_config()).unwrap();
assert_eq!(
config.profile.memory.prefix_cache_tail.as_deref(),
Some("prompt")
);
assert_eq!(config.profile.spec_min_p, Some(0.25));
check_the_settings_are_in_the_persisted_config(fixture);
assert_eq!(
fixture.status().unwrap()["engine_pid"].as_u64().unwrap(),
engine,
@@ -122,6 +134,12 @@ fn what_the_planner_refuses_changes_nothing_and_a_failing_new_engine_restores_th
let service = start("reconf-refuse");
let fixture = &service.fixture;
let engine = service.first["engine_pid"].as_u64().unwrap();
check_refused_requests_leave_the_engine_alone(fixture, engine);
check_failed_new_engine_restores_the_old_one(&service, engine);
service.stop();
}
fn check_refused_requests_leave_the_engine_alone(fixture: &Fixture, engine: u64) {
// refused before the engine is touched
let bad = ask(
fixture,
@@ -146,28 +164,27 @@ 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 run_reconfigure(dirs: &leleka_deploy::layout::Dirs, args: &[&str]) -> std::process::Output {
Process::new(LELEKA)
.arg("reconfigure")
.args(args)
.arg("--state-dir")
.arg(&dirs.state)
.arg("--assets")
.arg(&dirs.assets)
.arg("--prefix")
.arg(&dirs.prefix)
.output()
.unwrap()
}
#[test]
fn the_cli_asks_the_supervisor_and_prints_the_answer() {
let service = start("reconf-cli");
let dirs = service.fixture.dirs.clone();
let run = |args: &[&str]| {
Process::new(LELEKA)
.arg("reconfigure")
.args(args)
.arg("--state-dir")
.arg(&dirs.state)
.arg("--assets")
.arg(&dirs.assets)
.arg("--prefix")
.arg(&dirs.prefix)
.output()
.unwrap()
};
let output = run(&["--gpu-budget-gib", "5", "--persist"]);
let output = run_reconfigure(&dirs, &["--gpu-budget-gib", "5", "--persist"]);
let text = String::from_utf8_lossy(&output.stdout).into_owned()
+ &String::from_utf8_lossy(&output.stderr);
assert!(
@@ -181,17 +198,25 @@ fn the_cli_asks_the_supervisor_and_prints_the_answer() {
);
let config = leleka_deploy::config::RunConfig::read(&dirs.paths().run_config()).unwrap();
assert_eq!(config.profile.gpu_budget_bytes, 5 * GIB);
check_a_refusal_is_a_nonzero_exit_with_the_reason(&dirs);
service.stop();
check_without_a_supervisor_the_restart_path_says_what_to_do(&dirs);
}
fn check_a_refusal_is_a_nonzero_exit_with_the_reason(dirs: &leleka_deploy::layout::Dirs) {
// a refusal is a non-zero exit with the reason
let refused = run(&["--gpu-budget-gib", "6", "--cpu-workers", "70"]);
let refused = run_reconfigure(dirs, &["--gpu-budget-gib", "6", "--cpu-workers", "70"]);
assert!(!refused.status.success());
let text = String::from_utf8_lossy(&refused.stderr);
assert!(
text.contains("cpu_workers") || text.contains("1..=64") || text.contains("cpu-workers"),
"{text}"
);
service.stop();
}
fn check_without_a_supervisor_the_restart_path_says_what_to_do(dirs: &leleka_deploy::layout::Dirs) {
// without a supervisor the restart path says what to do instead of hanging
let stopped = run(&["--preset", "workstation"]);
let stopped = run_reconfigure(dirs, &["--preset", "workstation"]);
assert!(!stopped.status.success());
assert!(
String::from_utf8_lossy(&stopped.stderr).contains("no supervisor runs"),
+49 -32
View File
@@ -2,7 +2,11 @@
use crate::harness::*;
use leleka_deploy::profile::{KarSource, Profile};
use std::{fs, process::Command as Process, time::Duration};
use std::{
fs,
process::{Child, Command as Process},
time::Duration,
};
/// `memfd_extents: ple_only` profile of the test double (the laptop profile with a sealed memfd and an explicit prefix cap).
pub(super) fn sparse_profile() -> Profile {
@@ -22,12 +26,7 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims
let config = fixture.write_state(sparse_profile());
let memfd = inheritable_sealed_memfd(&vec![7u8; 100_000]);
let pin = "ab".repeat(32);
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
let expected: String = if compiled == [0u8; 32] {
pin.clone()
} else {
compiled.iter().map(|b| format!("{b:02x}")).collect()
};
let expected = expected_extents_digest(&pin);
let mut supervisor = start_supervisor_with_env(
&fixture,
&config,
@@ -42,9 +41,23 @@ fn a_sparse_memfd_profile_tells_every_engine_the_extents_digest_and_never_claims
});
check_both_engines_got_the_digest(&fixture, &expected);
check_no_archive_stamp_and_digest_logged(&fixture, &expected);
terminate_cleanly(&mut supervisor, &fixture);
}
/// The digest the engines are told: the operator pin while the binary pins none, else the compiled one.
fn expected_extents_digest(pin: &str) -> String {
let compiled = leleka_model_format::kar::PLE_EXTENTS_SHA256;
if compiled == [0u8; 32] {
pin.to_owned()
} else {
compiled.iter().map(|b| format!("{b:02x}")).collect()
}
}
fn terminate_cleanly(supervisor: &mut Child, fixture: &Fixture) {
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()),
wait_exit(supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()),
"{}",
fixture.logs()
);
@@ -106,30 +119,30 @@ fn a_sparse_memfd_profile_starts_on_the_compiled_digest_and_refuses_when_none_is
if leleka_model_format::kar::PLE_EXTENTS_SHA256 != [0u8; 32] {
// the extents digest is pinned in the binary (the release form): no operator pin is needed and the supervisor starts
fixture.wait_for("ready", Duration::from_secs(120), |s| s["phase"] == "ready");
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60)).is_some_and(|s| s.success()),
"{}",
fixture.logs()
);
terminate_cleanly(&mut supervisor, &fixture);
return;
}
let status =
wait_exit(&mut supervisor, Duration::from_secs(60)).expect("the supervisor must refuse");
{
assert_eq!(status.code(), Some(1));
let message = fixture.status().unwrap()["message"]
.as_str()
.unwrap()
.to_owned();
assert!(
message.contains("kar_census") && message.contains("--hash-extents"),
"{message}"
);
// no engine was started
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default();
assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}");
}
check_the_refusal_names_the_census_and_no_engine_started(&fixture, status);
}
fn check_the_refusal_names_the_census_and_no_engine_started(
fixture: &Fixture,
status: std::process::ExitStatus,
) {
assert_eq!(status.code(), Some(1));
let message = fixture.status().unwrap()["message"]
.as_str()
.unwrap()
.to_owned();
assert!(
message.contains("kar_census") && message.contains("--hash-extents"),
"{message}"
);
// no engine was started
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap_or_default();
assert_eq!(calls.matches("leleka-inference ").count(), 0, "{calls}");
}
#[test]
@@ -139,7 +152,13 @@ fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_ca
let file = dir.join("archive.bin");
let bytes: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
fs::write(&file, &bytes).unwrap();
let run = |extra: &[&str]| seal_exec_output(&file, extra);
check_seal_exec_hands_a_sealed_memfd_of_the_file(&file);
check_seal_exec_refusals(&file);
fs::remove_dir_all(&dir).unwrap();
}
fn check_seal_exec_hands_a_sealed_memfd_of_the_file(file: &std::path::Path) {
let run = |extra: &[&str]| seal_exec_output(file, extra);
let ok = run(&[
"--expect-bytes",
"300000",
@@ -160,15 +179,13 @@ fn seal_exec_hands_the_command_a_sealed_memfd_of_the_file_and_refuses_what_it_ca
"{out}"
);
let want = Process::new("cksum")
.stdin(fs::File::open(&file).unwrap())
.stdin(fs::File::open(file).unwrap())
.output()
.unwrap();
assert!(
out.contains(String::from_utf8_lossy(&want.stdout).trim()),
"the descriptor holds the file byte for byte: {out}"
);
check_seal_exec_refusals(&file);
fs::remove_dir_all(&dir).unwrap();
}
fn seal_exec_output(file: &std::path::Path, extra: &[&str]) -> std::process::Output {
+11 -6
View File
@@ -181,19 +181,24 @@ async fn reverify_forces_the_verification(scene: &Scene) {
let _ = FsState::default();
}
#[tokio::test]
async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() {
let scene = Scene::new("trust");
let fixture = &scene.fixture;
let opts = scene.options(&["--trust-archive"]);
/// An archive of the pinned length with its provenance sidecar, as left by an earlier build.
fn write_archive_with_provenance(fixture: &Fixture) {
let paths = fixture.dirs.paths();
// An archive of the pinned length with its provenance sidecar, as left by an earlier build.
fs::create_dir_all(&fixture.dirs.assets).unwrap();
fs::File::create(paths.kar())
.unwrap()
.set_len(55_295_529_472)
.unwrap();
fs::write(paths.kar_provenance(), "{}").unwrap();
}
#[tokio::test]
async fn trust_archive_skips_the_strict_rederivation_but_still_fetches_and_verifies_the_shards() {
let scene = Scene::new("trust");
let fixture = &scene.fixture;
let opts = scene.options(&["--trust-archive"]);
let paths = fixture.dirs.paths();
write_archive_with_provenance(fixture);
let ctx = healthy_context(&opts);
let steps = plan_steps(&ctx, &gather_fs(&ctx).await);
let kar = steps.iter().find(|s| s.id == "kar").unwrap();
+33 -20
View File
@@ -25,8 +25,13 @@ fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model
&& text.contains("health: NOT OK"),
"{text}"
);
check_the_running_service_is_healthy(&fixture, &config);
}
fn check_the_running_service_is_healthy(fixture: &Fixture, config: &std::path::Path) {
let quick = || quick_verify(fixture);
// Running: healthy.
let mut supervisor = start_supervisor(&fixture, &config, None);
let mut supervisor = start_supervisor(fixture, config, None);
fixture.wait_for("ready", Duration::from_secs(60), |s| s["phase"] == "ready");
let after = quick();
let text = String::from_utf8_lossy(&after.stdout).into_owned();
@@ -37,7 +42,7 @@ fn verify_quick_reports_the_health_of_the_installation_without_reading_the_model
&& text.contains("engine restarts 0 in total"),
"{text}"
);
check_status_shows_the_same_facts(&fixture);
check_status_shows_the_same_facts(fixture);
signal(u64::from(supervisor.id()), "TERM");
assert!(
wait_exit(&mut supervisor, Duration::from_secs(60))
@@ -99,24 +104,33 @@ fn verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure() {
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
fixture.write_state(profile);
let run = |fixture: &Fixture| {
Process::new(LELEKA)
.arg("verify")
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--assets")
.arg(&fixture.dirs.assets)
.output()
.unwrap()
};
let output = run(&fixture);
let output = full_verify(&fixture);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
check_the_engine_got_the_rehash_switches(&fixture);
fs::write(fixture.fake_dir().join("fail-verify"), "").unwrap();
let output = full_verify(&fixture);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("verification FAILED"));
}
fn full_verify(fixture: &Fixture) -> std::process::Output {
Process::new(LELEKA)
.arg("verify")
.arg("--state-dir")
.arg(&fixture.dirs.state)
.arg("--prefix")
.arg(&fixture.dirs.prefix)
.arg("--assets")
.arg(&fixture.dirs.assets)
.output()
.unwrap()
}
fn check_the_engine_got_the_rehash_switches(fixture: &Fixture) {
let calls = fs::read_to_string(fixture.fake_dir().join("calls.log")).unwrap();
let line = calls
.lines()
@@ -134,10 +148,6 @@ fn verify_runs_the_engine_in_full_rehash_mode_and_reports_a_failure() {
"{line}"
);
assert!(fixture.dirs.paths().engine_stamps().is_dir());
fs::write(fixture.fake_dir().join("fail-verify"), "").unwrap();
let output = run(&fixture);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("verification FAILED"));
}
#[test]
@@ -154,7 +164,10 @@ fn a_broken_configuration_is_exit_code_two_with_a_clear_message() {
assert_eq!(output.status.code(), Some(2));
let text = String::from_utf8_lossy(&output.stderr);
assert!(text.contains("run `leleka up` first"), "{text}");
// Weak tokens are refused before anything starts.
check_weak_tokens_are_refused_before_anything_starts(&fixture);
}
fn check_weak_tokens_are_refused_before_anything_starts(fixture: &Fixture) {
fixture.install_fake_binaries(&fixture.dirs.prefix.join("bin"));
let mut profile = Profile::builtin("rtx3080-16g").unwrap();
profile.kar_source = KarSource::File;
+14 -81
View File
@@ -26,6 +26,10 @@ const KEY: &str = "fake-api-key-0123456789abcdef0123456789abcdef";
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[path = "e2e_windows/checks.rs"]
mod checks;
use checks::*;
fn free_port() -> u16 {
TcpListener::bind(("127.0.0.1", 0))
.unwrap()
@@ -81,6 +85,12 @@ impl Fixture {
)
.unwrap();
fs::write(paths.api_key(), KEY).unwrap();
self.write_configs();
}
/// The run, daemon and gateway configuration files of the laptop profile.
fn write_configs(&self) {
let paths = self.dirs.paths();
// The laptop profile: the archive is a plain file, the experts are mapped. The double only checks that the file exists.
fs::create_dir_all(&self.dirs.assets).unwrap();
fs::write(paths.kar(), b"archive").unwrap();
@@ -261,81 +271,9 @@ fn the_supervisor_starts_serves_status_and_reconfigure_and_stops_by_ctrl_break()
.engine_pid()
.expect("the engine double wrote its pid");
assert!(alive(engine));
// `leleka status` reads the files and the API of this state directory.
let (code, out, err) = fixture.cli(&["status"]);
assert_eq!(code, 0, "{out}{err}");
assert!(
out.contains("ready: true") && out.contains("supervisor: phase ready"),
"{out}"
);
assert!(
out.contains("engine load (idle)") && out.contains("context 0 of 8192 tokens"),
"{out}"
);
let (code, out, _) = fixture.cli(&["status", "--json"]);
assert_eq!(code, 0);
let document: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(document["ready"], true);
// `leleka reconfigure` over HTTP.
let (code, out, err) = fixture.cli(&[
"reconfigure",
"--context-tokens",
"4096",
"--cpu-workers",
"3",
]);
assert_eq!(code, 0, "{out}{err}");
assert!(
out.contains("reconfigured") && out.contains("4096"),
"{out}
{}",
fixture.logs()
);
// A change that needs a new engine process goes through the supervisor and keeps the other two programs.
let (gateway, api) = (status["gateway_pid"].clone(), status["api_pid"].clone());
let (code, out, err) = fixture.cli(&["reconfigure", "--gpu-budget-gib", "12"]);
assert_eq!(code, 0, "{out}{err}\n{}", fixture.logs());
let again = ready(&fixture);
assert_eq!(
again["engine_restarts"], 0,
"a planned restart is not a crash"
);
assert_eq!(
(again["gateway_pid"].clone(), again["api_pid"].clone()),
(gateway, api),
"gateway and API survive"
);
assert_ne!(
fixture.engine_pid(),
Some(engine),
"the engine is a new process"
);
// Ctrl-Break aimed at the supervisor's process group: the API drains, then the gateway and the engine stop.
let engine = fixture.engine_pid().unwrap();
if !leleka_deploy::winsys::send_ctrl_break(supervisor.id()) {
eprintln!(
"no console to send Ctrl-Break through; the stop-file test covers the shutdown path"
);
let _ = fixture.cli(&["down"]);
}
let exit = wait_exit(&mut supervisor, Duration::from_secs(60));
if exit.is_none() {
kill_tree(&mut supervisor);
panic!("the supervisor did not stop\n{}", fixture.logs());
}
assert!(exit.unwrap().success(), "{:?}\n{}", exit, fixture.logs());
let last = fixture.status().unwrap();
assert_eq!(last["phase"], "stopped", "{last}");
std::thread::sleep(Duration::from_millis(500));
assert!(!alive(engine), "the engine must be gone");
assert_eq!(
fixture.http_status("/ready"),
0,
"nothing listens on the API port any more"
);
check_status_reads_the_files_and_the_api(&fixture);
check_reconfigure_keeps_gateway_and_api_and_replaces_the_engine(&fixture, &status, engine);
check_ctrl_break_stops_everything(&fixture, &mut supervisor);
}
#[test]
@@ -365,10 +303,5 @@ fn leleka_down_stops_the_supervisor_through_the_stop_file() {
);
std::thread::sleep(Duration::from_millis(500));
assert!(!alive(engine));
// Nothing runs now: `down` says so, `status` reports not ready.
let (code, _, err) = fixture.cli(&["down"]);
assert_eq!(code, 0);
assert!(err.contains("no running supervisor"), "{err}");
let (code, out, _) = fixture.cli(&["status"]);
assert_eq!(code, 1, "{out}");
check_nothing_runs_after_down(&fixture);
}
+101
View File
@@ -0,0 +1,101 @@
//! Checks of the Windows supervisor test, one function per stage (moved out of `e2e_windows.rs`, file size limit).
use super::*;
pub(super) fn check_status_reads_the_files_and_the_api(fixture: &Fixture) {
// `leleka status` reads the files and the API of this state directory.
let (code, out, err) = fixture.cli(&["status"]);
assert_eq!(code, 0, "{out}{err}");
assert!(
out.contains("ready: true") && out.contains("supervisor: phase ready"),
"{out}"
);
assert!(
out.contains("engine load (idle)") && out.contains("context 0 of 8192 tokens"),
"{out}"
);
let (code, out, _) = fixture.cli(&["status", "--json"]);
assert_eq!(code, 0);
let document: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(document["ready"], true);
}
pub(super) fn check_reconfigure_keeps_gateway_and_api_and_replaces_the_engine(
fixture: &Fixture,
status: &serde_json::Value,
engine: u32,
) {
check_reconfigure_over_http(fixture);
// A change that needs a new engine process goes through the supervisor and keeps the other two programs.
let (gateway, api) = (status["gateway_pid"].clone(), status["api_pid"].clone());
let (code, out, err) = fixture.cli(&["reconfigure", "--gpu-budget-gib", "12"]);
assert_eq!(code, 0, "{out}{err}@@NL@@{}", fixture.logs());
let again = ready(fixture);
assert_eq!(
again["engine_restarts"], 0,
"a planned restart is not a crash"
);
assert_eq!(
(again["gateway_pid"].clone(), again["api_pid"].clone()),
(gateway, api),
"gateway and API survive"
);
assert_ne!(
fixture.engine_pid(),
Some(engine),
"the engine is a new process"
);
}
pub(super) fn check_reconfigure_over_http(fixture: &Fixture) {
// `leleka reconfigure` over HTTP.
let (code, out, err) = fixture.cli(&[
"reconfigure",
"--context-tokens",
"4096",
"--cpu-workers",
"3",
]);
assert_eq!(code, 0, "{out}{err}");
assert!(
out.contains("reconfigured") && out.contains("4096"),
"{out}
{}",
fixture.logs()
);
}
pub(super) fn check_ctrl_break_stops_everything(fixture: &Fixture, supervisor: &mut Child) {
// Ctrl-Break aimed at the supervisor's process group: the API drains, then the gateway and the engine stop.
let engine = fixture.engine_pid().unwrap();
if !leleka_deploy::winsys::send_ctrl_break(supervisor.id()) {
eprintln!(
"no console to send Ctrl-Break through; the stop-file test covers the shutdown path"
);
let _ = fixture.cli(&["down"]);
}
let exit = wait_exit(supervisor, Duration::from_secs(60));
if exit.is_none() {
kill_tree(supervisor);
panic!("the supervisor did not stop\n{}", fixture.logs());
}
assert!(exit.unwrap().success(), "{:?}\n{}", exit, fixture.logs());
let last = fixture.status().unwrap();
assert_eq!(last["phase"], "stopped", "{last}");
std::thread::sleep(Duration::from_millis(500));
assert!(!alive(engine), "the engine must be gone");
assert_eq!(
fixture.http_status("/ready"),
0,
"nothing listens on the API port any more"
);
}
pub(super) fn check_nothing_runs_after_down(fixture: &Fixture) {
// Nothing runs now: `down` says so, `status` reports not ready.
let (code, _, err) = fixture.cli(&["down"]);
assert_eq!(code, 0);
assert!(err.contains("no running supervisor"), "{err}");
let (code, out, _) = fixture.cli(&["status"]);
assert_eq!(code, 1, "{out}");
}
+33 -17
View File
@@ -30,31 +30,39 @@ fn instructions(text: &str) -> Vec<String> {
out
}
/// The instructions that start with `prefix`.
fn find(lines: &[String], prefix: &str) -> Vec<String> {
lines
.iter()
.filter(|l| l.starts_with(prefix))
.cloned()
.collect()
}
#[test]
fn the_oci_recipe_is_non_root_checked_and_model_free() {
let text = read("deploy/Containerfile.rust-runtime");
let lines = instructions(&text);
let find = |prefix: &str| {
lines
.iter()
.filter(|l| l.starts_with(prefix))
.cloned()
.collect::<Vec<_>>()
};
// Non-root, and the last USER wins.
assert_eq!(
find("USER ").last().map(String::as_str),
find(&lines, "USER ").last().map(String::as_str),
Some("USER 10001:10001")
);
// A health check that does not need a GPU probe.
let health = find("HEALTHCHECK").join(" ");
let health = find(&lines, "HEALTHCHECK").join(" ");
assert!(
health.contains("/opt/leleka/bin/leleka") && health.contains("status"),
"{health}"
);
check_the_model_volume_is_external_and_never_copied(&lines);
check_only_binaries_libraries_and_manifests_are_copied(&text, &lines);
check_no_secret_environment_and_the_entrypoint(&lines);
}
fn check_the_model_volume_is_external_and_never_copied(lines: &[String]) {
// The model volume is external: declared, never copied.
assert!(find("VOLUME").join(" ").contains("/models"));
for copy in find("COPY").iter().chain(find("ADD").iter()) {
assert!(find(lines, "VOLUME").join(" ").contains("/models"));
for copy in find(lines, "COPY").iter().chain(find(lines, "ADD").iter()) {
let lower = copy.to_ascii_lowercase();
for forbidden in [
".gguf",
@@ -71,19 +79,25 @@ fn the_oci_recipe_is_non_root_checked_and_model_free() {
);
}
}
}
fn check_only_binaries_libraries_and_manifests_are_copied(text: &str, lines: &[String]) {
// Only the binaries, the cuBLAS libraries and the manifests are copied in.
let copies: Vec<String> = find("COPY");
let copies: Vec<String> = find(lines, "COPY");
assert!(copies.iter().any(|c| c.contains("bin/ /opt/leleka/bin/")));
assert!(copies.iter().any(|c| c.contains("--from=cublas")));
// The cuBLAS download is checksum-pinned.
assert!(
find("ADD")
find(lines, "ADD")
.iter()
.any(|a| a.contains("--checksum=sha256:${CUBLAS_SHA256}"))
);
assert!(text.contains("546addc4a9d82b8f23aa9ba9274b6bc0429a63008a31c759884ac24880796057"));
}
fn check_no_secret_environment_and_the_entrypoint(lines: &[String]) {
// No secret-looking environment, no ssh keys, no package-manager network step in the runtime stage.
for env in find("ENV") {
for env in find(lines, "ENV") {
assert!(
!env.to_ascii_uppercase().contains("TOKEN")
&& !env.to_ascii_uppercase().contains("KEY="),
@@ -91,10 +105,10 @@ fn the_oci_recipe_is_non_root_checked_and_model_free() {
);
}
assert_eq!(
find("ENTRYPOINT"),
find(lines, "ENTRYPOINT"),
vec![r#"ENTRYPOINT ["/opt/leleka/bin/leleka"]"#.to_string()]
);
assert!(find("CMD").join(" ").contains("--foreground"));
assert!(find(lines, "CMD").join(" ").contains("--foreground"));
}
#[test]
@@ -116,7 +130,9 @@ fn the_cublas_pin_matches_the_tool_and_the_documentation() {
#[test]
fn the_pinned_archive_digest_of_the_stamps_is_the_one_the_engine_pins() {
// the pin is spelled out in the pinned-profile test module, which sits in a child file of qwen4exp_kar_ple.rs
let engine = read("crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs");
let engine = read(
"crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs",
);
assert!(
engine.contains(leleka_deploy::profile::ARCHIVE_SHA256_HEX),
"the archive digest the supervisor stamps differs from the engine's pin"