From df15e7afd5b755efd20bb4b11db436860d10645d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 17:04:17 +0100 Subject: [PATCH] STRA-338 size6 r01: split oversized tests and example, wrap wide lines in small crates --- .../impl_backend_for_scriptedengine.rs | 3 +- crates/context/src/rope_scaling/tests.rs | 28 ++- crates/context/tests/rope_plan_golden.rs | 120 +++++++---- crates/context/tests/setup_policy_oracle.rs | 49 +++-- .../src/bringup_trace_enabled_fn.rs | 2 +- crates/cuda-driver/src/tests.rs | 33 +-- .../retained_buffers_count_against_bytes.rs | 8 + .../store/tests/hit_by_another_session.rs | 191 ++++++++++------- .../store/tests/request_resumes_from.rs | 20 +- crates/engine-core/src/prompt/grid_tests.rs | 30 +-- crates/engine-core/src/prompt/tests.rs | 194 ++++++++++++------ crates/engine-core/src/spec/adaptive/tests.rs | 90 ++++---- .../spec/adaptive/tests/default_ceiling.rs | 16 +- .../stationary_regimes_reach_the_best.rs | 110 +++++----- crates/gateway-text/src/prompt/tests.rs | 58 +----- .../src/prompt/tests/jinja_filters.rs | 61 ++++++ crates/leleka-memory/examples/swap_ab.rs | 176 +++++++++------- crates/leleka-memory/src/governor/tests.rs | 8 +- crates/leleka-memory/src/host/tests.rs | 12 +- crates/leleka-memory/src/lock/sys.rs | 6 +- crates/leleka-memory/src/lock/tests.rs | 3 +- crates/leleka-memory/src/pressure/tests.rs | 12 +- crates/leleka-memory/src/procfs/tests.rs | 23 ++- crates/leleka-memory/src/smi.rs | 3 +- crates/leleka-memory/src/telemetry/tests.rs | 40 ++-- crates/leleka-runtime/src/lib.rs | 6 +- crates/libc-shim/src/lib.rs | 36 ++-- .../grpc_backend/runtime_restart_and_loss.rs | 14 +- .../tests/grpc_backend/stream_lifecycle.rs | 40 ++-- 29 files changed, 837 insertions(+), 555 deletions(-) create mode 100644 crates/gateway-text/src/prompt/tests/jinja_filters.rs diff --git a/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs b/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs index 8a406d65..dc1364b4 100644 --- a/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs +++ b/crates/backend-api/src/scripted/impl_backend_for_scriptedengine.rs @@ -20,7 +20,8 @@ impl Backend for ScriptedEngine { self.shared.memory_report.lock().unwrap().clone() } - /// Accepts any document that looks like a JSON object unless it names a member `"bad"` (refused as an invalid request) and echoes it. + /// Accepts any document that looks like a JSON object unless it names a member `"bad"` (refused as an invalid + /// request) and echoes it. fn reconfigure(&mut self, settings_json: &str) -> Result { let invalid = |message: &str| BackendError { code: ErrorCode::InvalidRequest, diff --git a/crates/context/src/rope_scaling/tests.rs b/crates/context/src/rope_scaling/tests.rs index 6c56d9ff..a098b67d 100644 --- a/crates/context/src/rope_scaling/tests.rs +++ b/crates/context/src/rope_scaling/tests.rs @@ -104,6 +104,14 @@ fn setup_resolution_matches_setup_py() { #[test] fn knob_resolution_follows_generate_cpp() { + knobs_default_to_the_stock_model_and_derive_the_ext_factor(); + let model = ModelRopeKeys { scaling_type: Some("yarn".into()), factor: 2.0, freq_base: 5e6, orig_ctx: 131_072.0 }; + the_model_file_supplies_defaults_and_none_opts_out(&model); + refusals_name_the_failing_knob(&model); + a_resolved_factor_invalid_as_a_whole_is_refused(); +} + +fn knobs_default_to_the_stock_model_and_derive_the_ext_factor() { // flag absent everywhere: stock model let r = resolve_rope_scaling(&RopeKnobs::default(), &ModelRopeKeys::default()).unwrap(); assert_eq!(r.scaling, RopeScaling::default()); @@ -119,32 +127,38 @@ fn knob_resolution_follows_generate_cpp() { // linear: ext auto = 0 let k = RopeKnobs { scaling: Some(RopeScalingType::Linear), rope_scale: 2.0, ..RopeKnobs::default() }; assert_eq!(resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap().scaling.ext_factor, 0.0); +} +fn the_model_file_supplies_defaults_and_none_opts_out(model: &ModelRopeKeys) { // model file supplies defaults; an explicit none opts out and notes the dropped knobs - let model = ModelRopeKeys { scaling_type: Some("yarn".into()), factor: 2.0, freq_base: 5e6, orig_ctx: 131_072.0 }; - let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap(); + let r = resolve_rope_scaling(&RopeKnobs::default(), model).unwrap(); assert_eq!(r.scaling.kind, RopeScalingType::YaRN); assert_eq!(r.scaling.factor, 2.0); assert_eq!(r.scaling.freq_base, 5e6); assert_eq!(r.scaling.orig_ctx, 131_072.0); let k = RopeKnobs { scaling: Some(RopeScalingType::None), rope_scale: 2.0, ..RopeKnobs::default() }; - let r = resolve_rope_scaling(&k, &model).unwrap(); + let r = resolve_rope_scaling(&k, model).unwrap(); assert_eq!(r.scaling.kind, RopeScalingType::None); assert_eq!(r.scaling.freq_base, 5e6); assert_eq!(r.scaling.factor, 1.0); assert!(r.inert_knobs_ignored); +} +fn refusals_name_the_failing_knob(model: &ModelRopeKeys) { // refusals let bad_scale = RopeKnobs { rope_scale: 0.5, ..RopeKnobs::default() }; - assert_eq!(resolve_rope_scaling(&bad_scale, &model), Err(RopeKnobError::ScaleBelowOne)); + assert_eq!(resolve_rope_scaling(&bad_scale, model), Err(RopeKnobError::ScaleBelowOne)); let nan = RopeKnobs { yarn_beta_fast: f64::NAN, ..RopeKnobs::default() }; - assert_eq!(resolve_rope_scaling(&nan, &model), Err(RopeKnobError::NotFinite)); + assert_eq!(resolve_rope_scaling(&nan, model), Err(RopeKnobError::NotFinite)); let base1 = RopeKnobs { rope_freq_base: 1.0, ..RopeKnobs::default() }; - assert_eq!(resolve_rope_scaling(&base1, &model), Err(RopeKnobError::FreqBase)); + assert_eq!(resolve_rope_scaling(&base1, model), Err(RopeKnobError::FreqBase)); let neg = RopeKnobs { yarn_attn_factor: 0.0, ..RopeKnobs::default() }; - assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob)); + assert_eq!(resolve_rope_scaling(&neg, model), Err(RopeKnobError::Knob)); let weird = ModelRopeKeys { scaling_type: Some("longrope".into()), ..ModelRopeKeys::default() }; assert_eq!(resolve_rope_scaling(&RopeKnobs::default(), &weird), Err(RopeKnobError::ModelType("longrope".into()))); +} + +fn a_resolved_factor_invalid_as_a_whole_is_refused() { // a resolved factor that is fine per-flag but invalid as a whole let k = RopeKnobs { scaling: Some(RopeScalingType::YaRN), diff --git a/crates/context/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs index 64fd891a..5719dbe5 100644 --- a/crates/context/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -15,7 +15,7 @@ use leleka_context::memory_plan::{ Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan, make_plan_with_format, state_bytes, }; -use leleka_context::rope_scaling::{RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle}; +use leleka_context::rope_scaling::{RopeKernelArgs, RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle}; use serde_json::Value; const ROPE_JSON: &str = include_str!("rope_plan_golden/rope_golden.json"); @@ -102,11 +102,19 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { // validity message, exactly let want = c["invalid"].as_str(); assert_eq!(sc.validate().err().map(|e| e.reason()), want, "{name}: validity"); + check_scalar_resolutions(c, sc, n_rot, want.is_none()); + let a = sc.kernel_args(n_rot); + check_kernel_args(c, name, &a); + check_analytic_path(c, name, &a); +} + +fn check_scalar_resolutions(c: &Value, sc: &RopeScaling, n_rot: i32, valid: bool) { + let name = c["name"].as_str().unwrap(); // scalar resolutions: libm log is the only dependency let tol = if EXACT { 0.0 } else { 4.0 * f64::EPSILON }; let near = |a: f64, b: f64| (a - b).abs() <= tol * b.abs().max(1.0); assert!(near(sc.freq_scale(), bits64(&c["freq_scale"])), "{name}: freq_scale"); - if want.is_none() || sc.freq_scale().is_finite() { + if valid || sc.freq_scale().is_finite() { assert!(near(sc.mscale(), bits64(&c["mscale"])), "{name}: mscale"); } let cd = sc.corr_dims(n_rot); @@ -115,7 +123,9 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { // a NaN from log(<0) of an invalid config: any NaN matches (payload/sign are libm detail) assert!(cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()), "{name}: corr_dims[{k}]"); } - let a = sc.kernel_args(n_rot); +} + +fn check_kernel_args(c: &Value, name: &str, a: &RopeKernelArgs) { let w = &c["kernel_args"]; assert_eq!(a.freq_scale.to_bits(), bits32(&w["freq_scale"]).to_bits(), "{name}: args.freq_scale"); assert!( @@ -132,6 +142,9 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { ); assert_eq!(a.ext_factor.to_bits(), bits32(&w["ext_factor"]).to_bits(), "{name}: args.ext_factor"); assert_eq!(a.attn_factor.to_bits(), bits32(&w["attn_factor"]).to_bits(), "{name}: args.attn_factor"); +} + +fn check_analytic_path(c: &Value, name: &str, a: &RopeKernelArgs) { // analytic float32 path for s in c["analytic"].as_array().unwrap() { let (co, si) = rope_scaled_angle( @@ -148,6 +161,46 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { } } +struct TableChunk<'a> { + name: &'a str, + first: usize, + half: usize, + cos: &'a [f32], + sin: &'a [f32], +} + +fn check_sample_rows(samples: &[Value], chunk: &TableChunk) { + const CHUNK: usize = 4096; + let TableChunk { name, first, half, cos: cbuf, sin: sbuf } = *chunk; + for s in samples { + let p = s["pos"].as_u64().unwrap() as usize; + if p >= first && p < first + CHUNK { + let r = p - first; + for i in 0..half { + assert_close(&format!("{name}: row {p} cos[{i}]"), cbuf[r * half + i], bits32(&s["cos"][i]), 1); + assert_close(&format!("{name}: row {p} sin[{i}]"), sbuf[r * half + i], bits32(&s["sin"][i]), 1); + } + } + } +} + +fn check_table_hashes(c: &Value, name: &str, got: [(u64, u64); 2]) { + let want = c["tables"].as_array().unwrap(); + for (t, (gc, gs)) in want.iter().zip(got) { + let (wc, ws) = (hex64(&t["cos_fnv1a64"]), hex64(&t["sin_fnv1a64"])); + let n = t["n_pos"].as_u64().unwrap(); + if EXACT { + assert_eq!(gc, wc, "{name}: cos table hash over {n} rows"); + assert_eq!(gs, ws, "{name}: sin table hash over {n} rows"); + } else if (gc, gs) != (wc, ws) { + eprintln!( + "note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); \ + sample rows are within tolerance" + ); + } + } +} + fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { let name = c["name"].as_str().unwrap(); let half = n_rot / 2; @@ -165,35 +218,12 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { if first == 262_144 { at_262144 = (cos_hash.0, sin_hash.0); } - for s in samples { - let p = s["pos"].as_u64().unwrap() as usize; - if p >= first && p < first + CHUNK { - let r = p - first; - for i in 0..half { - assert_close(&format!("{name}: row {p} cos[{i}]"), cbuf[r * half + i], bits32(&s["cos"][i]), 1); - assert_close(&format!("{name}: row {p} sin[{i}]"), sbuf[r * half + i], bits32(&s["sin"][i]), 1); - } - } - } + check_sample_rows(samples, &TableChunk { name, first, half, cos: &cbuf, sin: &sbuf }); cos_hash.feed(&cbuf); sin_hash.feed(&sbuf); first += CHUNK; } - let want = c["tables"].as_array().unwrap(); - let got = [(at_262144.0, at_262144.1), (cos_hash.0, sin_hash.0)]; - for (t, (gc, gs)) in want.iter().zip(got) { - let (wc, ws) = (hex64(&t["cos_fnv1a64"]), hex64(&t["sin_fnv1a64"])); - let n = t["n_pos"].as_u64().unwrap(); - if EXACT { - assert_eq!(gc, wc, "{name}: cos table hash over {n} rows"); - assert_eq!(gs, ws, "{name}: sin table hash over {n} rows"); - } else if (gc, gs) != (wc, ws) { - eprintln!( - "note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); \ - sample rows are within tolerance" - ); - } - } + check_table_hashes(c, name, [(at_262144.0, at_262144.1), (cos_hash.0, sin_hash.0)]); } fn run_case(name: &str) { @@ -239,11 +269,15 @@ rope_cases!( // ---- memory plan ------------------------------------------------------------------------------- -fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> { - let mut ctx: u64 = 20480; - let mut free_vram: u64 = 12_000_000_000; - let mut costs = Costs::default(); - let mut state_given = false; +struct CliArgs { + ctx: u64, + free_vram: u64, + costs: Costs, + state_given: bool, +} + +fn parse_cli(args: &[String]) -> Option { + let mut cli = CliArgs { ctx: 20480, free_vram: 12_000_000_000, costs: Costs::default(), state_given: false }; let mut i = 0; while i < args.len() { let a = args[i].as_str(); @@ -253,19 +287,24 @@ fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> { raw.parse().expect("fixture numbers are plain u64") }; match a { - "--max-context" => ctx = next(&mut i), - "--vram" | "--pool" => free_vram = next(&mut i), - "--dense" => costs.dense_bytes = next(&mut i), - "--embd" => costs.embd_bytes = next(&mut i), - "--workspace" => costs.workspace_bytes = next(&mut i), + "--max-context" => cli.ctx = next(&mut i), + "--vram" | "--pool" => cli.free_vram = next(&mut i), + "--dense" => cli.costs.dense_bytes = next(&mut i), + "--embd" => cli.costs.embd_bytes = next(&mut i), + "--workspace" => cli.costs.workspace_bytes = next(&mut i), "--state" => { - costs.state_bytes = next(&mut i); - state_given = true; + cli.costs.state_bytes = next(&mut i); + cli.state_given = true; } _ => return None, // --help / unknown / missing value: argument parsing, not planner arithmetic } i += 1; } + Some(cli) +} + +fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> { + let CliArgs { ctx, free_vram, mut costs, state_given } = parse_cli(args)?; let g = Geometry::default(); if !state_given { costs.state_bytes = state_bytes(&g).unwrap(); @@ -281,6 +320,5 @@ fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> { Err(e) => panic!("unexpected {e}"), }) } - #[path = "rope_plan_golden/every_fixture_case_has.rs"] mod every_fixture_case_has; diff --git a/crates/context/tests/setup_policy_oracle.rs b/crates/context/tests/setup_policy_oracle.rs index e2bfe80d..5cd535b3 100644 --- a/crates/context/tests/setup_policy_oracle.rs +++ b/crates/context/tests/setup_policy_oracle.rs @@ -32,6 +32,33 @@ fn model_table_and_contexts_are_setup_pys() { assert_eq!(contexts, policy::CONTEXTS); } +fn rope_kind(name: &Value) -> Option { + match name.as_str() { + None => None, + Some("none") => Some(RopeScalingType::None), + Some("linear") => Some(RopeScalingType::Linear), + Some("yarn") => Some(RopeScalingType::YaRN), + Some(other) => panic!("{other}"), + } +} + +fn check_resolve_rope_row(row: &Value) { + let got = + setup_resolve_rope(row["ctx"].as_u64().unwrap(), rope_kind(&row["scaling"]), row["scale"].as_f64(), 262144); + if row.get("error").is_some() { + assert!(got.is_err(), "{row}"); + return; + } + match (&row["result"], got.unwrap_or_else(|e| panic!("{row}: {e}"))) { + (Value::Null, None) => {} + (want, Some((scaling, factor))) => { + assert_eq!(rope_kind(&want[0]), Some(scaling), "{row}"); + same(factor, &want[1], &row.to_string()); + } + (want, got) => panic!("{row}: want {want}, got {got:?}"), + } +} + #[test] fn derived_factor_and_resolve_rope_match() { let g = golden(); @@ -42,30 +69,10 @@ fn derived_factor_and_resolve_rope_match() { "derived_factor", ); } - let kind = |name: &Value| match name.as_str() { - None => None, - Some("none") => Some(RopeScalingType::None), - Some("linear") => Some(RopeScalingType::Linear), - Some("yarn") => Some(RopeScalingType::YaRN), - Some(other) => panic!("{other}"), - }; let rows = g["resolve_rope"].as_array().unwrap(); assert!(rows.len() > 300); for row in rows { - let got = - setup_resolve_rope(row["ctx"].as_u64().unwrap(), kind(&row["scaling"]), row["scale"].as_f64(), 262144); - if row.get("error").is_some() { - assert!(got.is_err(), "{row}"); - continue; - } - match (&row["result"], got.unwrap_or_else(|e| panic!("{row}: {e}"))) { - (Value::Null, None) => {} - (want, Some((scaling, factor))) => { - assert_eq!(kind(&want[0]), Some(scaling), "{row}"); - same(factor, &want[1], &row.to_string()); - } - (want, got) => panic!("{row}: want {want}, got {got:?}"), - } + check_resolve_rope_row(row); } } diff --git a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs index c2d28261..257b181a 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs @@ -154,7 +154,7 @@ impl<'driver> Device<'driver> { } } impl<'driver> Context<'driver> { - fn fresh(driver: &'driver Driver, handle: ffi::ContextHandle, ordinal: i32, budget: usize) -> Self { + pub(super) fn fresh(driver: &'driver Driver, handle: ffi::ContextHandle, ordinal: i32, budget: usize) -> Self { Context { driver, handle: Some(handle), diff --git a/crates/cuda-driver/src/tests.rs b/crates/cuda-driver/src/tests.rs index 617823e3..d1023ff7 100644 --- a/crates/cuda-driver/src/tests.rs +++ b/crates/cuda-driver/src/tests.rs @@ -161,35 +161,10 @@ fn matvec_allocation_identity_and_absent_handles() { } #[cfg(not(feature = "cuda-driver"))] fn bare_context(driver: &Driver) -> Context<'_> { - Context { - driver, - handle: None, - ordinal: 0, - budget: 64, - allocated: Cell::new(12), - poisoned: PoisonCell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - grouped_iq3: Cell::new(None), - grouped_iq2: Cell::new(None), - grouped_iq3_s: Cell::new(None), - grouped_iq4_xs: Cell::new(None), - grouped_iq3_s_nc4: Cell::new(None), - grouped_iq4_xs_nc4: Cell::new(None), - grouped_swiglu: Cell::new(None), - grouped_down_iq4: Cell::new(None), - grouped_down_q2: Cell::new(None), - gr_read_guard_kernel: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::new(None)), - qwen_kernels: qwen_dispatch::Cache::new(), - kar_levels: Cell::new(None), - experimental: std::array::from_fn(|_| Cell::new(None)), - window_modules: RefCell::new(Vec::new()), - deferred_frees: RefCell::new(Vec::new()), - } + let mut context = Context::fresh(driver, ffi::ContextHandle::synthetic(0), 0, 64); + context.handle = None; + context.allocated = Cell::new(12); + context } #[cfg(not(feature = "cuda-driver"))] #[test] diff --git a/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs b/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs index 20874f31..499ae66f 100644 --- a/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs +++ b/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs @@ -17,12 +17,20 @@ fn retained_buffers_count_against_bytes_but_not_slots() { cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot" ); + take_the_retained_buffers_and_retain_them_again(&mut cache, parked); + assert_optional_reuse_never_evicts(&mut cache, retained, parked); +} + +fn take_the_retained_buffers_and_retain_them_again(cache: &mut ConversationCache, parked: usize) { cache.limit_reuse(9); cache.limit_reuse(12); let reuse = cache.take_reuse(); assert_eq!(reuse.unchanged_tokens, 9, "a later continuation cannot undo a rewind's dirty boundary"); assert_eq!(cache.bytes(), parked, "taking retained buffers releases their budget accounting"); cache.retain(reuse.kv, 16); +} + +fn assert_optional_reuse_never_evicts(cache: &mut ConversationCache, retained: usize, parked: usize) { assert!(!cache.can_fit(parked, 0), "retained storage is counted when checking a capture without eviction"); assert!( cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, diff --git a/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs b/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs index 779dbfbd..dfaa1697 100644 --- a/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs +++ b/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs @@ -157,91 +157,142 @@ fn a_long_agent_session_costs_a_sparse_chain_not_a_node_per_block() { assert!(depths.iter().any(|d| *d < 39), "{depths:?}"); } +const SCALE_BLOCK_TOKENS: usize = 2048; +const SCALE_STATE_BYTES: usize = 127 << 20; +const SCALE_BLOCK_BYTES: usize = 29 << 20; + +fn scale_token(session: i32, i: usize) -> i32 { + if i < 4 * SCALE_BLOCK_TOKENS { + (i as i32 * 31) % 247_000 + 1 + } else { + ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 + } +} + +fn scale_mean(v: &[f64]) -> f64 { + v.iter().sum::() / v.len() as f64 +} + +fn scale_max(v: &[f64]) -> f64 { + v.iter().cloned().fold(0.0, f64::max) +} + +/// The state of the scale simulation: the store, each session's history length and the measurements. +struct ScaleRun { + s: PrefixStore, + lengths: Vec, + match_us: Vec, + policy_us: Vec, + reused: usize, + prompt_total: usize, +} + +impl ScaleRun { + fn new(sessions: usize) -> Self { + let s = PrefixStore::::new(StoreConfig { + block_tokens: SCALE_BLOCK_TOKENS, + budget_bytes: 13 << 30, + max_nodes: 1024, + policy: PolicyParams::default(), + }); + Self { + s, + lengths: vec![8_192usize; sessions], + match_us: Vec::new(), + policy_us: Vec::new(), + reused: 0, + prompt_total: 0, + } + } + + /// One request of `session`: the lookup, the hit/miss record, then the admission of its grid points. + fn request(&mut self, session: usize) { + let n = self.lengths[session]; + let prompt: Vec = (0..n).map(|i| scale_token(session as i32, i)).collect(); + self.s.tick(n); + let limit = n - 1; + let started = std::time::Instant::now(); + let hit = self.s.longest_match(&prompt, limit); + self.match_us.push(started.elapsed().as_secs_f64() * 1e6); + let resume = hit.map_or(0, |m| m.tokens); + match hit { + Some(m) => self.s.record_hit(&m), + None => self.s.record_miss(), + } + self.reused += resume; + self.prompt_total += limit; + self.admit_grid_points(&prompt, limit, resume); + assert!(self.s.bytes() <= self.s.config().budget_bytes); + self.lengths[session] += 4_096; + } + + fn admit_grid_points(&mut self, prompt: &[i32], limit: usize, resume: usize) { + let last_grid = limit / SCALE_BLOCK_TOKENS * SCALE_BLOCK_TOKENS; + let started = std::time::Instant::now(); + let mut end = (resume / SCALE_BLOCK_TOKENS + 1) * SCALE_BLOCK_TOKENS; + while end <= last_grid { + let consider = self.s.consider(&prompt[..end], end == last_grid, SCALE_STATE_BYTES, SCALE_BLOCK_BYTES); + if let Consider::Admit(c) = consider { + let blocks = c.missing.iter().map(|j| (*j, Payload(SCALE_BLOCK_BYTES))).collect(); + self.s.commit(c, &prompt[..end], Payload(SCALE_STATE_BYTES), blocks).unwrap(); + } + end += SCALE_BLOCK_TOKENS; + } + self.policy_us.push(started.elapsed().as_secs_f64() * 1e6); + } + + fn report(&self, longest: usize) { + let s = &self.s; + eprintln!( + concat!( + "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; ", + "policy per request mean {:.0} us max {:.0} us; ", + "nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}" + ), + self.match_us.len(), + 100.0 * self.reused as f64 / self.prompt_total as f64, + scale_mean(&self.match_us), + scale_max(&self.match_us), + scale_mean(&self.policy_us), + scale_max(&self.policy_us), + s.node_count(), + s.block_count(), + s.bytes() >> 20, + s.config().budget_bytes >> 20, + s.stats().admitted, + s.stats().rejected, + s.stats().evicted, + longest = longest + ); + } +} + /// The pool at the production size, model-free: 12 agent sessions behind one runtime, an 8k shared system prompt, /// histories growing by 4k tokens per request up to 180k, interleaved round robin, 2048-token blocks, the sizes a real /// node and block have (127 MB of state, 29 MB per block) against a 13 GB budget. Checks the budget, the hit rate, the /// cost of the policy and of a lookup over a 180k-token prompt. #[test] -#[ignore = "scale simulation, seconds in release: cargo test --release -p leleka-runtime --lib -- --ignored twelve_sessions"] +#[ignore = "scale simulation, seconds in release: cargo test --release -p leleka-runtime --lib -- \ + --ignored twelve_sessions"] fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_stays_fast() { - const BLOCK_TOKENS: usize = 2048; - const STATE_BYTES: usize = 127 << 20; - const BLOCK_BYTES: usize = 29 << 20; - let mut s = PrefixStore::::new(StoreConfig { - block_tokens: BLOCK_TOKENS, - budget_bytes: 13 << 30, - max_nodes: 1024, - policy: PolicyParams::default(), - }); - let token = |session: i32, i: usize| -> i32 { - if i < 4 * BLOCK_TOKENS { - (i as i32 * 31) % 247_000 + 1 - } else { - ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 - } - }; let sessions = 12; - let mut lengths = vec![8_192usize; sessions]; - let (mut match_us, mut policy_us) = (Vec::new(), Vec::new()); - let (mut reused, mut prompt_total) = (0usize, 0usize); + let mut run = ScaleRun::new(sessions); for _round in 0..43 { for session in 0..sessions { - let n = lengths[session]; - let prompt: Vec = (0..n).map(|i| token(session as i32, i)).collect(); - s.tick(n); - let limit = n - 1; - let started = std::time::Instant::now(); - let hit = s.longest_match(&prompt, limit); - match_us.push(started.elapsed().as_secs_f64() * 1e6); - let resume = hit.map_or(0, |m| m.tokens); - match hit { - Some(m) => s.record_hit(&m), - None => s.record_miss(), - } - reused += resume; - prompt_total += limit; - let last_grid = limit / BLOCK_TOKENS * BLOCK_TOKENS; - let started = std::time::Instant::now(); - let mut end = (resume / BLOCK_TOKENS + 1) * BLOCK_TOKENS; - while end <= last_grid { - if let Consider::Admit(c) = s.consider(&prompt[..end], end == last_grid, STATE_BYTES, BLOCK_BYTES) { - let blocks = c.missing.iter().map(|j| (*j, Payload(BLOCK_BYTES))).collect(); - s.commit(c, &prompt[..end], Payload(STATE_BYTES), blocks).unwrap(); - } - end += BLOCK_TOKENS; - } - policy_us.push(started.elapsed().as_secs_f64() * 1e6); - assert!(s.bytes() <= s.config().budget_bytes); - lengths[session] += 4_096; + run.request(session); } } - s.check_invariants(); - let longest = lengths.iter().max().copied().unwrap(); - let mean = |v: &[f64]| v.iter().sum::() / v.len() as f64; - let max = |v: &[f64]| v.iter().cloned().fold(0.0, f64::max); - eprintln!( - "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; policy per request mean {:.0} us max {:.0} us; nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}", - match_us.len(), - 100.0 * reused as f64 / prompt_total as f64, - mean(&match_us), - max(&match_us), - mean(&policy_us), - max(&policy_us), - s.node_count(), - s.block_count(), - s.bytes() >> 20, - s.config().budget_bytes >> 20, - s.stats().admitted, - s.stats().rejected, - s.stats().evicted - ); + run.s.check_invariants(); + let longest = run.lengths.iter().max().copied().unwrap(); + run.report(longest); assert!(longest >= 170_000); + let s = &run.s; // the cache is smaller than the sum of the histories (12 x ~90k tokens on average = 15 GB of blocks alone): it must // have chosen assert!(s.stats().evicted > 0 || s.stats().rejected > 0); // a lookup over a 180k-token prompt (hashing and comparing every token) is milliseconds even in a debug build - assert!(max(&match_us) < 200_000.0, "{} us", max(&match_us)); - assert!(max(&policy_us) < 2_000_000.0, "{} us", max(&policy_us)); + assert!(scale_max(&run.match_us) < 200_000.0, "{} us", scale_max(&run.match_us)); + assert!(scale_max(&run.policy_us) < 2_000_000.0, "{} us", scale_max(&run.policy_us)); // sessions keep resuming close to their frontier: the hit rate stays high - assert!(reused as f64 / prompt_total as f64 > 0.5); + assert!(run.reused as f64 / run.prompt_total as f64 > 0.5); } diff --git a/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs b/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs index b764a723..355cda4e 100644 --- a/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs +++ b/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs @@ -109,20 +109,20 @@ fn a_checkpoint_between_two_grid_points_is_matched_exactly_and_supersedes_the_on let mut other = a.clone(); other[3 * G + 2] += 1; assert_eq!(s.longest_match(&other, other.len()).unwrap().tokens, 3 * G); + a_later_tail_supersedes_the_earlier_one(&mut s, &a); +} + +fn a_later_tail_supersedes_the_earlier_one(s: &mut PrefixStore, a: &[i32]) { // the next request of the session ends later: its node supersedes the first one let nodes = s.node_count(); - assert_eq!(put_tail(&mut s, &a, 3 * G + 7), Consider::Exists); + assert_eq!(put_tail(s, a, 3 * G + 7), Consider::Exists); assert_eq!(s.node_count(), nodes, "one added, one superseded"); - assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 3 * G + 7); + assert_eq!(s.longest_match(a, a.len()).unwrap().tokens, 3 * G + 7); // a tail that starts a new block after a later grid point supersedes it too - put(&mut s, &a, 4, true); - assert_eq!(put_tail(&mut s, &a, 4 * G + 3), Consider::Exists); - assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 4 * G + 3); - assert_eq!( - s.longest_match(&a, 4 * G + 2).unwrap().tokens, - 4 * G, - "the older tails are gone, the grid nodes remain" - ); + put(s, a, 4, true); + assert_eq!(put_tail(s, a, 4 * G + 3), Consider::Exists); + assert_eq!(s.longest_match(a, a.len()).unwrap().tokens, 4 * G + 3); + assert_eq!(s.longest_match(a, 4 * G + 2).unwrap().tokens, 4 * G, "the older tails are gone, the grid nodes remain"); // summaries and router queries only know grid nodes assert!(s.heads().iter().all(|h| h.1 % G == 0)); assert_eq!(s.heads_by_value().len(), s.heads().len()); diff --git a/crates/engine-core/src/prompt/grid_tests.rs b/crates/engine-core/src/prompt/grid_tests.rs index a1436a6b..dd609bf7 100644 --- a/crates/engine-core/src/prompt/grid_tests.rs +++ b/crates/engine-core/src/prompt/grid_tests.rs @@ -10,6 +10,22 @@ fn cuts(tokens: &[u32], resume: usize, o: PromptOptions, capacity: usize) -> Vec .collect() } +fn assert_cuts_sit_on_the_grid_and_a_resume_reads_the_rest(tokens: &[u32], o: PromptOptions, capacity: usize) { + let full = cuts(tokens, 0, o, capacity); + let (last, rest) = full.split_last().unwrap(); + assert!(rest.iter().all(|(first, count)| (first + count) % 512 == 0), "{capacity}: {full:?}"); + assert_eq!(last.0 + last.1, 4999); + assert!(full.iter().all(|(_, count)| *count <= capacity.min(512))); + // contiguous + assert!(full.windows(2).all(|w| w[0].0 + w[0].1 == w[1].0)); + // resuming on any grid point reads exactly the remaining chunks of the full read + for resume in [512usize, 1024, 2560, 4608] { + let read = cuts(tokens, resume, o, capacity); + let expected: Vec<_> = full.iter().copied().filter(|(first, _)| *first >= resume).collect(); + assert_eq!(read, expected, "capacity {capacity} resume {resume}"); + } +} + #[test] fn a_grid_puts_every_chunk_end_but_the_last_on_a_multiple_and_a_resume_on_the_grid_reads_the_same_chunks() { let o = PromptOptions { @@ -25,19 +41,7 @@ fn a_grid_puts_every_chunk_end_but_the_last_on_a_multiple_and_a_resume_on_the_gr tokens[300] = 248_045; tokens[3000] = 248_045; for capacity in [512, 1024, 2048, 8192] { - let full = cuts(&tokens, 0, o, capacity); - let (last, rest) = full.split_last().unwrap(); - assert!(rest.iter().all(|(first, count)| (first + count) % 512 == 0), "{capacity}: {full:?}"); - assert_eq!(last.0 + last.1, 4999); - assert!(full.iter().all(|(_, count)| *count <= capacity.min(512))); - // contiguous - assert!(full.windows(2).all(|w| w[0].0 + w[0].1 == w[1].0)); - // resuming on any grid point reads exactly the remaining chunks of the full read - for resume in [512usize, 1024, 2560, 4608] { - let read = cuts(&tokens, resume, o, capacity); - let expected: Vec<_> = full.iter().copied().filter(|(first, _)| *first >= resume).collect(); - assert_eq!(read, expected, "capacity {capacity} resume {resume}"); - } + assert_cuts_sit_on_the_grid_and_a_resume_reads_the_rest(&tokens, o, capacity); } // a prompt that ends inside a block has a short last chunk, and a short prompt a single one assert_eq!(cuts(&tokens[..700], 0, o, 2048), vec![(0, 512), (512, 187)]); diff --git a/crates/engine-core/src/prompt/tests.rs b/crates/engine-core/src/prompt/tests.rs index 02465ae3..f030f6d2 100644 --- a/crates/engine-core/src/prompt/tests.rs +++ b/crates/engine-core/src/prompt/tests.rs @@ -3,25 +3,20 @@ use super::*; // Independent literal Original control flow FIRST; no session/device proof. -fn original( - tokens: &[u32], - resume: usize, - reread: Option, - pictures: Option<&[bool]>, - o: PromptOptions, - cap: usize, -) -> Vec { - let n = tokens.len(); +fn original_turn(tokens: &[u32], resume: usize, o: PromptOptions) -> Option { let mut turn = None; if o.prompt_cache { - for i in (resume + 1..n).rev() { + for i in (resume + 1..tokens.len()).rev() { if Some(tokens[i]) == o.turn_token { turn = Some(i); break; } } } - let from = if reread.is_some() { 0 } else { resume }; + turn +} + +fn original_root(tokens: &[u32], from: usize, turn: Option, o: PromptOptions) -> Option { let mut root = None; if o.prompt_cache && o.root_min > 0 && from == 0 { for i in 1..turn.unwrap_or(0) { @@ -33,41 +28,78 @@ fn original( } } } + root +} + +struct OriginalSegment<'a> { + pictures: Option<&'a [bool]>, + o: PromptOptions, + cap: usize, + turn: Option, + root: Option, +} + +fn original_segment(actions: &mut Vec, at: &mut usize, to: usize, seg: &OriginalSegment) { + let (o, pictures) = (seg.o, seg.pictures); + let windows = + !o.force_batched && to - *at <= o.short_read && !pictures.is_some_and(|p| p[*at..to].iter().any(|v| *v)); + let capacity = ((to - *at + 255) / 256 * 256).min(seg.cap); + while *at < to { + let count = (if windows { o.verify_width } else { capacity }).min(to - *at); + let first = *at; + *at += count; + actions.push(PromptAction { + first, + count, + path: if windows { PromptPath::Verify } else { PromptPath::Batched { capacity } }, + checkpoint_after: *at == to && (Some(to) == seg.turn || Some(to) == seg.root), + }); + } +} + +fn original( + tokens: &[u32], + resume: usize, + reread: Option, + pictures: Option<&[bool]>, + o: PromptOptions, + cap: usize, +) -> Vec { + let n = tokens.len(); + let turn = original_turn(tokens, resume, o); + let from = if reread.is_some() { 0 } else { resume }; + let root = original_root(tokens, from, turn, o); + let seg = OriginalSegment { pictures, o, cap, turn, root }; let mut actions = Vec::new(); let mut at = from; for to in [reread.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), n - 1] { if to <= at { continue; } - let windows = - !o.force_batched && to - at <= o.short_read && !pictures.is_some_and(|p| p[at..to].iter().any(|v| *v)); - let capacity = ((to - at + 255) / 256 * 256).min(cap); - while at < to { - let count = (if windows { o.verify_width } else { capacity }).min(to - at); - let first = at; - at += count; - actions.push(PromptAction { - first, - count, - path: if windows { PromptPath::Verify } else { PromptPath::Batched { capacity } }, - checkpoint_after: at == to && (Some(to) == turn || Some(to) == root), - }); - } + original_segment(&mut actions, &mut at, to, &seg); } actions.push(PromptAction { first: n - 1, count: 1, path: PromptPath::FinalSeed, checkpoint_after: false }); actions } -#[test] -fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { - let o = PromptOptions::original_mode17(262144); + +fn sanitized_frame() -> Vec { // Sanitized IDs reproduce only known turn-boundary positions; no model // payload, tokenizer output or expected greedy output is embedded. let mut frame = vec![17; 202]; for i in [0, 17, 195] { frame[i] = 248045; } - let baseline = original(&frame, 0, None, None, o, 8192); - let candidate: Vec<_> = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap().collect(); + frame +} + +fn assert_plan_matches_original(frame: &[u32], options: PromptOptions) { + let baseline = original(frame, 0, None, None, options, 8192); + assert_eq!(baseline, PromptPlan::new(frame, 0, None, None, options, 8192).unwrap().collect::>()); +} + +fn assert_first_frame_plan(frame: &[u32], o: PromptOptions) { + let baseline = original(frame, 0, None, None, o, 8192); + let candidate: Vec<_> = PromptPlan::new(frame, 0, None, None, o, 8192).unwrap().collect(); assert_eq!(baseline, candidate); assert_eq!( candidate.iter().map(|a| (a.first, a.count, a.path)).collect::>(), @@ -78,6 +110,28 @@ fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { (201, 1, PromptPath::FinalSeed) ] ); +} + +fn assert_sweep_case_matches_original(tokens: &[u32], resume: usize, reread: Option, options: PromptOptions) { + let n = tokens.len(); + let baseline = original(tokens, resume, reread, None, options, 8192); + let candidate: Vec<_> = PromptPlan::new(tokens, resume, reread, None, options, 8192).unwrap().collect(); + assert_eq!(baseline, candidate); + assert_eq!(candidate.last().unwrap().first, n - 1); + assert!(candidate.iter().all(|a| a.count > 0 && a.first + a.count <= n)); +} + +fn sweep_options(o: PromptOptions) -> Vec { + let mut all = Vec::new(); + for cache in [false, true] { + for forced in [false, true] { + all.push(PromptOptions { prompt_cache: cache, force_batched: forced, root_min: 64, ..o }); + } + } + all +} + +fn assert_sweep_matches_original(o: PromptOptions) { for n in [1, 64, 65, 256, 8193, 16386] { let mut tokens = vec![7; n]; if n > 70 { @@ -85,24 +139,15 @@ fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { } for resume in [0, n.saturating_sub(8)] { for reread in [None, (resume > 0).then_some(resume)] { - for cache in [false, true] { - for forced in [false, true] { - let options = PromptOptions { prompt_cache: cache, force_batched: forced, root_min: 64, ..o }; - let baseline = original(&tokens, resume, reread, None, options, 8192); - let candidate: Vec<_> = - PromptPlan::new(&tokens, resume, reread, None, options, 8192).unwrap().collect(); - assert_eq!(baseline, candidate); - assert_eq!(candidate.last().unwrap().first, n - 1); - assert!(candidate.iter().all(|a| a.count > 0 && a.first + a.count <= n)); - } + for options in sweep_options(o) { + assert_sweep_case_matches_original(&tokens, resume, reread, options); } } } } - let mut pictures = vec![false; 202]; - pictures[199] = true; - let baseline = original(&frame, 0, None, Some(&pictures), o, 8192); - assert_eq!(baseline, PromptPlan::new(&frame, 0, None, Some(&pictures), o, 8192).unwrap().collect::>()); +} + +fn assert_auto_capacity_and_request_capacity() { let mut visited = Vec::new(); assert_eq!( choose_auto_capacity(262144, 8192, 1000, 85, |cap| { @@ -116,17 +161,33 @@ fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { assert_eq!(request_capacity(195, 8192), Ok(256)); assert_eq!(request_capacity(8193, 8192), Ok(8192)); assert_eq!(request_capacity(usize::MAX, 8192), Ok(8192)); - for options in [PromptOptions { root_min: 1, ..o }, PromptOptions { short_read: 0, ..o }] { - let baseline = original(&frame, 0, None, None, options, 8192); - assert_eq!(baseline, PromptPlan::new(&frame, 0, None, None, options, 8192).unwrap().collect::>()); - } - assert!(PromptPlan::new(&frame, 202, None, None, o, 8192).is_err()); - assert!(PromptPlan::new(&frame, 0, Some(1), None, o, 8192).is_err()); - assert!(PromptPlan::new(&frame, 0, None, Some(&pictures[..201]), o, 8192).is_err()); - assert!(PromptPlan::new(&frame, 0, None, None, o, 0).is_err()); +} + +fn assert_invalid_plans_are_refused(frame: &[u32], pictures: &[bool], o: PromptOptions) { + assert!(PromptPlan::new(frame, 202, None, None, o, 8192).is_err()); + assert!(PromptPlan::new(frame, 0, Some(1), None, o, 8192).is_err()); + assert!(PromptPlan::new(frame, 0, None, Some(&pictures[..201]), o, 8192).is_err()); + assert!(PromptPlan::new(frame, 0, None, None, o, 0).is_err()); assert!(choose_auto_capacity(262144, 8192, 128, 85, |_| Ok(1)).unwrap().is_none()); } +#[test] +fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { + let o = PromptOptions::original_mode17(262144); + let frame = sanitized_frame(); + assert_first_frame_plan(&frame, o); + assert_sweep_matches_original(o); + let mut pictures = vec![false; 202]; + pictures[199] = true; + let baseline = original(&frame, 0, None, Some(&pictures), o, 8192); + assert_eq!(baseline, PromptPlan::new(&frame, 0, None, Some(&pictures), o, 8192).unwrap().collect::>()); + assert_auto_capacity_and_request_capacity(); + for options in [PromptOptions { root_min: 1, ..o }, PromptOptions { short_read: 0, ..o }] { + assert_plan_matches_original(&frame, options); + } + assert_invalid_plans_are_refused(&frame, &pictures, o); +} + struct Recorder { log: Vec<(&'static str, usize, usize)>, stop_after: Option, @@ -158,16 +219,15 @@ impl PromptRunner for Recorder { } } -#[test] -fn drive_executes_a_plan_in_order_with_checkpoints_and_the_final_seed() { - let o = PromptOptions::original_mode17(262144); - let mut frame = vec![17; 202]; - for i in [0, 17, 195] { - frame[i] = 248045; - } - let plan = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap(); +fn recorded_drive(tokens: &[u32], resume: usize, o: PromptOptions) -> (Recorder, DriveSummary) { + let plan = PromptPlan::new(tokens, resume, None, None, o, 8192).unwrap(); let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; let s = drive(plan, 8192, &mut r).unwrap(); + (r, s) +} + +fn assert_the_frame_is_driven_in_order(o: PromptOptions) { + let (r, s) = recorded_drive(&sanitized_frame(), 0, o); assert_eq!( r.log, vec![("batched", 0, 195), ("checkpoint", 195, 0), ("verify", 195, 4), ("verify", 199, 2), ("seed", 201, 1)] @@ -185,20 +245,22 @@ fn drive_executes_a_plan_in_order_with_checkpoints_and_the_final_seed() { ), (1, 195, 2, 6, 1, true, 0, 202) ); +} + +#[test] +fn drive_executes_a_plan_in_order_with_checkpoints_and_the_final_seed() { + let o = PromptOptions::original_mode17(262144); + assert_the_frame_is_driven_in_order(o); // a long segment is cut into admitted-capacity chunks let long = vec![7; 20000]; - let plan = PromptPlan::new(&long, 0, None, None, o, 8192).unwrap(); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - let s = drive(plan, 8192, &mut r).unwrap(); + let (r, s) = recorded_drive(&long, 0, o); assert_eq!( r.log.iter().map(|e| (e.0, e.2)).collect::>(), vec![("batched", 8192), ("batched", 8192), ("batched", 3615), ("seed", 1)] ); assert_eq!((s.batched_rows, s.end), (19999, 20000)); // resume from a cached prefix: positions start there and stay contiguous - let plan = PromptPlan::new(&long, 12000, None, None, o, 8192).unwrap(); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - let s = drive(plan, 8192, &mut r).unwrap(); + let (r, s) = recorded_drive(&long, 12000, o); assert_eq!(s.first, 12000); assert_eq!(r.log.first().map(|e| e.1), Some(12000)); } diff --git a/crates/engine-core/src/spec/adaptive/tests.rs b/crates/engine-core/src/spec/adaptive/tests.rs index 5e23d40c..8a8df3ad 100644 --- a/crates/engine-core/src/spec/adaptive/tests.rs +++ b/crates/engine-core/src/spec/adaptive/tests.rs @@ -50,6 +50,55 @@ const REPEAT: World = World { suffix_match: 40, }; +/// Number of leading draws below `q`, at most `n`. +fn sim_hits(rng: &mut Rng, q: f64, n: usize) -> usize { + let mut a = 0; + while a < n && rng.next() < q { + a += 1; + } + a +} + +fn sim_accept_mtp(rng: &mut Rng, world: &World, probs: &[f32], rows: usize) -> usize { + let mut a = 0; + while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { + a += 1; + } + a +} + +fn sim_cost(world: &World, noise: f64, t: usize) -> f64 { + (world.base + world.slope * (t - 1) as f64) * noise +} + +fn play_policy( + world: &World, + rng: &mut Rng, + pol: &mut AdaptivePolicy, + probs: &[f32], + noise: f64, +) -> (usize, f64, usize) { + let offer = + Offer { mtp_probs: probs, suffix_k: world.suffix_len, suffix_match: world.suffix_match, suffix_agrees: true }; + let c = pol.choose(&offer); + let a = match c.origin { + Origin::Mtp => sim_accept_mtp(rng, world, probs, c.t - 1), + Origin::Suffix => sim_hits(rng, world.suffix_q, c.t - 1), + }; + let ms = sim_cost(world, noise, c.t) + 0.45 * probs.len().min(4) as f64; + pol.observe(&c, a, ms, probs.len().min(4)); + (a + 1, ms, c.t) +} + +fn play_fixed(world: &World, rng: &mut Rng, t: usize, probs: &[f32], noise: f64) -> (usize, f64, usize) { + let a = if world.suffix_len > 0 && world.suffix_q > 0.9 && t - 1 <= world.suffix_len { + sim_hits(rng, world.suffix_q, t - 1) + } else { + sim_accept_mtp(rng, world, probs, t - 1) + }; + (a + 1, sim_cost(world, noise, t) + 0.45 * 3.0, t) +} + /// One policy-driven (`fixed == None`) or fixed-width round; returns (tokens, ms, t). fn play( world: &World, @@ -60,47 +109,10 @@ fn play( let max_t = 8; let probs: Vec = (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect(); - let hits = |rng: &mut Rng, q: f64, n: usize| -> usize { - let mut a = 0; - while a < n && rng.next() < q { - a += 1; - } - a - }; - let accept_mtp = |rng: &mut Rng, rows: usize| -> usize { - let mut a = 0; - while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { - a += 1; - } - a - }; let noise = 1.0 + 0.04 * (rng.next() - 0.5); - let cost = |t: usize| (world.base + world.slope * (t - 1) as f64) * noise; match (policy, fixed) { - (Some(pol), _) => { - let offer = Offer { - mtp_probs: &probs, - suffix_k: world.suffix_len, - suffix_match: world.suffix_match, - suffix_agrees: true, - }; - let c = pol.choose(&offer); - let a = match c.origin { - Origin::Mtp => accept_mtp(rng, c.t - 1), - Origin::Suffix => hits(rng, world.suffix_q, c.t - 1), - }; - let ms = cost(c.t) + 0.45 * probs.len().min(4) as f64; - pol.observe(&c, a, ms, probs.len().min(4)); - (a + 1, ms, c.t) - } - (None, Some(t)) => { - let a = if world.suffix_len > 0 && world.suffix_q > 0.9 && t - 1 <= world.suffix_len { - hits(rng, world.suffix_q, t - 1) - } else { - accept_mtp(rng, t - 1) - }; - (a + 1, cost(t) + 0.45 * 3.0, t) - } + (Some(pol), _) => play_policy(world, rng, pol, &probs, noise), + (None, Some(t)) => play_fixed(world, rng, t, &probs, noise), _ => unreachable!(), } } diff --git a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs index 55c0513f..17a274c4 100644 --- a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs +++ b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs @@ -5,12 +5,7 @@ #[allow(unused_imports)] use super::*; -#[test] -fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { - let new = AdaptiveConfig::new(8, 7); - assert_eq!(new.min_p_hi, FLOOR_CEILING); - let legacy = new.with_policy(Some("legacy")); - assert_eq!(legacy.min_p_hi, 0.90); +fn assert_legacy_is_the_earlier_policy_but_for_the_ceiling(new: AdaptiveConfig, legacy: AdaptiveConfig) { // everything but the ceiling is the earlier policy's, field by field let earlier = AdaptiveConfig { max_t: 8, @@ -31,6 +26,15 @@ fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_pol assert_eq!(new.with_policy(Some("v1")), earlier); assert_eq!(new.with_policy(None), new); assert_eq!(new.with_policy(Some("current")), new); +} + +#[test] +fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { + let new = AdaptiveConfig::new(8, 7); + assert_eq!(new.min_p_hi, FLOOR_CEILING); + let legacy = new.with_policy(Some("legacy")); + assert_eq!(legacy.min_p_hi, 0.90); + assert_legacy_is_the_earlier_policy_but_for_the_ceiling(new, legacy); // a request that names a ceiling keeps it in both policies; one that does not gets the policy's for (cfg, want) in [(new, FLOOR_CEILING), (legacy, 0.90)] { let mut pol = AdaptivePolicy::new(cfg); diff --git a/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs b/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs index a94034a2..da6536cc 100644 --- a/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs +++ b/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs @@ -25,37 +25,47 @@ fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() { assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]); } +/// The rate of the oracle that knows each segment's best fixed width. +fn per_segment_oracle(seq: &[(World, usize)]) -> f64 { + let (mut tok, mut ms) = (0.0, 0.0); + for &(w, n) in seq { + let (_, r) = best_fixed(&w); + tok += r * n as f64 * 1.0; + ms += n as f64; + } + let _ = (tok, ms); + seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() / seq.iter().map(|(_, n)| *n as f64).sum::() +} + +/// The rate of one fixed width over the whole sequence. +fn whole_sequence_rate(seq: &[(World, usize)], t: usize) -> f64 { + let mut rng = Rng(3); + let (mut tk, mut m) = (0usize, 0.0); + for &(w, n) in seq { + for _ in 0..n { + let (a, c, _) = play(&w, &mut rng, None, Some(t)); + tk += a; + m += c; + } + } + tk as f64 / m +} + #[test] fn it_follows_a_change_of_content_and_of_cost() { let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)]; let (rate, tail) = adaptive_run(&seq, cfg()); assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}"); // against the oracle that knows each segment's best fixed width - let (mut tok, mut ms) = (0.0, 0.0); - for (w, n) in seq { - let (_, r) = best_fixed(&w); - tok += r * n as f64 * 1.0; - ms += n as f64; - } - let _ = (tok, ms); - let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() - / seq.iter().map(|(_, n)| *n as f64).sum::(); + let oracle = per_segment_oracle(&seq); assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}"); // and it beats every single fixed width over the whole sequence - let whole = |t: usize| -> f64 { - let mut rng = Rng(3); - let (mut tk, mut m) = (0usize, 0.0); - for (w, n) in seq { - for _ in 0..n { - let (a, c, _) = play(&w, &mut rng, None, Some(t)); - tk += a; - m += c; - } - } - tk as f64 / m - }; for t in 1..=8 { - assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t)); + assert!( + rate >= whole_sequence_rate(&seq, t) * 0.995, + "fixed {t}: {:.5} vs adaptive {rate:.5}", + whole_sequence_rate(&seq, t) + ); } } @@ -215,35 +225,39 @@ fn replay_arm_options_set_the_named_constants_and_refuse_the_unknown() { assert_eq!(c, before); } +fn assert_the_plans_follow_the_earlier_rule_in(world: World, rng: &mut Rng) { + let mut pol = AdaptivePolicy::new(cfg()); + let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); + cheaper.row_q = 0.5; + smooth.smooth_floor = true; + measured.measured_rate = true; + let (mut pc, mut ps, mut pm) = + (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); + for i in 0..600 { + let mut r2 = Rng(i + 3); + play(&world, rng, Some(&mut pol), None); + play(&world, &mut r2, Some(&mut pc), None); + let mut r3 = Rng(i + 3); + play(&world, &mut r3, Some(&mut ps), None); + let mut r4 = Rng(i + 3); + play(&world, &mut r4, Some(&mut pm), None); + assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); + let l = legacy_plan(&pc); + assert!( + pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, + "row_q 0.5 raised the floor at round {i}" + ); + let sp = ps.draft_plan().min_p; + assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); + let pl = pm.draft_plan(); + assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); + } +} + #[test] fn the_default_draft_plan_is_the_earlier_rule_and_the_new_options_only_lower_or_smooth_the_floor() { let mut rng = Rng(8); for world in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { - let mut pol = AdaptivePolicy::new(cfg()); - let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); - cheaper.row_q = 0.5; - smooth.smooth_floor = true; - measured.measured_rate = true; - let (mut pc, mut ps, mut pm) = - (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); - for i in 0..600 { - let mut r2 = Rng(i + 3); - play(&world, &mut rng, Some(&mut pol), None); - play(&world, &mut r2, Some(&mut pc), None); - let mut r3 = Rng(i + 3); - play(&world, &mut r3, Some(&mut ps), None); - let mut r4 = Rng(i + 3); - play(&world, &mut r4, Some(&mut pm), None); - assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); - let l = legacy_plan(&pc); - assert!( - pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, - "row_q 0.5 raised the floor at round {i}" - ); - let sp = ps.draft_plan().min_p; - assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); - let pl = pm.draft_plan(); - assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); - } + assert_the_plans_follow_the_earlier_rule_in(world, &mut rng); } } diff --git a/crates/gateway-text/src/prompt/tests.rs b/crates/gateway-text/src/prompt/tests.rs index 982f0c58..8016451a 100644 --- a/crates/gateway-text/src/prompt/tests.rs +++ b/crates/gateway-text/src/prompt/tests.rs @@ -354,59 +354,5 @@ fn raise_exception_surfaces_the_template_message() { let _ = messages; } -#[test] -fn tojson_matches_python_json_dumps() { - let renderer = Renderer::new("{{ value | tojson }}").unwrap(); - let render = |json: &str| { - let value: Json = serde_json::from_str(json).unwrap(); - let mut context = BTreeMap::new(); - context.insert("value", Value::from_serialize(&value)); - renderer.env.get_template("chat").unwrap().render(&context).unwrap() - }; - assert_eq!( - render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#), - r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"# - ); - assert_eq!( - render(r#"["é", "\u0001", "\u007f", "😀", "\u2028"]"#), - "[\"é\", \"\\u0001\", \"\u{7f}\", \"😀\", \"\u{2028}\"]" - ); - assert_eq!( - render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"), - "[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]" - ); - assert_eq!(render("[18446744073709551615, -9223372036854775808]"), "[18446744073709551615, -9223372036854775808]"); -} - -#[test] -fn trim_is_pythons_strip() { - let renderer = Renderer::new("[{{ value | trim }}]").unwrap(); - let render = |text: &str| { - let mut context = BTreeMap::new(); - context.insert("value", Value::from(text)); - renderer.env.get_template("chat").unwrap().render(&context).unwrap() - }; - // U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space - assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]"); -} - -#[test] -fn objects_keep_the_order_they_were_written_in() { - let tools: Vec = - serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#) - .unwrap(); - let out = pinned() - .render(&ChatInput { - messages: &[Json::object([("role", Json::str("user")), ("content", Json::str("x"))])], - tools: Some(&tools), - add_generation_prompt: true, - kwargs: vec![("enable_thinking", Json::Bool(false))], - }) - .unwrap(); - assert!( - out.contains( - r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"# - ), - "{out}" - ); -} +#[path = "tests/jinja_filters.rs"] +mod jinja_filters; diff --git a/crates/gateway-text/src/prompt/tests/jinja_filters.rs b/crates/gateway-text/src/prompt/tests/jinja_filters.rs new file mode 100644 index 00000000..1a5bd40c --- /dev/null +++ b/crates/gateway-text/src/prompt/tests/jinja_filters.rs @@ -0,0 +1,61 @@ +//! Tests of the `tojson` and `trim` filters and of object key order (moved out of `tests.rs` by STRA-338 size6). + +#[allow(unused_imports)] +use super::*; + +#[test] +fn tojson_matches_python_json_dumps() { + let renderer = Renderer::new("{{ value | tojson }}").unwrap(); + let render = |json: &str| { + let value: Json = serde_json::from_str(json).unwrap(); + let mut context = BTreeMap::new(); + context.insert("value", Value::from_serialize(&value)); + renderer.env.get_template("chat").unwrap().render(&context).unwrap() + }; + assert_eq!( + render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#), + r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"# + ); + assert_eq!( + render(r#"["é", "\u0001", "\u007f", "😀", "\u2028"]"#), + "[\"é\", \"\\u0001\", \"\u{7f}\", \"😀\", \"\u{2028}\"]" + ); + assert_eq!( + render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"), + "[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]" + ); + assert_eq!(render("[18446744073709551615, -9223372036854775808]"), "[18446744073709551615, -9223372036854775808]"); +} + +#[test] +fn trim_is_pythons_strip() { + let renderer = Renderer::new("[{{ value | trim }}]").unwrap(); + let render = |text: &str| { + let mut context = BTreeMap::new(); + context.insert("value", Value::from(text)); + renderer.env.get_template("chat").unwrap().render(&context).unwrap() + }; + // U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space + assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]"); +} + +#[test] +fn objects_keep_the_order_they_were_written_in() { + let tools: Vec = + serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#) + .unwrap(); + let out = pinned() + .render(&ChatInput { + messages: &[Json::object([("role", Json::str("user")), ("content", Json::str("x"))])], + tools: Some(&tools), + add_generation_prompt: true, + kwargs: vec![("enable_thinking", Json::Bool(false))], + }) + .unwrap(); + assert!( + out.contains( + r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"# + ), + "{out}" + ); +} diff --git a/crates/leleka-memory/examples/swap_ab.rs b/crates/leleka-memory/examples/swap_ab.rs index 9c321b33..ca9ca8fb 100644 --- a/crates/leleka-memory/examples/swap_ab.rs +++ b/crates/leleka-memory/examples/swap_ab.rs @@ -65,12 +65,7 @@ fn sealed_memfd(bytes: u64) -> OwnedFd { } #[cfg(all(target_os = "linux", target_pointer_width = "64"))] -fn main() { - let memfd_mib = num("--memfd-mib", 4096); - let hog_mib = num("--hog-mib", 3072); - let secs = num("--secs", 60); - let lock = LockMode::parse(&arg("--lock").unwrap_or_else(|| "off".into())).expect("--lock off|try|require"); - let heal = num("--heal", 0) != 0; +fn open_governor(lock: LockMode, heal: bool) -> Governor { let mut cfg = GovernorConfig::from_env(64 << 30, false, &|k| std::env::var(k).ok()).expect("LELEKA_MEMORY_* overrides"); cfg.lock_mode = lock; @@ -79,85 +74,96 @@ fn main() { cfg.residency_every_ms = 1000; cfg.sample_interval_ms = 500; let _ = Policy::for_host(0, false); - let governor = Governor::real(cfg); + Governor::real(cfg) +} - let len = memfd_mib << 20; - let fd = sealed_memfd(len); - let report = governor.guard_archive(fd.as_fd(), len); - println!("AB guard: {:?}", report.as_ref().map(|r| r.outcome.clone()).map_err(|e| e.to_string())); - let _sampler = governor.spawn_sampler(); +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn spawn_hog(stop: Arc, hog_bytes: u64, hog_release: u64) -> std::thread::JoinHandle { + std::thread::spawn(move || { + let born = std::time::Instant::now(); + let mut v = vec![0u8; hog_bytes as usize]; + for i in (0..v.len()).step_by(4096) { + v[i] = 1; + } + // keep the hog hot: touch pages round robin, slowly + let mut at = 0usize; + // `--hog-release N`: the pressure goes away after N seconds (the other process exits, the cache is dropped) + while !stop.load(Ordering::Relaxed) && (hog_release == 0 || born.elapsed().as_secs() < hog_release) { + for _ in 0..2048 { + v[at] = v[at].wrapping_add(1); + at = (at + 4096) % v.len(); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + v[0] + }) +} - let stop = Arc::new(AtomicBool::new(false)); - let hog_bytes = hog_mib << 20; - let hog_release = num("--hog-release", 0); - let hog = { - let stop = stop.clone(); - std::thread::spawn(move || { - let born = std::time::Instant::now(); - let mut v = vec![0u8; hog_bytes as usize]; - for i in (0..v.len()).step_by(4096) { - v[i] = 1; - } - // keep the hog hot: touch pages round robin, slowly - let mut at = 0usize; - // `--hog-release N`: the pressure goes away after N seconds (the other process exits, the cache is dropped) - while !stop.load(Ordering::Relaxed) && (hog_release == 0 || born.elapsed().as_secs() < hog_release) { - for _ in 0..2048 { - v[at] = v[at].wrapping_add(1); - at = (at + 4096) % v.len(); - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - v[0] - }) - }; - let read_bytes = Arc::new(AtomicU64::new(0)); - let reader = arg("--reader").map(|path| { - let (stop, read_bytes) = (stop.clone(), read_bytes.clone()); - std::thread::spawn(move || { - use std::io::Read; - let mut buf = vec![0u8; 8 << 20]; +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn spawn_reader(path: String, stop: Arc, read_bytes: Arc) -> std::thread::JoinHandle<()> { + std::thread::spawn(move || { + use std::io::Read; + let mut buf = vec![0u8; 8 << 20]; + while !stop.load(Ordering::Relaxed) { + let Ok(mut f) = std::fs::File::open(&path) else { return }; while !stop.load(Ordering::Relaxed) { - let Ok(mut f) = std::fs::File::open(&path) else { return }; - while !stop.load(Ordering::Relaxed) { - match f.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(k) => { - read_bytes.fetch_add(k as u64, Ordering::Relaxed); - } + match f.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(k) => { + read_bytes.fetch_add(k as u64, Ordering::Relaxed); } } } - }) - }); + } + }) +} +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn print_second(governor: &Governor, t: u64, swapped: u64, read_bytes: &AtomicU64, last: &mut (u64, u64)) { + let facts = governor.probe(); + let (swp_in, swp_out) = (facts.pswpin.unwrap_or(0), facts.pswpout.unwrap_or(0)); + let own_swap = facts.status.vm_swap.unwrap_or(0); + println!( + concat!( + "AB t={t} memfd_swapped_mib={} own_vmswap_mib={} locked_mib={} pswpin+={} pswpout+={} reader_gib={} ", + "level={} cgroup_events={:?}" + ), + swapped >> 20, + own_swap >> 20, + facts.status.vm_lck.unwrap_or(0) >> 20, + swp_in.saturating_sub(last.0), + swp_out.saturating_sub(last.1), + read_bytes.load(Ordering::Relaxed) >> 30, + governor.level().as_str(), + facts.cgroup.as_ref().and_then(|c| c.events), + t = t, + ); + *last = (swp_in, swp_out); +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn sample_seconds(governor: &Governor, secs: u64, read_bytes: &AtomicU64) -> u64 { let mut max_swapped = 0u64; let mut last = (0u64, 0u64); for t in 0..secs { std::thread::sleep(std::time::Duration::from_secs(1)); let swapped = governor.residency_tick(); max_swapped = max_swapped.max(swapped); - let facts = governor.probe(); - let (swp_in, swp_out) = (facts.pswpin.unwrap_or(0), facts.pswpout.unwrap_or(0)); - let own_swap = facts.status.vm_swap.unwrap_or(0); - println!( - "AB t={t} memfd_swapped_mib={} own_vmswap_mib={} locked_mib={} pswpin+={} pswpout+={} reader_gib={} level={} cgroup_events={:?}", - swapped >> 20, - own_swap >> 20, - facts.status.vm_lck.unwrap_or(0) >> 20, - swp_in.saturating_sub(last.0), - swp_out.saturating_sub(last.1), - read_bytes.load(Ordering::Relaxed) >> 30, - governor.level().as_str(), - facts.cgroup.as_ref().and_then(|c| c.events), - ); - last = (swp_in, swp_out); - } - stop.store(true, Ordering::Relaxed); - let _ = hog.join(); - if let Some(r) = reader { - let _ = r.join(); + print_second(governor, t, swapped, read_bytes, &mut last); } + max_swapped +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn guard_sealed_archive(governor: &Governor, len: u64) -> OwnedFd { + let fd = sealed_memfd(len); + let report = governor.guard_archive(fd.as_fd(), len); + println!("AB guard: {:?}", report.as_ref().map(|r| r.outcome.clone()).map_err(|e| e.to_string())); + fd +} + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn print_result(governor: &Governor, (lock, heal): (LockMode, bool), max_swapped: u64) { let report = governor.report(); println!( "AB-RESULT lock={lock:?} heal={heal} max_memfd_swapped_mib={} final_memfd_swapped_mib={} heal_bytes_mib={}", @@ -166,3 +172,31 @@ fn main() { report["counters"]["heal_bytes"].as_u64().unwrap_or(0) >> 20 ); } + +#[cfg(all(target_os = "linux", target_pointer_width = "64"))] +fn main() { + let memfd_mib = num("--memfd-mib", 4096); + let hog_mib = num("--hog-mib", 3072); + let secs = num("--secs", 60); + let lock = LockMode::parse(&arg("--lock").unwrap_or_else(|| "off".into())).expect("--lock off|try|require"); + let heal = num("--heal", 0) != 0; + let governor = open_governor(lock, heal); + + let _fd = guard_sealed_archive(&governor, memfd_mib << 20); + let _sampler = governor.spawn_sampler(); + + let stop = Arc::new(AtomicBool::new(false)); + let hog_bytes = hog_mib << 20; + let hog_release = num("--hog-release", 0); + let hog = spawn_hog(stop.clone(), hog_bytes, hog_release); + let read_bytes = Arc::new(AtomicU64::new(0)); + let reader = arg("--reader").map(|path| spawn_reader(path, stop.clone(), read_bytes.clone())); + + let max_swapped = sample_seconds(&governor, secs, &read_bytes); + stop.store(true, Ordering::Relaxed); + let _ = hog.join(); + if let Some(r) = reader { + let _ = r.join(); + } + print_result(&governor, (lock, heal), max_swapped); +} diff --git a/crates/leleka-memory/src/governor/tests.rs b/crates/leleka-memory/src/governor/tests.rs index 76b0e5d8..0cc3a371 100644 --- a/crates/leleka-memory/src/governor/tests.rs +++ b/crates/leleka-memory/src/governor/tests.rs @@ -80,15 +80,19 @@ fn shedding_runs_in_order_prefix_cache_first_then_reject_with_retry_after() { assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "no second step within the same second"); // requests are still served while only shedding assert_eq!(g.admit(&SHAPE), Admission::Admit); + assert_the_hard_floor_rejects_and_memory_coming_back_restores(&h, &g); +} + +fn assert_the_hard_floor_rejects_and_memory_coming_back_restores(h: &Live, g: &Governor) { // below the hard floor: everything goes, new requests are refused with Retry-After - set_avail(&h, 1024); + set_avail(h, 1024); assert_eq!(g.sample_at(2000).unwrap().to, Level::Reject); assert_eq!(g.directive(6 * GIB).prefix_budget, Some(0)); let Admission::Refuse(r) = g.admit(&SHAPE) else { panic!("must refuse") }; assert_eq!((r.status, r.code), (503, "memory_pressure")); assert!(r.retry_after_secs >= 5); // memory comes back: three calm samples per step down, then the configured budget is restored - set_avail(&h, 30 * 1024); + set_avail(h, 30 * 1024); for i in 0..3 { g.sample_at(3000 + i * 1000); } diff --git a/crates/leleka-memory/src/host/tests.rs b/crates/leleka-memory/src/host/tests.rs index 7bacb754..45fa315d 100644 --- a/crates/leleka-memory/src/host/tests.rs +++ b/crates/leleka-memory/src/host/tests.rs @@ -2,9 +2,17 @@ use super::*; fn server() -> FakeProc { FakeProc::default() - .with("/proc/meminfo", "MemTotal: 127091644 kB\nMemAvailable: 20699384 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n") + .with( + "/proc/meminfo", + "MemTotal: 127091644 kB\nMemAvailable: 20699384 kB\nSwapTotal: 65535996 kB\nSwapFree: \ +65452100 kB\nShmem: 54338244 kB\n", + ) .with("/proc/self/status", "VmRSS: 100 kB\nVmPin: 52428800 kB\nThreads: 40\n") - .with("/proc/pressure/memory", "some avg10=0.00 avg60=0.01 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.01 avg300=0.00 total=1\n") + .with( + "/proc/pressure/memory", + "some avg10=0.00 avg60=0.01 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.01 \ +avg300=0.00 total=1\n", + ) .with("/proc/self/limits", "Max locked memory 8388608 8388608 bytes \n") .with("/proc/sys/kernel/osrelease", "7.0.0-38-generic\n") .with("/proc/vmstat", "pswpin 10\npswpout 20\n") diff --git a/crates/leleka-memory/src/lock/sys.rs b/crates/leleka-memory/src/lock/sys.rs index eb11b13f..496a20a8 100644 --- a/crates/leleka-memory/src/lock/sys.rs +++ b/crates/leleka-memory/src/lock/sys.rs @@ -366,10 +366,8 @@ mod tests { calls += 1; calls <= 3 }); - assert!( - matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), - "{outcome:?}" - ); + let LockOutcome::Partial { locked, wanted, .. } = outcome else { panic!("{outcome:?}") }; + assert_eq!((locked, wanted), (12 * PAGE, 16 * PAGE), "{outcome:?}"); assert_eq!(m.locked_bytes(), 12 * PAGE); m.unlock(); assert_eq!(m.locked_bytes(), 0); diff --git a/crates/leleka-memory/src/lock/tests.rs b/crates/leleka-memory/src/lock/tests.rs index 821fa22a..507f1ee7 100644 --- a/crates/leleka-memory/src/lock/tests.rs +++ b/crates/leleka-memory/src/lock/tests.rs @@ -86,7 +86,8 @@ fn already_locked_pages_count_against_the_limit() { #[test] fn residency_is_read_from_the_mapping_that_starts_at_our_address() { - let smaps = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\nSize: 4194304 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n"; + let smaps = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\nSize: 4194304 kB\n\ +Rss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n"; let r = residency_from_smaps(smaps, 0x7f00_0000_0000, 1 << 30).unwrap(); assert_eq!((r.swapped_bytes, r.rss_bytes), (194_304 * 1024, 4_000_000 * 1024)); assert!(residency_from_smaps(smaps, 0x1000, 1).is_none()); diff --git a/crates/leleka-memory/src/pressure/tests.rs b/crates/leleka-memory/src/pressure/tests.rs index c5198977..6b29e5cc 100644 --- a/crates/leleka-memory/src/pressure/tests.rs +++ b/crates/leleka-memory/src/pressure/tests.rs @@ -100,14 +100,12 @@ fn psi_stalls_shed_and_reject_independent_of_available_memory() { let t = m.update(&Sample { at_ms: 2000, available: Some(10 * GIB), psi: psi(40.0, 9.0), ..Sample::default() }).unwrap(); assert_eq!(t.to, Level::Reject); - // a quiet PSI recovers after the calm samples + a_quiet_psi_recovers_after_the_calm_samples(&mut m, psi(0.0, 0.0)); +} + +fn a_quiet_psi_recovers_after_the_calm_samples(m: &mut Monitor, quiet: Option) { for i in 0..3 { - m.update(&Sample { - at_ms: 3000 + i * 1000, - available: Some(10 * GIB), - psi: psi(0.0, 0.0), - ..Sample::default() - }); + m.update(&Sample { at_ms: 3000 + i * 1000, available: Some(10 * GIB), psi: quiet, ..Sample::default() }); } assert_eq!(m.level(), Level::Shed); } diff --git a/crates/leleka-memory/src/procfs/tests.rs b/crates/leleka-memory/src/procfs/tests.rs index d3eacff7..3e1ac2a9 100644 --- a/crates/leleka-memory/src/procfs/tests.rs +++ b/crates/leleka-memory/src/procfs/tests.rs @@ -2,9 +2,12 @@ use super::*; -const MEMINFO: &str = "MemTotal: 127091644 kB\nMemFree: 2612464 kB\nMemAvailable: 20699384 kB\nBuffers: 37200 kB\n\ -Cached: 73044620 kB\nSwapCached: 22052 kB\nSwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n\ -Mlocked: 8724 kB\nUnevictable: 8724 kB\nHugePages_Total: 0\nHugepagesize: 2048 kB\nHugetlb: 0 kB\n"; +const MEMINFO: &str = "MemTotal: 127091644 kB\nMemFree: 2612464 kB\nMemAvailable: 20699384 kB\n\ +Buffers: 37200 kB\n\ +Cached: 73044620 kB\nSwapCached: 22052 kB\n\ +SwapTotal: 65535996 kB\nSwapFree: 65452100 kB\nShmem: 54338244 kB\n\ +Mlocked: 8724 kB\nUnevictable: 8724 kB\nHugePages_Total: 0\n\ +Hugepagesize: 2048 kB\nHugetlb: 0 kB\n"; #[test] fn meminfo_reads_the_5090_server_snapshot() { @@ -37,7 +40,8 @@ fn meminfo_never_turns_a_malformed_or_duplicated_number_into_a_value() { #[test] fn status_reads_pinned_locked_and_swap() { - let t = "Name:\tleleka\nVmPeak:\t 1 kB\nVmPin:\t 52428800 kB\nVmHWM:\t 70000000 kB\nVmRSS:\t 61000000 kB\nRssAnon:\t 1000 kB\nRssFile:\t 2000 kB\n\ + let t = "Name:\tleleka\nVmPeak:\t 1 kB\nVmPin:\t 52428800 kB\nVmHWM:\t 70000000 kB\nVmRSS:\t 61000000 kB\n\ +RssAnon:\t 1000 kB\nRssFile:\t 2000 kB\n\ RssShmem:\t 3000 kB\nVmSwap:\t 12 kB\nVmLck:\t 8 kB\nThreads:\t 41\nCapEff:\t0000000000004000\n"; let s = parse_status(t); assert_eq!(s.vm_pin, Some(52_428_800 * 1024)); @@ -51,7 +55,9 @@ RssShmem:\t 3000 kB\nVmSwap:\t 12 kB\nVmLck:\t 8 kB\nThreads:\t 41\nCapEff:\t000 #[test] fn memlock_limit_reads_numbers_and_unlimited() { - let t = "Limit Soft Limit Hard Limit Units \nMax locked memory 8388608 8388608 bytes \nMax address space unlimited unlimited bytes \n"; + let t = "Limit Soft Limit Hard Limit Units \nMax locked \ +memory 8388608 8388608 bytes \nMax address space unlimited \ +unlimited bytes \n"; assert_eq!(parse_memlock_limit(t), Some((8 << 20, 8 << 20))); let u = "Max locked memory unlimited unlimited bytes \n"; assert_eq!(parse_memlock_limit(u), Some((u64::MAX, u64::MAX))); @@ -60,7 +66,8 @@ fn memlock_limit_reads_numbers_and_unlimited() { #[test] fn psi_needs_both_lines_and_all_fields() { - let t = "some avg10=0.00 avg60=0.01 avg300=0.00 total=2586497190\nfull avg10=1.50 avg60=0.01 avg300=0.00 total=2572226352\n"; + let t = "some avg10=0.00 avg60=0.01 avg300=0.00 total=2586497190\nfull avg10=1.50 avg60=0.01 avg300=0.00 \ +total=2572226352\n"; let p = parse_psi(t).unwrap(); assert_eq!(p.some.total_us, 2_586_497_190); assert!((p.full.avg10 - 1.5).abs() < 1e-9); @@ -98,7 +105,9 @@ fn cgroup_files() { #[test] fn smaps_finds_the_memfd_mapping_with_its_swap() { let t = "7f0000000000-7f0100000000 r--s 00000000 00:01 4242 /memfd:kar-archive (deleted)\n\ -Size: 4194304 kB\nKernelPageSize: 4 kB\nRss: 4000000 kB\nSwap: 194304 kB\nLocked: 0 kB\n\ +Size: 4194304 kB\n\ +KernelPageSize: 4 kB\nRss: 4000000 kB\n\ +Swap: 194304 kB\nLocked: 0 kB\n\ 55e0-55e1 r-xp 00000000 08:01 1 /usr/bin/x\nSize: 4 kB\nRss: 4 kB\nSwap: 0 kB\nLocked: 0 kB\n"; let e = parse_smaps(t); assert_eq!(e.len(), 2); diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index d9792193..e85407bc 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -190,7 +190,8 @@ mod tests { #[test] fn the_requested_device_is_picked_from_several_rows() { - let text = "0, 10, 5, 1000, 24576, 100.0, 1500, 40, NVIDIA GeForce RTX 3090\n1, 99, 80, 20000, 32607, 450.1, 2900, 71, NVIDIA GeForce RTX 5090\n"; + let text = "0, 10, 5, 1000, 24576, 100.0, 1500, 40, NVIDIA GeForce RTX 3090\n1, 99, 80, 20000, 32607, 450.1, \ +2900, 71, NVIDIA GeForce RTX 5090\n"; assert_eq!(parse_csv(text, 1).unwrap().vram_used_mib, 20000); assert_eq!(parse_csv(text, 0).unwrap().name.as_deref(), Some("NVIDIA GeForce RTX 3090")); assert_eq!(parse_csv(text, 2), None); diff --git a/crates/leleka-memory/src/telemetry/tests.rs b/crates/leleka-memory/src/telemetry/tests.rs index 926960ae..2fdcdc78 100644 --- a/crates/leleka-memory/src/telemetry/tests.rs +++ b/crates/leleka-memory/src/telemetry/tests.rs @@ -69,14 +69,13 @@ fn the_nan_guard_reports_each_healed_and_unhealed_window() { *lock(&STATE) = None; } -#[test] -fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { +fn engine_line(r: &RequestLine<'_>) -> String { use leleka_obs::{Format, Level, Settings}; let json = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false }; - let line = |r: &RequestLine<'_>| format_line_for_test(&json, r); - fn format_line_for_test(json: &Settings, r: &RequestLine<'_>) -> String { - leleka_obs::format_line(json, 1_793_613_072_345, Level::Info, "engine", "request", &request_line_fields(r), 0) - } + leleka_obs::format_line(&json, 1_793_613_072_345, Level::Info, "engine", "request", &request_line_fields(r), 0) +} + +fn assert_the_full_engine_line_carries_the_figures() { let full = RequestLine { request_id: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d", input_tokens: 182_341, @@ -88,7 +87,7 @@ fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { rounds: 131, shares: Some((91.4, 5.1, 3.5)), }; - let text = line(&full); + let text = engine_line(&full); for expected in [ "\"comp\":\"engine\"", "\"rid\":\"0b1c2d3e", @@ -101,8 +100,13 @@ fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { } assert!(text.len() < 512, "{} bytes: {text}", text.len()); eprintln!("ENGINE-LINE-BYTES {} {text}", text.len()); +} + +#[test] +fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { + assert_the_full_engine_line_carries_the_figures(); // without the expert tier the three shares are left out; an idle request has no rates - let idle = line(&RequestLine { + let idle = engine_line(&RequestLine { request_id: "r", input_tokens: 0, reused_tokens: 0, @@ -128,14 +132,7 @@ fn the_tier_share_of_a_request_is_the_difference_to_the_previous_one() { assert_eq!(tier_shares(Some(&second), &first), (90.0, 6.0, 4.0)); } -#[test] -fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { - let _serial = lock(&SERIAL); - *lock(&STATE) = None; - let first: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert!(first["last_request"].is_null() && first["expert_tier"].is_null()); - assert_eq!(first["spec"]["rounds"], 0); - assert!(first["spec"]["tokens_per_round"].is_null()); +fn report_two_requests_the_second_without_tier_counters() { request_started(1000); tokens_delivered(300); request_finished(1000, 400, 300, 600.0, 3000.0); @@ -154,6 +151,17 @@ fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { request_started(1000); request_finished(1000, 0, 100, 1200.0, 1000.0); request_detail("req-2", 50, None); +} + +#[test] +fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { + let _serial = lock(&SERIAL); + *lock(&STATE) = None; + let first: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); + assert!(first["last_request"].is_null() && first["expert_tier"].is_null()); + assert_eq!(first["spec"]["rounds"], 0); + assert!(first["spec"]["tokens_per_round"].is_null()); + report_two_requests_the_second_without_tier_counters(); let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); assert_eq!(doc["spec"]["rounds"], 150); assert_eq!(doc["spec"]["tokens"], 400); diff --git a/crates/leleka-runtime/src/lib.rs b/crates/leleka-runtime/src/lib.rs index d2f21b7c..8b17e6a4 100644 --- a/crates/leleka-runtime/src/lib.rs +++ b/crates/leleka-runtime/src/lib.rs @@ -1,5 +1,5 @@ -//! Facade of the serving runtime (STRA-338 S22). The Qwen3.5 CUDA engine lives in `leleka-engine-qwen35-cuda`; the binaries -//! and the gateway keep importing `leleka_runtime::...`, which is this re-export, so the engine crate can change without a -//! change to its users. The engine-independent policy is in `leleka-engine-core`. +//! Facade of the serving runtime (STRA-338 S22). The Qwen3.5 CUDA engine lives in `leleka-engine-qwen35-cuda`; the +//! binaries and the gateway keep importing `leleka_runtime::...`, which is this re-export, so the engine crate can +//! change without a change to its users. The engine-independent policy is in `leleka-engine-core`. pub use leleka_engine_qwen35_cuda::*; diff --git a/crates/libc-shim/src/lib.rs b/crates/libc-shim/src/lib.rs index 2db8efff..1bf316dd 100644 --- a/crates/libc-shim/src/lib.rs +++ b/crates/libc-shim/src/lib.rs @@ -2,8 +2,8 @@ //! `rlimit`, `geteuid`). Consumers depend on it under the name `libc` on Windows only //! (`libc = { package = "leleka-libc-shim", ... }`), so the Linux call sites compile unchanged against either. //! -//! Library names are mapped inside [`dlopen`]: `libcuda.so.1` becomes `nvcuda.dll`, and so on ([`windows_library_name`]). -//! On other targets the crate is empty. +//! Library names are mapped inside [`dlopen`]: `libcuda.so.1` becomes `nvcuda.dll`, and so on +//! ([`windows_library_name`]). On other targets the crate is empty. #![cfg(windows)] #![cfg(windows)] @@ -44,8 +44,9 @@ pub fn windows_library_name(unix_name: &str) -> &str { } /// Environment variable naming extra directories (`;`-separated) that `dlopen` may load DLLs from, next to the -/// application directory and System32. `leleka run` sets it from `runtime.env` (`LD_LIBRARY_PATH`) so that the CUDA 12 -/// cuBLAS DLLs can stay where the operator keeps them; `PATH` itself is not searched by the safe loader flags used here. +/// application directory and System32. `leleka run` sets it from `runtime.env` (`LD_LIBRARY_PATH`) so that the CUDA +/// 12 cuBLAS DLLs can stay where the operator keeps them; `PATH` itself is not searched by the safe loader flags +/// used here. pub const DLL_DIRS_ENV: &str = "LELEKA_DLL_DIRS"; /// Register the directories of [`DLL_DIRS_ENV`] with the loader once per process. @@ -203,8 +204,8 @@ pub unsafe fn munlock(addr: *const c_void, len: usize) -> c_int { if unsafe { VirtualUnlock(addr as *mut c_void, len) } == 0 { -1 } else { 0 } } -/// Physical memory the OS can hand out without paging (`ullAvailPhys` of `GlobalMemoryStatusEx`: free plus standby pages, the -/// closest figure to Linux `MemAvailable`), and the installed total. `None` when the call fails. +/// Physical memory the OS can hand out without paging (`ullAvailPhys` of `GlobalMemoryStatusEx`: free plus standby +/// pages, the closest figure to Linux `MemAvailable`), and the installed total. `None` when the call fails. pub fn physical_memory() -> Option<(u64, u64)> { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut status = MEMORYSTATUSEX { @@ -225,9 +226,9 @@ pub fn physical_memory() -> Option<(u64, u64)> { Some((status.ullTotalPhys, status.ullAvailPhys)) } -/// A new handle on the same file with its own file object (`ReOpenFile`, read access, shared with readers): positional reads through -/// two such handles run in parallel, while two `try_clone`s of one synchronous handle share one file object and the I/O manager runs -/// their requests one at a time, whatever the thread count. +/// A new handle on the same file with its own file object (`ReOpenFile`, read access, shared with readers): +/// positional reads through two such handles run in parallel, while two `try_clone`s of one synchronous handle +/// share one file object and the I/O manager runs their requests one at a time, whatever the thread count. pub fn reopen_file_read(file: &std::fs::File) -> std::io::Result { use std::os::windows::io::{AsRawHandle, FromRawHandle}; use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE}; @@ -242,8 +243,9 @@ pub fn reopen_file_read(file: &std::fs::File) -> std::io::Result Ok(unsafe { std::fs::File::from_raw_handle(handle.cast()) }) } -/// Memory priority of the calling thread (1 very low .. 5 normal, the default): the standby-list priority the file pages it faults in -/// get, which decides what the memory manager repurposes first when it needs RAM. `false` when the call is refused. +/// Memory priority of the calling thread (1 very low .. 5 normal, the default): the standby-list priority the file +/// pages it faults in get, which decides what the memory manager repurposes first when it needs RAM. `false` when +/// the call is refused. pub fn set_thread_memory_priority(priority: u32) -> bool { use windows_sys::Win32::System::Threading::{ GetCurrentThread, MEMORY_PRIORITY_INFORMATION, SetThreadInformation, ThreadMemoryPriority, @@ -274,7 +276,8 @@ pub unsafe fn madvise(_addr: *mut c_void, _len: usize, _advice: c_int) -> c_int 0 } -/// `dwAllocationGranularity`: the alignment of a file-view offset (64 KiB), the Windows counterpart of the page size for `mmap` offsets. +/// `dwAllocationGranularity`: the alignment of a file-view offset (64 KiB), the Windows counterpart of the page +/// size for `mmap` offsets. pub fn allocation_granularity() -> u64 { let mut info = std::mem::MaybeUninit::::zeroed(); // SAFETY: GetSystemInfo fills the structure it is given. @@ -283,12 +286,13 @@ pub fn allocation_granularity() -> u64 { u64::from(unsafe { info.assume_init() }.dwAllocationGranularity) } -/// Maps `len` bytes of an open file read-only and shared (the `mmap(PROT_READ, MAP_SHARED)` of the Linux code), starting at -/// `offset` (which must be a multiple of the allocation granularity, 64 KiB). `len == 0` maps to the end of the file. -/// Returns null on failure; see `std::io::Error::last_os_error`. +/// Maps `len` bytes of an open file read-only and shared (the `mmap(PROT_READ, MAP_SHARED)` of the Linux code), +/// starting at `offset` (which must be a multiple of the allocation granularity, 64 KiB). `len == 0` maps to the +/// end of the file. Returns null on failure; see `std::io::Error::last_os_error`. /// /// # Safety -/// `file` is a live file HANDLE opened for reading. Like any file mapping, a file truncated while mapped faults on access. +/// `file` is a live file HANDLE opened for reading. Like any file mapping, a file truncated while mapped faults +/// on access. pub unsafe fn map_file_readonly(file: *mut c_void, offset: u64, len: usize) -> *mut c_void { use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_READ, MapViewOfFile, PAGE_READONLY}; // SAFETY: a live file handle per the contract; no name, no security attributes; size 0 = the whole file. diff --git a/crates/runtime-client/tests/grpc_backend/runtime_restart_and_loss.rs b/crates/runtime-client/tests/grpc_backend/runtime_restart_and_loss.rs index 690cb974..03d3d863 100644 --- a/crates/runtime-client/tests/grpc_backend/runtime_restart_and_loss.rs +++ b/crates/runtime-client/tests/grpc_backend/runtime_restart_and_loss.rs @@ -12,6 +12,16 @@ async fn a_restarted_runtime_is_refused_before_dispatch_and_reattach_follows_the blocking(backend, |b| b.capabilities().supported_models.is_empty()).await; assert!(!empty, "a healthy attached runtime advertises its model"); + let backend = assert_a_restarted_runtime_is_refused(&server, backend, attached).await; + assert_reattach_follows_the_new_epoch(&server, backend).await; + server.finish().await; +} + +async fn assert_a_restarted_runtime_is_refused( + server: &Server, + backend: GrpcBackend, + attached: LoadedModel, +) -> GrpcBackend { // The runtime process restarts and loads the same model again: same handle, new epoch. server.fake.restart(); server.fake.set_loaded(Some(loaded("h-1"))); @@ -23,7 +33,10 @@ async fn a_restarted_runtime_is_refused_before_dispatch_and_reattach_follows_the assert_eq!(error.code, ErrorCode::BackendUnavailable); assert!(error.retryable); assert!(server.fake.state.lock().unwrap().requests.is_empty()); + backend +} +async fn assert_reattach_follows_the_new_epoch(server: &Server, backend: GrpcBackend) { // The health probe reports the model as gone until the caller attaches again. let (backend, empty) = blocking(backend, |b| b.capabilities().supported_models.is_empty()).await; @@ -34,7 +47,6 @@ async fn a_restarted_runtime_is_refused_before_dispatch_and_reattach_follows_the let (_backend, stream) = blocking(backend, move |b| b.start_generation(&again, request(&id()))).await; assert!(stream.is_ok()); - server.finish().await; } #[tokio::test(flavor = "multi_thread")] diff --git a/crates/runtime-client/tests/grpc_backend/stream_lifecycle.rs b/crates/runtime-client/tests/grpc_backend/stream_lifecycle.rs index 9bc2bf14..93dee216 100644 --- a/crates/runtime-client/tests/grpc_backend/stream_lifecycle.rs +++ b/crates/runtime-client/tests/grpc_backend/stream_lifecycle.rs @@ -3,6 +3,29 @@ #[allow(unused_imports)] use super::*; +async fn assert_a_stream_has_no_terminal( + backend: GrpcBackend, + attached: &LoadedModel, + case: usize, +) -> GrpcBackend { + let (b, stream) = { + let attached = attached.clone(); + blocking(backend, move |b| { + b.start_generation(&attached, request(&id())) + }) + .await + }; + let mut stream = stream.unwrap(); + let (_, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) + .await + .unwrap(); + assert!( + !terminated, + "case {case}: no terminal event may be invented" + ); + b +} + #[tokio::test(flavor = "multi_thread")] async fn a_stream_that_ends_without_a_terminal_or_with_a_transport_error_has_no_terminal() { let server = Server::start(Some(loaded("h-1"))).await; @@ -16,22 +39,7 @@ async fn a_stream_that_ends_without_a_terminal_or_with_a_transport_error_has_no_ blocking(server.backend(), |b| b.load(descriptor(), config())).await; let attached = attached.unwrap(); for case in 0..3 { - let (b, stream) = { - let attached = attached.clone(); - blocking(backend, move |b| { - b.start_generation(&attached, request(&id())) - }) - .await - }; - backend = b; - let mut stream = stream.unwrap(); - let (_, terminated) = tokio::task::spawn_blocking(move || drain(&mut stream)) - .await - .unwrap(); - assert!( - !terminated, - "case {case}: no terminal event may be invented" - ); + backend = assert_a_stream_has_no_terminal(backend, &attached, case).await; } server.finish().await; }