diff --git a/architecture-baseline.json b/architecture-baseline.json index b201a9d3..323391ba 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -74,7 +74,7 @@ "dyn-trait:leleka-cpu-worker": 4, "dyn-trait:leleka-cuda-driver": 48, "dyn-trait:leleka-deploy": 17, - "dyn-trait:leleka-engine-core": 19, + "dyn-trait:leleka-engine-core": 18, "dyn-trait:leleka-engine-fake": 1, "dyn-trait:leleka-engine-qwen35-cuda": 52, "dyn-trait:leleka-experimental-ref": 3, diff --git a/crates/context/src/context_policy.rs b/crates/context/src/context_policy.rs index 18933d30..11ec6140 100644 --- a/crates/context/src/context_policy.rs +++ b/crates/context/src/context_policy.rs @@ -155,8 +155,8 @@ pub struct EffectiveContext { pub notes: Vec, } -/// Derive the effective configuration or refuse. Pure; evaluates the same arithmetic as `strata-plan`. -pub fn resolve_context(req: &ContextRequest) -> Result { +/// Refuse a request that cannot be served before any arithmetic runs. +fn check_request(req: &ContextRequest) -> Result<(), PolicyError> { if req.slots == 0 { return Err(PolicyError::ZeroSlots); } @@ -169,12 +169,19 @@ pub fn resolve_context(req: &ContextRequest) -> Result= 1.0 { req.model_rope.orig_ctx as u64 } else { TRAINED_CONTEXT }; - let setup = - setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained).map_err(PolicyError::Setup)?; +/// The rope configuration chosen for the context actually served, and the size of its shared table. +struct RopeChoice { + rope: RopeScaling, + active: bool, + rows: u64, + bytes: u64, +} + +/// The knobs with the method and factor `setup.py` chose written over them. +fn knobs_for(req: &ContextRequest, setup: Option<(RopeScalingType, f64)>) -> RopeKnobs { let mut knobs = req.rope_knobs; match setup { Some((kind, scale)) => { @@ -187,10 +194,19 @@ pub fn resolve_context(req: &ContextRequest) -> Result) -> Result { + let trained = if req.model_rope.orig_ctx >= 1.0 { req.model_rope.orig_ctx as u64 } else { TRAINED_CONTEXT }; + let setup = + setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained).map_err(PolicyError::Setup)?; + let knobs = knobs_for(req, setup); let resolved = resolve_rope_scaling(&knobs, &req.model_rope).map_err(PolicyError::Rope)?; let rope = resolved.scaling; - let rope_active = rope.kind != RopeScalingType::None; - if rope_active { + let active = rope.kind != RopeScalingType::None; + if active { notes.push(format!( "rope scaling {} factor {} for {} positions per slot (trained {})", rope.kind.name(), @@ -202,57 +218,71 @@ pub fn resolve_context(req: &ContextRequest) -> Result) -> Result { let g = &req.geometry; - let state_per_slot = match req.vram.state_bytes_per_slot { - Some(s) => s, - None => state_bytes(g).map_err(PolicyError::Plan)?, - }; - let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; - let state_total = req.slots.checked_mul(state_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; + let overflow = || PolicyError::Plan(PlanError::Overflow); + let state_per_slot = req.vram.state_bytes_per_slot.map_or_else(|| state_bytes(g), Ok).map_err(PolicyError::Plan)?; + let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or_else(overflow)?; + let state_total = req.slots.checked_mul(state_per_slot).ok_or_else(overflow)?; let costs = Costs { state_bytes: state_total, ..req.vram.costs }; let pool = cli_pool(req.vram.free_vram_bytes, &costs).map_err(PolicyError::Plan)?; let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool).map_err(PolicyError::Plan)?; let per_token = kv_bytes_per_token(g, req.kv_format).map_err(PolicyError::Plan)?; - let per_slot = per_token.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; - let engine_estimate = engine_resident_estimate( - g, - req.kv_format, - req.slots, - req.ctx_per_slot, - rope_active.then_some(ROPE_N_ROT as u64), - ) - .map_err(PolicyError::Plan)?; + let per_slot = per_token.checked_mul(req.ctx_per_slot).ok_or_else(overflow)?; + let rope_rot = rope_active.then_some(ROPE_N_ROT as u64); + let engine_estimate = + engine_resident_estimate(g, req.kv_format, req.slots, req.ctx_per_slot, rope_rot).map_err(PolicyError::Plan)?; let exceeds = engine_estimate.total > pool; if exceeds { - notes.push( - "advisory: the engine's own KV/indexer/rope allocation formulas exceed the planner pool \ - even though the planner admitted it (plan.hpp counts the indexer key store at 32 B per \ - token and layer; layer.cpp allocates fp32)" - .into(), - ); + notes.push(ADVISORY_EXCEEDS_POOL.into()); } + Ok(Admission { total_cells, state_per_slot, plan, per_token, per_slot, engine_estimate, exceeds }) +} + +/// Derive the effective configuration or refuse. Pure; evaluates the same arithmetic as `strata-plan`. +pub fn resolve_context(req: &ContextRequest) -> Result { + check_request(req)?; + let mut notes = Vec::new(); + let r = choose_rope(req, &mut notes)?; + let a = admit(req, r.active, &mut notes)?; if req.kv_format.is_experimental() { notes.push("experimental KV format enabled explicitly; no default and no quality claim".into()); } Ok(EffectiveContext { slots: req.slots, ctx_per_slot: req.ctx_per_slot, - total_cells, + total_cells: a.total_cells, kv_format: req.kv_format, - rope, - rope_active, - rope_table_rows: rope_rows, - rope_table_bytes: rope_bytes, - kv_bytes_per_token: per_token, - kv_bytes_per_slot: per_slot, - state_bytes_per_slot: state_per_slot, - plan, - engine_estimate, - engine_estimate_exceeds_pool: exceeds, + rope: r.rope, + rope_active: r.active, + rope_table_rows: r.rows, + rope_table_bytes: r.bytes, + kv_bytes_per_token: a.per_token, + kv_bytes_per_slot: a.per_slot, + state_bytes_per_slot: a.state_per_slot, + plan: a.plan, + engine_estimate: a.engine_estimate, + engine_estimate_exceeds_pool: a.exceeds, notes, }) } diff --git a/crates/context/src/geometry.rs b/crates/context/src/geometry.rs index 08fea84e..230926ad 100644 --- a/crates/context/src/geometry.rs +++ b/crates/context/src/geometry.rs @@ -44,7 +44,8 @@ impl fmt::Display for GeometryError { } Self::Resident(n) => write!( f, - "a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)" + "a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} \ + pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)" ), Self::Overflow => f.write_str("geometry arithmetic overflowed"), } @@ -218,7 +219,10 @@ impl fmt::Display for KvStreamFootprint { let gib = |b: usize| b as f64 / (1u64 << 30) as f64; write!( f, - "kv int8 context={} resident={} cells ({} pages/layer) vram={:.3} GiB (+{:.3} GiB prompt stage) pinned-host={:.3} GiB", + concat!( + "kv int8 context={} resident={} cells ({} pages/layer) vram={:.3} GiB ", + "(+{:.3} GiB prompt stage) pinned-host={:.3} GiB" + ), self.cells, self.resident_pages * PAGE_CELLS, self.resident_pages, diff --git a/crates/context/src/memory_plan/impl_default_for_geometry.rs b/crates/context/src/memory_plan/impl_default_for_geometry.rs index 5f58c92c..7ce6ed1e 100644 --- a/crates/context/src/memory_plan/impl_default_for_geometry.rs +++ b/crates/context/src/memory_plan/impl_default_for_geometry.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Default_for_Geometry, impl Geometry, impl Default_for_Costs, impl fmt_Display_for, impl std_error_Error, fn mul .... +//! Moved out of the parent module by STRA-338: impl Default_for_Geometry, impl Geometry, impl Default_for_Costs, impl +//! fmt_Display_for, impl std_error_Error, fn mul .... #[allow(unused_imports)] use super::*; @@ -136,22 +137,31 @@ pub(super) fn q4_bytes_per_head(head_dim: u64) -> R { mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES) } +fn fp16_bytes_per_cell(s: &KvShapes) -> R { + mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2) +} +fn q4_bytes_per_cell(s: &KvShapes) -> R { + mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2) +} +/// `layer.cpp` hybrid branch: INT8 keys, Q4_0 values. +fn k8v4_bytes_per_cell(s: &KvShapes) -> R { + let rows = s.n_head_kv; + add( + add(mul(rows, s.head_dim)?, mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?)?, + mul(rows, q4_bytes_per_head(s.head_dim)?)?, + ) +} + /// Bytes per cell (one token, one QSA layer) of the K/V pool in `fmt`, without the pool's constant `+64`. /// fp16: `n_head_kv * head_dim * 2 * 2`; INT8: kv_q8.hpp; Q4_0: kv_q4.hpp; K8V4: `layer.cpp` hybrid branch /// (816 B/cell on the real shapes); keyless: INT8 / 2. pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R { s.validate(fmt)?; match fmt { - KvFormat::Fp16 => mul(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, 2), + KvFormat::Fp16 => fp16_bytes_per_cell(s), KvFormat::Int8 => q8_bytes_per_cell(s), - KvFormat::Q4_0 => mul(mul(s.n_head_kv, q4_bytes_per_head(s.head_dim)?)?, 2), - KvFormat::K8V4 => { - let rows = s.n_head_kv; - add( - add(mul(rows, s.head_dim)?, mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?)?, - mul(rows, q4_bytes_per_head(s.head_dim)?)?, - ) - } + KvFormat::Q4_0 => q4_bytes_per_cell(s), + KvFormat::K8V4 => k8v4_bytes_per_cell(s), KvFormat::Int8Keyless => Ok(q8_bytes_per_cell(s)? / 2), } } diff --git a/crates/context/src/memory_plan/plan_with_per_token.rs b/crates/context/src/memory_plan/plan_with_per_token.rs index e085a4c6..7991fb6f 100644 --- a/crates/context/src/memory_plan/plan_with_per_token.rs +++ b/crates/context/src/memory_plan/plan_with_per_token.rs @@ -1,8 +1,14 @@ -//! Moved out of the parent module by STRA-338: fn plan_with_per_token, fn cli_pool, impl Plan, fn engine_resident_estimate. +//! Moved out of the parent module by STRA-338: fn plan_with_per_token, fn cli_pool, impl Plan, fn +//! engine_resident_estimate. #[allow(unused_imports)] use super::*; +/// The refusal when the KV and fixed bytes of `max_context` exceed the VRAM pool. +fn over_pool(max_context: u64, need: u64, pool: u64) -> R { + does_not_close(format!("max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context")) +} + pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R { if c.expert_blob == 0 { return Err(PlanError::Geometry("expert_blob must be non-zero")); @@ -12,9 +18,7 @@ pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, p let fixed = add(add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, c.state_bytes)?; let need = add(kv_bytes, fixed)?; if need > pool { - return does_not_close(format!( - "max-context {max_context} needs {need} B of the {pool} B VRAM pool; reduce --max-context" - )); + return over_pool(max_context, need, pool); } let cache_bytes = pool - need; let cache_slots = cache_bytes / c.expert_blob; @@ -69,6 +73,35 @@ impl Plan { } } +/// Bytes of the fp32 indexer key store of one layer of one slot. +fn indexer_layer_bytes(g: &Geometry, ctx_per_slot: u64) -> R { + let key = g.indexer_key_dim; + let pooled_rows = ctx_per_slot / g.qsa_block + 2; + let head = mul(mul(g.qsa_block - 1, key)?, 4)?; + let current = mul(key, 4)?; + let pooled = mul(mul(pooled_rows, key)?, 4)?; + add(add(head, current)?, pooled) +} + +/// Bytes of the rope cos/sin table of one slot (0 when the stock model needs none). +fn rope_slot_bytes(ctx_per_slot: u64, rope_n_rot: Option) -> R { + match rope_n_rot { + Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8), + None => Ok(0), + } +} + +/// Per slot: `[KV pools, page tables, indexer stores, rope table]`. +fn per_slot_bytes(g: &Geometry, fmt: KvFormat, ctx_per_slot: u64, rope_n_rot: Option) -> R<[u64; 4]> { + let s = KvShapes::from_geometry(g); + let pages = ctx_per_slot.div_ceil(s.page_size); + let layers = g.n_qsa_layers; + let kv_layer = kv_pool_bytes(&s, pages, fmt)?; + let idx_layer = indexer_layer_bytes(g, ctx_per_slot)?; + let rope = rope_slot_bytes(ctx_per_slot, rope_n_rot)?; + Ok([mul(layers, kv_layer)?, mul(layers, mul(pages, 4)?)?, mul(layers, idx_layer)?, rope]) +} + /// `slots` independent sequence states of `ctx_per_slot` cells each; one rope table per state when /// `rope_table_per_slot` is `Some(n_rot)` (the table is shared across layers by `share_rope`). pub fn engine_resident_estimate( @@ -79,26 +112,9 @@ pub fn engine_resident_estimate( rope_n_rot: Option, ) -> R { g.validate()?; - let s = KvShapes::from_geometry(g); - let pages = ctx_per_slot.div_ceil(s.page_size); - let layers = g.n_qsa_layers; - let kv_layer = kv_pool_bytes(&s, pages, fmt)?; - let pooled_rows = ctx_per_slot / g.qsa_block + 2; - let idx_layer = add( - add(mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, mul(g.indexer_key_dim, 4)?)?, - mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?, - )?; - let per_slot_kv = mul(layers, kv_layer)?; - let per_slot_pt = mul(layers, mul(pages, 4)?)?; - let per_slot_idx = mul(layers, idx_layer)?; - let per_slot_rope = match rope_n_rot { - Some(n) => mul(mul(ctx_per_slot, n / 2)?, 8)?, - None => 0, - }; - let kv_pools = mul(slots, per_slot_kv)?; - let page_tables = mul(slots, per_slot_pt)?; - let indexer_stores = mul(slots, per_slot_idx)?; - let rope_tables = mul(slots, per_slot_rope)?; + let per_slot = per_slot_bytes(g, fmt, ctx_per_slot, rope_n_rot)?; + let [kv_pools, page_tables, indexer_stores, rope_tables] = + [mul(slots, per_slot[0])?, mul(slots, per_slot[1])?, mul(slots, per_slot[2])?, mul(slots, per_slot[3])?]; let total = add(add(add(kv_pools, page_tables)?, indexer_stores)?, rope_tables)?; Ok(EngineResidentEstimate { kv_pools, page_tables, indexer_stores, rope_tables, total }) } diff --git a/crates/context/src/rope_scaling/fill_rope_table.rs b/crates/context/src/rope_scaling/fill_rope_table.rs index 157c9673..8ed2d6e6 100644 --- a/crates/context/src/rope_scaling/fill_rope_table.rs +++ b/crates/context/src/rope_scaling/fill_rope_table.rs @@ -1,45 +1,46 @@ -//! Moved out of the parent module by STRA-338: fn fill_rope_table, impl RopeTable, fn build_rope_table, impl Default_for_RopeKnobs, impl fmt_Display_for, impl std_error_Error .... +//! Moved out of the parent module by STRA-338: fn fill_rope_table, impl RopeTable, fn build_rope_table, impl +//! Default_for_RopeKnobs, impl fmt_Display_for, impl std_error_Error .... #[allow(unused_imports)] use super::*; -/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` -/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). -/// -/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. -/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). -pub fn fill_rope_table( - n_rot: usize, - sc: &RopeScaling, +/// The rows being filled: `rows` rows of `half` entries, starting at position `first_pos`. +#[derive(Clone, Copy)] +struct RowSpan { + half: usize, first_pos: usize, - cos_out: &mut [f32], - sin_out: &mut [f32], -) -> Result<(), RopeTableError> { - check_n_rot(n_rot)?; - sc.validate()?; - let half = n_rot / 2; - if cos_out.len() != sin_out.len() || !cos_out.len().is_multiple_of(half) { + rows: usize, +} + +/// The number of rows the output buffers hold, refused when they disagree or reach past `i32` positions. +fn fill_rows(half: usize, first_pos: usize, cos_len: usize, sin_len: usize) -> Result { + if cos_len != sin_len || !cos_len.is_multiple_of(half) { return Err(RopeTableError::BufferLength); } - let rows = cos_out.len() / half; + let rows = cos_len / half; let end = first_pos.checked_add(rows).ok_or(RopeTableError::TooManyPositions(rows))?; if i32::try_from(end).is_err() { return Err(RopeTableError::TooManyPositions(end)); } - // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. - let n_rot_f = n_rot as f64; - let inv: Vec = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect(); - if sc.kind == RopeScalingType::None { - for r in 0..rows { - let p = (first_pos + r) as f64; - for i in 0..half { - let ang = p * inv[i]; - cos_out[r * half + i] = ang.cos() as f32; - sin_out[r * half + i] = ang.sin() as f32; - } + Ok(rows) +} + +/// The unscaled loop of the Original, verbatim (no mscale multiply). +fn fill_unscaled(inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { + let RowSpan { half, first_pos, rows } = span; + for r in 0..rows { + let p = (first_pos + r) as f64; + for i in 0..half { + let ang = p * inv[i]; + cos_out[r * half + i] = ang.cos() as f32; + sin_out[r * half + i] = ang.sin() as f32; } - return Ok(()); } +} + +/// The scaled loop: linear interpolation of the angle, the YaRN ramp blend and the magnitude scale. +fn fill_scaled(sc: &RopeScaling, n_rot: usize, inv: &[f64], span: RowSpan, cos_out: &mut [f32], sin_out: &mut [f32]) { + let RowSpan { half, first_pos, rows } = span; let fs = sc.freq_scale(); let ms = sc.mscale(); let cd = sc.corr_dims(n_rot as i32); @@ -60,6 +61,33 @@ pub fn fill_rope_table( sin_out[r * half + i] = (ang.sin() * ms) as f32; } } +} + +/// Fill rows `first_pos .. first_pos + rows` of the table into `cos_out` / `sin_out` +/// (`rows * n_rot / 2` entries each, row-major like `cos_tab[p * half + i]`). +/// +/// Row `p` depends only on `(n_rot, sc, p)`, so a table of any length is a prefix of any longer one. +/// `RopeScalingType::None` takes the Original's unscaled loop verbatim (no mscale multiply). +pub fn fill_rope_table( + n_rot: usize, + sc: &RopeScaling, + first_pos: usize, + cos_out: &mut [f32], + sin_out: &mut [f32], +) -> Result<(), RopeTableError> { + check_n_rot(n_rot)?; + sc.validate()?; + let half = n_rot / 2; + let rows = fill_rows(half, first_pos, cos_out.len(), sin_out.len())?; + // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. + let n_rot_f = n_rot as f64; + let inv: Vec = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect(); + let span = RowSpan { half, first_pos, rows }; + if sc.kind == RopeScalingType::None { + fill_unscaled(&inv, span, cos_out, sin_out); + } else { + fill_scaled(sc, n_rot, &inv, span, cos_out, sin_out); + } Ok(()) } @@ -105,19 +133,13 @@ impl fmt::Display for RopeKnobError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::NotFinite => f.write_str("a rope scaling knob is not a finite number"), - Self::ScaleBelowOne => { - f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)") - } - Self::FreqBase => { - f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)") - } - Self::Knob => f.write_str( - "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, --yarn-orig-ctx 0 = default, the rest positive)", - ), - Self::ModelType(t) => write!( - f, - "model file carries rope.scaling.type '{t}' - none, linear or yarn only" - ), + Self::ScaleBelowOne => f.write_str("--rope-scale must be >= 1 (it extends the context, not shrinks it)"), + Self::FreqBase => f.write_str("--rope-freq-base must be a base above 1 (0 = the model's)"), + Self::Knob => f.write_str(concat!( + "invalid rope scaling knob (--yarn-ext-factor < 0 = auto, ", + "--yarn-orig-ctx 0 = default, the rest positive)", + )), + Self::ModelType(t) => write!(f, "model file carries rope.scaling.type '{t}' - none, linear or yarn only"), Self::Invalid(e) => write!(f, "invalid rope scaling configuration: {e}"), } } @@ -125,9 +147,8 @@ impl fmt::Display for RopeKnobError { impl std::error::Error for RopeKnobError {} -/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, -/// the `none` reset, and the whole-config validity rule. -pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { +/// The range checks of the `generate.cpp` rope resolution. +fn check_knobs(knobs: &RopeKnobs) -> Result<(), RopeKnobError> { let all = [ knobs.rope_scale, knobs.rope_freq_base, @@ -147,40 +168,49 @@ pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result< if knobs.rope_freq_base != 0.0 && knobs.rope_freq_base <= 1.0 { return Err(RopeKnobError::FreqBase); } - if knobs.rope_freq_scale < 0.0 + if knob_out_of_range(knobs) { + return Err(RopeKnobError::Knob); + } + Ok(()) +} + +fn knob_out_of_range(knobs: &RopeKnobs) -> bool { + knobs.rope_freq_scale < 0.0 || knobs.yarn_orig_ctx < 0.0 || knobs.yarn_ext_factor < -1.0 || knobs.yarn_attn_factor <= 0.0 || knobs.yarn_beta_fast <= 0.0 || knobs.yarn_beta_slow <= 0.0 - { - return Err(RopeKnobError::Knob); - } +} - let mut cfg = RopeScaling::default(); +/// The flag's kind, else the model file's; `None` leaves the default. +fn resolve_kind(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result, RopeKnobError> { if let Some(kind) = knobs.scaling { + return Ok(Some(kind)); + } + match model.scaling_type.as_deref().filter(|t| !t.is_empty()) { + Some(t) => RopeScalingType::parse(t).map(Some).ok_or_else(|| RopeKnobError::ModelType(t.to_owned())), + None => Ok(None), + } +} + +/// Precedence flag > model file > the current value. +fn pick(flag: Option, model: Option, current: f64) -> f64 { + flag.or(model).unwrap_or(current) +} + +/// The configuration the knobs and the model file give before the `none` reset and the validity rule. +fn layered_config(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { + let mut cfg = RopeScaling::default(); + if let Some(kind) = resolve_kind(knobs, model)? { cfg.kind = kind; - } else if let Some(t) = model.scaling_type.as_deref().filter(|t| !t.is_empty()) { - match RopeScalingType::parse(t) { - Some(kind) => cfg.kind = kind, - None => return Err(RopeKnobError::ModelType(t.to_owned())), - } - } - if knobs.rope_scale > 0.0 { - cfg.factor = knobs.rope_scale; - } else if model.factor > 1.0 { - cfg.factor = model.factor; - } - if knobs.rope_freq_base > 0.0 { - cfg.freq_base = knobs.rope_freq_base; - } else if model.freq_base > 1.0 { - cfg.freq_base = model.freq_base; - } - if knobs.yarn_orig_ctx > 0.0 { - cfg.orig_ctx = knobs.yarn_orig_ctx; - } else if model.orig_ctx >= 1.0 { - cfg.orig_ctx = model.orig_ctx; } + let flag_factor = (knobs.rope_scale > 0.0).then_some(knobs.rope_scale); + cfg.factor = pick(flag_factor, (model.factor > 1.0).then_some(model.factor), cfg.factor); + let flag_base = (knobs.rope_freq_base > 0.0).then_some(knobs.rope_freq_base); + cfg.freq_base = pick(flag_base, (model.freq_base > 1.0).then_some(model.freq_base), cfg.freq_base); + let flag_orig = (knobs.yarn_orig_ctx > 0.0).then_some(knobs.yarn_orig_ctx); + cfg.orig_ctx = pick(flag_orig, (model.orig_ctx >= 1.0).then_some(model.orig_ctx), cfg.orig_ctx); cfg.freq_scale_in = knobs.rope_freq_scale; cfg.ext_factor = if knobs.yarn_ext_factor >= 0.0 { knobs.yarn_ext_factor @@ -192,7 +222,14 @@ pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result< cfg.attn_factor = knobs.yarn_attn_factor; cfg.beta_fast = knobs.yarn_beta_fast; cfg.beta_slow = knobs.yarn_beta_slow; + Ok(cfg) +} +/// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, +/// the `none` reset, and the whole-config validity rule. +pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { + check_knobs(knobs)?; + let mut cfg = layered_config(knobs, model)?; let mut inert = false; if cfg.kind == RopeScalingType::None { inert = knobs.rope_scale > 1.0 diff --git a/crates/context/src/rope_scaling/impl_fmt_display_for.rs b/crates/context/src/rope_scaling/impl_fmt_display_for.rs index 2622fe36..e04d473f 100644 --- a/crates/context/src/rope_scaling/impl_fmt_display_for.rs +++ b/crates/context/src/rope_scaling/impl_fmt_display_for.rs @@ -6,12 +6,14 @@ use super::*; impl fmt::Display for SetupRopeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ScaleWithoutMethod => f.write_str( - "--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the trained range, so there is nothing to scale)", - ), - Self::NoneBeyondTrained => f.write_str( - "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; pick yarn or linear, or lower the context", - ), + Self::ScaleWithoutMethod => f.write_str(concat!( + "--rope-scale needs --rope-scaling linear or yarn ", + "(the chosen context fits the trained range, so there is nothing to scale)", + )), + Self::NoneBeyondTrained => f.write_str(concat!( + "the context is past the model's trained range and --rope-scaling none keeps the stock angles there; ", + "pick yarn or linear, or lower the context", + )), } } } diff --git a/crates/context/src/rope_scaling/impl_ropescalingtype.rs b/crates/context/src/rope_scaling/impl_ropescalingtype.rs index a172aada..812107c0 100644 --- a/crates/context/src/rope_scaling/impl_ropescalingtype.rs +++ b/crates/context/src/rope_scaling/impl_ropescalingtype.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl RopeScalingType, impl Default_for_RopeKernelArgs, impl RopeScalingError, impl fmt_Display_for, impl std_error_Error, impl Default_for_RopeScaling .... +//! Moved out of the parent module by STRA-338: impl RopeScalingType, impl Default_for_RopeKernelArgs, impl +//! RopeScalingError, impl fmt_Display_for, impl std_error_Error, impl Default_for_RopeScaling .... #[allow(unused_imports)] use super::*; @@ -115,41 +116,35 @@ impl RopeScaling { /// `rope_scaling_invalid`: the one validity rule. Every value is tested with `is_finite` first so a NaN /// cannot slip through a range comparison. pub fn validate(&self) -> Result<(), RopeScalingError> { - if !self.freq_base.is_finite() || self.freq_base <= 1.0 { + if not_ok(self.freq_base, |x| x > 1.0) { return Err(RopeScalingError::FreqBase); } if self.kind == RopeScalingType::None { return Ok(()); } - if !self.factor.is_finite() || self.factor < 1.0 { - return Err(RopeScalingError::Factor); - } - if !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 { - return Err(RopeScalingError::FreqScaleIn); - } - let fs = self.freq_scale(); - if !fs.is_finite() || fs <= 0.0 { - return Err(RopeScalingError::ResolvedFreqScale); - } - if !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 { - return Err(RopeScalingError::OrigCtx); - } - if !self.ext_factor.is_finite() || self.ext_factor < 0.0 { - return Err(RopeScalingError::ExtFactor); - } - if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 { - return Err(RopeScalingError::AttnFactor); - } - if !self.beta_fast.is_finite() || self.beta_fast <= 0.0 || !self.beta_slow.is_finite() || self.beta_slow <= 0.0 - { - return Err(RopeScalingError::Betas); - } - let ms = self.mscale(); - if !ms.is_finite() || ms <= 0.0 { - return Err(RopeScalingError::Mscale); - } - Ok(()) + self.validate_scaled() } + + /// The rules of a scaled configuration, the first miss in the order of the Original. + fn validate_scaled(&self) -> Result<(), RopeScalingError> { + let (fs, ms) = (self.freq_scale(), self.mscale()); + let misses = [ + (not_ok(self.factor, |x| x >= 1.0), RopeScalingError::Factor), + (not_ok(self.freq_scale_in, |x| x >= 0.0), RopeScalingError::FreqScaleIn), + (not_ok(fs, |x| x > 0.0), RopeScalingError::ResolvedFreqScale), + (not_ok(self.orig_ctx, |x| x >= 1.0), RopeScalingError::OrigCtx), + (not_ok(self.ext_factor, |x| x >= 0.0), RopeScalingError::ExtFactor), + (not_ok(self.attn_factor, |x| x > 0.0), RopeScalingError::AttnFactor), + (not_ok(self.beta_fast, |x| x > 0.0) || not_ok(self.beta_slow, |x| x > 0.0), RopeScalingError::Betas), + (not_ok(ms, |x| x > 0.0), RopeScalingError::Mscale), + ]; + misses.into_iter().find(|(missed, _)| *missed).map_or(Ok(()), |(_, error)| Err(error)) + } +} + +/// True when `x` is not finite or fails the range test `ok`. +fn not_ok(x: f64, ok: impl Fn(f64) -> bool) -> bool { + !x.is_finite() || !ok(x) } /// `rope_yarn_ramp`: 1 - clamp(y, 0, 1), float32, taking the PAIR index (ggml's `i0 / 2`). diff --git a/crates/context/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs index 344f9731..64fd891a 100644 --- a/crates/context/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -189,7 +189,8 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { 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" + "note: {name}: table hash over {n} rows differs from the macOS fixture (non-macOS libm); \ + sample rows are within tolerance" ); } } diff --git a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs index 13ec748f..ce1554ec 100644 --- a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs +++ b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs @@ -1,4 +1,6 @@ -//! Tests of rope_plan_golden by topic (moved out of the test file by STRA-338): every_fixture_case_has_a_test, yarn_is_observably_different_from_none, strata_plan_cli_output_is_reproduced_exactly, kv_pool_bytes_match_the_originals_layer_cpp. +//! Tests of rope_plan_golden by topic (moved out of the test file by STRA-338): every_fixture_case_has_a_test, +//! yarn_is_observably_different_from_none, strata_plan_cli_output_is_reproduced_exactly, +//! kv_pool_bytes_match_the_originals_layer_cpp. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/buffer.rs b/crates/engine-core/src/conversation/buffer.rs index a8e5548c..d9d5ba56 100644 --- a/crates/engine-core/src/conversation/buffer.rs +++ b/crates/engine-core/src/conversation/buffer.rs @@ -95,45 +95,56 @@ impl ConversationBuffer { total } + /// Grow to `n` bytes (more than the size): fill the spare room of the last segment, then add segments. + fn grow(&mut self, n: usize, value: u8) -> Result<(), TryReserveError> { + let growing = self.size != 0; + let spare = self.segments.last().map_or(0, |segment| segment.capacity() - segment.len()); + let extend = (n - self.size).min(spare); + let extra = n - self.size - extend; + let directory = extra / SEGMENT_BYTES + usize::from(!extra.is_multiple_of(SEGMENT_BYTES)); + self.segments.try_reserve_exact(directory)?; + if extend != 0 { + let back = self.segments.last_mut().expect("spare implies a segment"); + let to = back.len() + extend; + back.resize(to, value); + self.size += extend; + } + while self.size < n { + let count = SEGMENT_BYTES.min(n - self.size); + let previous = self.segments.last().map_or(0, Vec::capacity); + let mut segment = Vec::new(); + segment.try_reserve_exact(segment_capacity(count, previous, growing))?; + segment.resize(count, value); + self.segments.push(segment); + self.size += count; + } + Ok(()) + } + + /// Shrink to `n` bytes (at most the size): drop the segments past it and cut the last one. + fn shrink(&mut self, n: usize) { + while let Some(back) = self.segments.last() { + if self.size - back.len() < n { + break; + } + self.size -= back.len(); + self.segments.pop(); + } + if self.size > n { + let back = self.segments.last_mut().expect("excess implies a segment"); + let to = back.len() - (self.size - n); + back.truncate(to); + } + self.size = n; + } + /// Resize to `n` bytes; new bytes take `value`. Allocation failure leaves /// the buffer valid (possibly partially grown), never panics. pub fn resize(&mut self, n: usize, value: u8) -> Result<(), TryReserveError> { if n > self.size { - let growing = self.size != 0; - let spare = self.segments.last().map_or(0, |segment| segment.capacity() - segment.len()); - let extend = (n - self.size).min(spare); - let extra = n - self.size - extend; - let directory = extra / SEGMENT_BYTES + usize::from(!extra.is_multiple_of(SEGMENT_BYTES)); - self.segments.try_reserve_exact(directory)?; - if extend != 0 { - let back = self.segments.last_mut().expect("spare implies a segment"); - let to = back.len() + extend; - back.resize(to, value); - self.size += extend; - } - while self.size < n { - let count = SEGMENT_BYTES.min(n - self.size); - let previous = self.segments.last().map_or(0, Vec::capacity); - let mut segment = Vec::new(); - segment.try_reserve_exact(segment_capacity(count, previous, growing))?; - segment.resize(count, value); - self.segments.push(segment); - self.size += count; - } + self.grow(n, value)?; } else { - while let Some(back) = self.segments.last() { - if self.size - back.len() < n { - break; - } - self.size -= back.len(); - self.segments.pop(); - } - if self.size > n { - let back = self.segments.last_mut().expect("excess implies a segment"); - let to = back.len() - (self.size - n); - back.truncate(to); - } - self.size = n; + self.shrink(n); } Ok(()) } diff --git a/crates/engine-core/src/conversation/cache/impl_conversationcache.rs b/crates/engine-core/src/conversation/cache/impl_conversationcache.rs index 791ebb01..33ee7bd3 100644 --- a/crates/engine-core/src/conversation/cache/impl_conversationcache.rs +++ b/crates/engine-core/src/conversation/cache/impl_conversationcache.rs @@ -3,6 +3,17 @@ #[allow(unused_imports)] use super::*; +/// The checkpoint with the most tokens (the first of them on a tie). +fn deepest_key<'a>(keys: impl IntoIterator>) -> Option> { + let mut deepest: Option> = None; + for key in keys { + if deepest.is_none_or(|d| key.ids.len() > d.ids.len()) { + deepest = Some(key); + } + } + deepest +} + impl ConversationCache { pub fn new(budget: usize, slots: usize) -> Self { Self { @@ -154,12 +165,7 @@ impl ConversationCache { let mut i = 0; while i < self.entries.len() { let entry = &self.entries[i]; - let mut deepest: Option> = None; - for key in entry.checkpoint_keys() { - if deepest.is_none_or(|d| key.ids.len() > d.ids.len()) { - deepest = Some(key); - } - } + let deepest = deepest_key(entry.checkpoint_keys()); let superseded = entry.cvec() == cvec && deepest.is_some_and(|d| !d.ids.is_empty() && held(&d)); if superseded { if let Some(entry) = self.entries.remove(i) { diff --git a/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs b/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs index 02717c26..05d646ab 100644 --- a/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs +++ b/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs @@ -1,4 +1,6 @@ -//! Moved out of the parent module by STRA-338: impl ConversationCheckpoint, impl ConversationKv, impl ConversationKvReuse, impl Default_for_SavedConversation, impl SavedConversation, impl ParkedConversation_for_SavedConversation .... +//! Moved out of the parent module by STRA-338: impl ConversationCheckpoint, impl ConversationKv, impl +//! ConversationKvReuse, impl Default_for_SavedConversation, impl SavedConversation, impl +//! ParkedConversation_for_SavedConversation .... #[allow(unused_imports)] use super::*; @@ -107,24 +109,23 @@ where { return 0; } + if images_match(imgs, images, n) { n as i64 } else { 0 } +} + +/// The images that start inside the first `n` tokens are the saved point's own, one for one; images past it are +/// irrelevant. +fn images_match(imgs: &[ConversationImageKey], images: &[ConversationImageKey], n: usize) -> bool { let mut j = 0; for image in images { if image.start >= n as i64 { continue; } - if j == imgs.len() { - return 0; + if j == imgs.len() || imgs[j] != *image { + return false; } - let saved = imgs[j]; j += 1; - if saved != *image { - return 0; - } } - if j != imgs.len() { - return 0; - } - n as i64 + j == imgs.len() } /// [`prefix_len`] over a [`ConversationCheckpoint`] (`conversation_prefix`). 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 73f6dc1a..20874f31 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 @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): retained_buffers_count_against_bytes_but_not_slots, a_b_a_recovery_and_slot_eviction, checkpoints_steering_and_boundary_rules, image_identity_is_part_of_the_prefix .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! retained_buffers_count_against_bytes_but_not_slots, a_b_a_recovery_and_slot_eviction, +//! checkpoints_steering_and_boundary_rules, image_identity_is_part_of_the_prefix .... #[allow(unused_imports)] use super::*; @@ -115,8 +117,9 @@ fn in_flight_image_is_counted_during_an_exchange() { assert!(!cache.make_room(0, one * 2 + 1), "held larger than budget cannot underflow"); } -/// Upstream 41cf05a0 `940011da`: a full cache dropped the new snapshot instead of evicting for it. Full by slots or by bytes, the -/// oldest conversation goes and the new one is parked; only an image that cannot fit at all is refused, and then nothing is dropped. +/// Upstream 41cf05a0 `940011da`: a full cache dropped the new snapshot instead of evicting for it. Full by slots or by +/// bytes, the oldest conversation goes and the new one is parked; only an image that cannot fit at all is refused, and +/// then nothing is dropped. #[test] fn a_full_cache_evicts_the_oldest_for_the_new_snapshot_by_slots_and_by_bytes() { let one = image(&[1, 2, 3]).bytes(); diff --git a/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs b/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs index 7c1b8314..8f780f21 100644 --- a/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs +++ b/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): what_is_not_superseded, disabled_caches_store_nothing, take_out_of_range_is_none_and_prefix_len_is_generic_over_token_types, struct_sizes_match_the_64_bit_original_layout. +//! Tests of tests by topic (moved out of the test file by STRA-338): what_is_not_superseded, +//! disabled_caches_store_nothing, take_out_of_range_is_none_and_prefix_len_is_generic_over_token_types, +//! struct_sizes_match_the_64_bit_original_layout. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/kv/impl_layout.rs b/crates/engine-core/src/conversation/kv/impl_layout.rs index 6b82d2ee..4be4358c 100644 --- a/crates/engine-core/src/conversation/kv/impl_layout.rs +++ b/crates/engine-core/src/conversation/kv/impl_layout.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Layout, fn kv_q4_bytes_per_head, fn valid_extent, fn layout, fn valid, fn region .... +//! Moved out of the parent module by STRA-338: impl Layout, fn kv_q4_bytes_per_head, fn valid_extent, fn layout, fn +//! valid, fn region .... #[allow(unused_imports)] use super::*; @@ -21,38 +22,64 @@ pub(super) fn valid_extent(st: &QsaDesc, upto: i64) -> ConvResult<()> { Ok(()) } -pub(super) fn layout(st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> ConvResult { +/// The K/V geometry the capture can lay out. +fn geometry_ok(st: &QsaDesc, g: &ModelGeometry, int8_keys: bool) -> bool { + !(g.n_head_kv <= 0 + || g.head_dim <= 0 + || g.head_dim > i64::from(i32::MAX) + || g.idx_key_dim <= 0 + || (st.kv_q4 && g.head_dim % 32 != 0) + || (int8_keys && !st.kv_q4 && g.head_dim % 64 != 0)) +} + +/// The refusals before any size is computed; whether the keys are INT8 (also in the hybrid format). +fn check_layout_inputs(st: &QsaDesc, g: &ModelGeometry, upto: i64) -> ConvResult { valid_extent(st, upto)?; if st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8) { return fail("hybrid K8V4 requires an identity layout and distinct format flags"); } let int8_keys = st.kv_int8 || st.kv_hybrid; - if g.n_head_kv <= 0 - || g.head_dim <= 0 - || g.head_dim > i64::from(i32::MAX) - || g.idx_key_dim <= 0 - || (st.kv_q4 && g.head_dim % 32 != 0) - || (int8_keys && !st.kv_q4 && g.head_dim % 64 != 0) - { + if !geometry_ok(st, g, int8_keys) { return fail("invalid K/V geometry"); } - let cells = ((upto + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE; - let per = - if st.kv_q4 { kv_q4_bytes_per_head(g.head_dim) } else { g.head_dim as u64 * if int8_keys { 1 } else { 2 } }; - // Include the moving spare row, not only completed blocks. The checkpoint - // restore reconstructs that row when rewinding to an earlier prefix. - let pooled = if index && upto > 0 { upto / IDX_BLOCK + 1 } else { 0 }; - // Format 3 identifies snapshot K8V4 only; rotated INT8 K/V is another - // format too (+16): its bytes mean nothing to a state that does not rotate. + Ok(int8_keys) +} + +/// The snapshot format code. Format 3 identifies snapshot K8V4 only; rotated INT8 K/V is another format too (+16): +/// its bytes mean nothing to a state that does not rotate. +fn format_code(st: &QsaDesc) -> i32 { let rotated = if st.kv_rot && !st.kv_q4 && !st.kv_hybrid { KV_ROTATED } else { 0 }; let base = if st.kv_hybrid { KV_HYBRID } else { st.kv_format().expect("non-hybrid has a format") }; + base + rotated +} + +/// Bytes of the keys (or values), their scales and the pooled indexer rows: `(data, scales, pooled)`. +fn byte_counts( + st: &QsaDesc, + g: &ModelGeometry, + cells: i64, + pooled: i64, + int8_keys: bool, +) -> ConvResult<(usize, usize, usize)> { + let per = + if st.kv_q4 { kv_q4_bytes_per_head(g.head_dim) } else { g.head_dim as u64 * if int8_keys { 1 } else { 2 } }; let overflow = || ConvError("conversation snapshot: K/V byte count overflow".into()); let scale_unit = if int8_keys && !st.kv_q4 { (g.head_dim / 64) as u64 * 2 } else { 0 }; let data = product(&[cells as u64, g.n_head_kv as u64, per]).ok_or_else(overflow)?; let scales = product(&[cells as u64, g.n_head_kv as u64, scale_unit]).ok_or_else(overflow)?; let pooled_bytes = product(&[pooled as u64, g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; + Ok((data, scales, pooled_bytes)) +} + +pub(super) fn layout(st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> ConvResult { + let int8_keys = check_layout_inputs(st, g, upto)?; + let cells = ((upto + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE; + // Include the moving spare row, not only completed blocks. The checkpoint + // restore reconstructs that row when rewinding to an earlier prefix. + let pooled = if index && upto > 0 { upto / IDX_BLOCK + 1 } else { 0 }; + let (data, scales, pooled_bytes) = byte_counts(st, g, cells, pooled, int8_keys)?; let mut l = Layout { - format: base + rotated, + format: format_code(st), cells, pooled_rows: pooled, page_size: PAGE_SIZE, @@ -74,38 +101,50 @@ pub(super) fn layout(st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> Ok(l) } -pub(super) fn valid(st: &QsaDesc, l: &Layout, upto: i64) -> ConvResult<()> { - if upto < 0 +/// The extent is inside the state and the mode is a known one. +fn extent_ok(st: &QsaDesc, l: &Layout, upto: i64) -> bool { + !(upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages - || !(0..=2).contains(&st.kv_mode) - || st.n_slots <= 0 + || !(0..=2).contains(&st.kv_mode)) +} + +/// Enough slots, enough pooled rows, and an authoritative host pool wherever the mode needs one. +fn slots_ok(st: &QsaDesc, l: &Layout) -> bool { + !(st.n_slots <= 0 || (st.kv_mode == 0 && st.n_slots < st.n_pages) || l.pooled_rows > st.idx_pooled_rows - || (st.kv_mode != 0 && !st.host.present()) - { + || (st.kv_mode != 0 && !st.host.present())) +} + +fn streaming_map_ok(st: &QsaDesc) -> bool { + let m = &st.map; + !(m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !st.page_table || !m.complete) +} + +/// Every buffer the drafter ring is made of is there. +fn ring_complete(st: &QsaDesc) -> bool { + if st.without_key { + st.v_q && st.v_scale + } else if st.kv_q4 { + st.k_q4 && st.v_q4 + } else if st.kv_int8 { + st.k_q && st.v_q && st.k_scale && st.v_scale + } else { + st.k_pool && st.v_pool + } +} + +pub(super) fn valid(st: &QsaDesc, l: &Layout, upto: i64) -> ConvResult<()> { + if !extent_ok(st, l, upto) || !slots_ok(st, l) { return fail("invalid K/V extent or missing authoritative host pool"); } - if st.kv_mode == 1 { - let m = &st.map; - if m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !st.page_table || !m.complete { - return fail("invalid streaming map"); - } + if st.kv_mode == 1 && !streaming_map_ok(st) { + return fail("invalid streaming map"); } - if st.kv_mode == 2 { - let complete = if st.without_key { - st.v_q && st.v_scale - } else if st.kv_q4 { - st.k_q4 && st.v_q4 - } else if st.kv_int8 { - st.k_q && st.v_q && st.k_scale && st.v_scale - } else { - st.k_pool && st.v_pool - }; - if !st.page_table || !complete { - return fail("invalid draft ring"); - } + if st.kv_mode == 2 && !(st.page_table && ring_complete(st)) { + return fail("invalid draft ring"); } Ok(()) } diff --git a/crates/engine-core/src/conversation/kv/kv_save_fn.rs b/crates/engine-core/src/conversation/kv/kv_save_fn.rs index e0e08a33..0ba7d855 100644 --- a/crates/engine-core/src/conversation/kv/kv_save_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_save_fn.rs @@ -3,6 +3,86 @@ #[allow(unused_imports)] use super::*; +/// Record the geometry of the layout in the image. +fn set_geometry(image: &mut ConversationKv, l: &Layout, g: &ModelGeometry) { + image.format = l.format; + image.cells = l.cells; + image.heads = g.n_head_kv; + image.head_dim = g.head_dim; + image.page_size = l.page_size; + image.pooled_rows = l.pooled_rows; + image.idx_dim = g.idx_key_dim; +} + +/// Bytes at the start of buffer `i` (of size `size`) that stay as they are. Recopy the partial page and the indexer's +/// moving spare row. Completed pages/rows strictly before the first rewritten token remain identical. +fn reusable_prefix( + i: usize, + size: usize, + (l, g): (&Layout, &ModelGeometry), + (index, unchanged_tokens): (bool, i64), +) -> usize { + if i == 4 { + return if index { (unchanged_tokens / IDX_BLOCK) as usize * g.idx_key_dim as usize * 4 } else { 0 }; + } + if l.cells == 0 { + return 0; + } + let whole_cells = (unchanged_tokens / l.page_size) * l.page_size; + (size / l.cells as usize) * whole_cells as usize +} + +/// Copy `size - keep` bytes from the device region into the buffer, after `keep` bytes that are kept. +fn capture_buffer( + buffer: &mut crate::conversation::buffer::ConversationBuffer, + (keep, size): (usize, usize), + present: bool, + (layer, pool): (KvLayer, KvPool), + mem: &mut (impl StateMemory + ?Sized), +) -> ConvResult<()> { + let mut error = None; + let ok = buffer.visit_mut(keep, size - keep, |chunk, at| { + if chunk.is_empty() { + return true; + } + if !present { + error = Some(ConvError("conversation snapshot: missing state buffer".into())); + return false; + } + match mem.read(region(layer, pool, false), at, chunk) { + Ok(()) => true, + Err(message) => { + error = Some(transfer_err(message)); + false + } + } + }); + if ok { Ok(()) } else { Err(error.unwrap_or_else(|| ConvError("conversation snapshot: capture failed".into()))) } +} + +/// Capture every buffer of the layer; returns the bytes of the retained prefixes that were kept. +fn capture_layer( + image: &mut ConversationKv, + layer: KvLayer, + (st, g, l): (&QsaDesc, &ModelGeometry, &Layout), + (index, unchanged_tokens): (bool, i64), + mem: &mut (impl StateMemory + ?Sized), +) -> ConvResult { + let present = st.pools(false); + let sizes = l.sizes(); + let mut reused = 0usize; + for (i, (buffer, pool)) in image.buffers_mut().into_iter().zip(KvPool::ALL).enumerate() { + let keep = reusable_prefix(i, sizes[i], (l, g), (index, unchanged_tokens)); + if keep > buffer.size() { + return fail("missing reusable prefix"); + } + buffer.resize(sizes[i], 0).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; + capture_buffer(buffer, (keep, sizes[i]), present[i], (layer, pool), mem)?; + reused += keep; + } + Ok(reused) +} + /// Capture layer `layer` into `image`. A nonzero `unchanged_tokens` is valid /// only for storage retained from an image actually restored into this /// session, bounded by every subsequent rewrite: equal token IDs alone do not @@ -24,88 +104,59 @@ pub fn kv_save( if unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells { return fail("invalid unchanged prefix"); } - let whole_cells = (unchanged_tokens / l.page_size) * l.page_size; - image.format = l.format; - image.cells = l.cells; - image.heads = g.n_head_kv; - image.head_dim = g.head_dim; - image.page_size = l.page_size; - image.pooled_rows = l.pooled_rows; - image.idx_dim = g.idx_key_dim; - let present = st.pools(false); - let sizes = l.sizes(); - let mut reused = 0usize; - for (i, (buffer, pool)) in image.buffers_mut().into_iter().zip(KvPool::ALL).enumerate() { - // Recopy the partial page and the indexer's moving spare row. Completed - // pages/rows strictly before the first rewritten token remain identical. - let keep = if i == 4 { - if index { (unchanged_tokens / IDX_BLOCK) as usize * g.idx_key_dim as usize * 4 } else { 0 } - } else if l.cells != 0 { - (sizes[i] / l.cells as usize) * whole_cells as usize - } else { - 0 - }; - if keep > buffer.size() { - return fail("missing reusable prefix"); - } - buffer.resize(sizes[i], 0).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; - let mut error = None; - let ok = buffer.visit_mut(keep, sizes[i] - keep, |chunk, at| { - if chunk.is_empty() { - return true; - } - if !present[i] { - error = Some(ConvError("conversation snapshot: missing state buffer".into())); - return false; - } - match mem.read(region(layer, pool, false), at, chunk) { - Ok(()) => true, - Err(message) => { - error = Some(transfer_err(message)); - false - } - } - }); - if !ok { - return Err(error.unwrap_or_else(|| ConvError("conversation snapshot: capture failed".into()))); - } - reused += keep; - } + set_geometry(image, &l, g); + let reused = capture_layer(image, layer, (st, g, &l), (index, unchanged_tokens), mem)?; if let Some(total) = reused_bytes { *total += reused; } Ok(()) } +/// The image was captured with the geometry of the layout. +fn geometry_matches(image: &ConversationKv, l: &Layout, g: &ModelGeometry) -> bool { + image.format == l.format + && image.cells == l.cells + && image.heads == g.n_head_kv + && image.head_dim == g.head_dim + && image.page_size == l.page_size + && image.pooled_rows == l.pooled_rows + && image.idx_dim == g.idx_key_dim +} + /// Structural validation of an image against a target: no device calls. pub fn kv_validate(image: &ConversationKv, st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> ConvResult<()> { let l = layout(st, g, upto, index)?; valid(st, &l, upto)?; - if image.format != l.format - || image.cells != l.cells - || image.heads != g.n_head_kv - || image.head_dim != g.head_dim - || image.page_size != l.page_size - || image.pooled_rows != l.pooled_rows - || image.idx_dim != g.idx_key_dim - { + if !geometry_matches(image, &l, g) { return fail("incompatible K/V geometry"); } let sizes = l.sizes(); - for (buffer, size) in image.buffers().into_iter().zip(sizes) { - if buffer.size() != size { - return fail("invalid K/V payload size"); - } + if image.buffers().into_iter().zip(sizes).any(|(buffer, size)| buffer.size() != size) { + return fail("invalid K/V payload size"); } - let present = st.pools(false); - for (size, present) in sizes.into_iter().zip(present) { - if size != 0 && !present { - return fail("missing target state buffer"); - } + if sizes.into_iter().zip(st.pools(false)).any(|(size, present)| size != 0 && !present) { + return fail("missing target state buffer"); } Ok(()) } +/// Write the whole buffer into the device region of `pool`. +fn restore_buffer( + buffer: &crate::conversation::buffer::ConversationBuffer, + (layer, pool): (KvLayer, KvPool), + mem: &mut (impl StateMemory + ?Sized), +) -> ConvResult<()> { + let mut error = None; + let ok = buffer.visit(0, buffer.size(), |chunk, at| match mem.write(region(layer, pool, false), at, chunk) { + Ok(()) => true, + Err(message) => { + error = Some(transfer_err(message)); + false + } + }); + if ok { Ok(()) } else { Err(error.unwrap_or_else(|| ConvError("conversation snapshot: restore failed".into()))) } +} + /// Write the image into the layer; refills streamed residency afterwards. /// The caller synchronises the device before and after the whole session. pub fn kv_restore( @@ -119,17 +170,7 @@ pub fn kv_restore( ) -> ConvResult<()> { kv_validate(image, st, g, upto, index)?; for (buffer, pool) in image.buffers().into_iter().zip(KvPool::ALL) { - let mut error = None; - let ok = buffer.visit(0, buffer.size(), |chunk, at| match mem.write(region(layer, pool, false), at, chunk) { - Ok(()) => true, - Err(message) => { - error = Some(transfer_err(message)); - false - } - }); - if !ok { - return Err(error.unwrap_or_else(|| ConvError("conversation snapshot: restore failed".into()))); - } + restore_buffer(buffer, (layer, pool), mem)?; } let residency = |message: String| ConvError(format!("conversation snapshot residency restore: {message}")); // VRAM slots still contain the outgoing conversation. Resolve must refill diff --git a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs index 12ac19cc..6a6d6daf 100644 --- a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs @@ -3,6 +3,28 @@ #[allow(unused_imports)] use super::*; +/// Compare the pages of the drafter ring (the last `st.n_slots` pages of the saved pool) with the device's resident +/// copy of them; false once a page differs or cannot be read (the verifier holds the failure). +fn verify_ring( + v: &mut Verifier<'_>, + saved: &crate::conversation::buffer::ConversationBuffer, + (begin, end): (i64, i64), + (layer, pool, st): (KvLayer, KvPool, &QsaDesc), +) -> bool { + let page_bytes = saved.size() / end as usize; + for page in begin..end { + let first = page as usize * page_bytes; + let ring = (page % st.n_slots) as usize * page_bytes; + let ok = saved.visit(first, page_bytes, |chunk, at| { + v.compare(region(layer, pool, true), ring + at - first, chunk, false) + }); + if !ok { + return false; + } + } + true +} + /// Diagnostic read-back after a synchronised restore: compares the /// authoritative bytes (and the resident draft-ring pages), fingerprinting the /// authoritative payload only (FNV-1a 64). Never changes model state. @@ -26,19 +48,8 @@ pub fn kv_verify( let end = image.cells / image.page_size; let begin = (end - st.n_slots).max(0); for (saved, pool) in image.buffers().into_iter().take(4).zip(KvPool::ALL) { - if saved.is_empty() { - continue; - } - let page_bytes = saved.size() / end as usize; - for page in begin..end { - let first = page as usize * page_bytes; - let ring = (page % st.n_slots) as usize * page_bytes; - let ok = saved.visit(first, page_bytes, |chunk, at| { - v.compare(region(layer, pool, true), ring + at - first, chunk, false) - }); - if !ok { - return Err(v.failure()); - } + if !saved.is_empty() && !verify_ring(&mut v, saved, (begin, end), (layer, pool, st)) { + return Err(v.failure()); } } } diff --git a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs index e45b0bd8..addd1092 100644 --- a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs +++ b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs @@ -63,14 +63,14 @@ impl ConversationManager { self.pp_next_check = 0; } - /// Save only on a switch/rewind, not on each continuing request. `held` is - /// an incoming image that is still alive during the exchange. Anything - /// recoverable (nothing to park, no room, no RAM, allocation failure) - /// skips parking and returns `Ok`; a device failure is fatal. - pub(in super::super) fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> { - if !self.cache.enabled() || !self.live_ok || self.live.is_empty() { - return Ok(()); - } + /// Note that parking was skipped, and why. + fn skip_parking(&mut self, why: &str) { + self.events.push(format!("conversation cache: skip parking ({why})")); + } + + /// The bytes a park of the live conversation needs, and the retained K/V it can reuse; `None` (parking skipped) + /// when the engine cannot size it. A retained K/V the engine cannot reuse is dropped. + fn estimate_park(&mut self, engine: &mut (impl SessionEngine + ?Sized)) -> Option<(usize, ConversationKvReuse)> { let view = ConversationView { ids: &self.live, images: &self.live_imgs, @@ -82,7 +82,7 @@ impl ConversationManager { Ok(n) => n, Err(e) => { self.events.push(format!("conversation cache: skip parking ({e})")); - return Ok(()); + return None; } }; let mut estimate = fresh_estimate; @@ -95,12 +95,17 @@ impl ConversationManager { } } } - // A park carrying its own retained K/V replaces memory the cache - // already held, so capacity is make_room's call: the with-reuse - // estimate must stay uncapped, because put() charges that same true - // size and a capped figure would under-evict and overfill the budget. - // #342: before make_room evicts oldest-first, the copies of this - // conversation a turn back go. + Some((estimate, reuse)) + } + + /// Drop the superseded copies of this conversation, then make room for `estimate` bytes. False (parking skipped) + /// when it does not fit the budget. + /// + /// A park carrying its own retained K/V replaces memory the cache already held, so capacity is make_room's call: + /// the with-reuse estimate must stay uncapped, because put() charges that same true size and a capped figure + /// would under-evict and overfill the budget. #342: before make_room evicts oldest-first, the copies of this + /// conversation a turn back go. + fn make_room_for_park(&mut self, estimate: usize, held: usize) -> bool { let keys: Vec> = self.checks.iter().map(|c| CheckpointKey { ids: &c.ids, imgs: &c.imgs }).collect(); let dropped = self.cache.drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached); @@ -111,50 +116,80 @@ impl ConversationManager { self.cache.size() )); } - if !self.cache.make_room(estimate, held) { - self.events.push(format!( - "conversation cache: skip parking (snapshot {} MiB exceeds available budget)", - estimate >> 20 - )); - return Ok(()); + if self.cache.make_room(estimate, held) { + return true; } - let floor = self.options.conversation_cache_min_free_bytes; - let additional = estimate.saturating_sub(reuse.bytes()); - if !memory_admit(engine.available_memory(), additional as u64, floor) { - self.events.push(format!( - "conversation cache: skip parking (physical RAM admission; need {} MiB plus {} MiB floor, or telemetry unavailable)", - additional >> 20, - floor >> 20 - )); - return Ok(()); - } - let mut reused_bytes = 0usize; - let image = match engine.snapshot_save(&view, reuse, &mut reused_bytes) { - Ok(image) => image, - Err(e) if is_allocation(&e) => { - // The active state has not been touched: continue with normal - // prompt processing rather than killing a serving process. - self.events.push("conversation cache: allocation failed; skip parking".into()); - return Ok(()); - } - Err(e) => return Err(e), + self.skip_parking(&format!("snapshot {} MiB exceeds available budget", estimate >> 20)); + false + } + + /// Capture the live conversation. `None` (parking skipped) when the allocation fails: the active state has not + /// been touched, so normal prompt processing continues rather than killing a serving process. The bytes of + /// retained K/V the capture reused come with the image. + fn capture_for_park( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + reuse: ConversationKvReuse, + ) -> ConvResult> { + let view = ConversationView { + ids: &self.live, + images: &self.live_imgs, + checkpoints: &self.checks, + cvec: self.cvec_cached, }; - if !memory_admit(engine.available_memory(), 0, floor) { - self.events.push( - "conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)".into(), - ); - return Ok(()); + let mut reused_bytes = 0usize; + match engine.snapshot_save(&view, reuse, &mut reused_bytes) { + Ok(image) => Ok(Some((image, reused_bytes))), + Err(e) if is_allocation(&e) => { + self.events.push("conversation cache: allocation failed; skip parking".into()); + Ok(None) + } + Err(e) => Err(e), } + } + + /// Put the captured `image` into the cache and note the result. + fn store_parked(&mut self, image: SavedConversation, held: usize, reused_bytes: usize) { let snapshot_bytes = image.bytes(); let tokens = self.live.len(); let stored = self.cache.put(image, held).is_ok(); self.events.push(format!( - "conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={} snapshot_bytes={snapshot_bytes} reused_kv_bytes={reused_bytes}", + "conversation cache: {} {tokens} tokens; parked={} bytes={} evictions={} snapshot_bytes={snapshot_bytes} \ + reused_kv_bytes={reused_bytes}", if stored { "parked" } else { "skipped" }, self.cache.size(), self.cache.bytes(), self.cache.evictions(), )); + } + + /// Save only on a switch/rewind, not on each continuing request. `held` is + /// an incoming image that is still alive during the exchange. Anything + /// recoverable (nothing to park, no room, no RAM, allocation failure) + /// skips parking and returns `Ok`; a device failure is fatal. + pub(in super::super) fn park_current(&mut self, engine: &mut dyn SessionEngine, held: usize) -> ConvResult<()> { + if !self.cache.enabled() || !self.live_ok || self.live.is_empty() { + return Ok(()); + } + let Some((estimate, reuse)) = self.estimate_park(engine) else { return Ok(()) }; + if !self.make_room_for_park(estimate, held) { + return Ok(()); + } + let floor = self.options.conversation_cache_min_free_bytes; + let additional = estimate.saturating_sub(reuse.bytes()); + if !memory_admit(engine.available_memory(), additional as u64, floor) { + let (need, floor_mib) = (additional >> 20, floor >> 20); + self.skip_parking(&format!( + "physical RAM admission; need {need} MiB plus {floor_mib} MiB floor, or telemetry unavailable" + )); + return Ok(()); + } + let Some((image, reused_bytes)) = self.capture_for_park(engine, reuse)? else { return Ok(()) }; + if !memory_admit(engine.available_memory(), 0, floor) { + self.skip_parking("physical RAM floor after capture, or telemetry unavailable"); + return Ok(()); + } + self.store_parked(image, held, reused_bytes); Ok(()) } } diff --git a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs index 41eb4166..8a27d97e 100644 --- a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs +++ b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs @@ -4,21 +4,11 @@ use super::*; impl ConversationManager { - /// Decide where `ids` starts reading and put the device in that state: - /// continue the live session, restore a checkpoint, restore a parked - /// conversation (parking the outgoing one first), or start empty. Any - /// error is fatal for the request and the device state is then undefined. - pub fn begin_request( - &mut self, - engine: &mut dyn SessionEngine, - ids: &[i32], - req_imgs: &[ConversationImageKey], - want_cvec: bool, - ) -> ConvResult { - let prompt_cache = self.options.prompt_cache > 0; - let mut resume = 0usize; - let mut from_live = false; - if prompt_cache && want_cvec == self.cvec_cached { + /// The longest prefix of `ids` the device can continue from without a parked conversation: the live session or + /// the longest checkpoint (later checkpoints win a tie). `(resume, from_live)`. + fn pick_resume(&self, ids: &[i32], req_imgs: &[ConversationImageKey], want_cvec: bool) -> (usize, bool) { + let (mut resume, mut from_live) = (0usize, false); + if self.options.prompt_cache > 0 && want_cvec == self.cvec_cached { if self.live_ok && starts_with(&self.live, &self.live_imgs, ids, req_imgs) { resume = self.live.len(); from_live = true; @@ -30,83 +20,94 @@ impl ConversationManager { } } } - let parked = self.cache.best(ids, req_imgs, want_cvec); - let mut incoming = if parked.tokens as usize > resume { self.cache.take(parked.index) } else { None }; + (resume, from_live) + } + + /// The parked conversation that reaches further than `resume`, taken out of the cache; `None` when there is none + /// or the engine rejects its image. + fn take_incoming( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + parked: &crate::conversation::cache::Match, + resume: usize, + ) -> Option { + let incoming = if parked.tokens as usize > resume { self.cache.take(parked.index) } else { None }; // Reject the entire image before parking/overwriting the outgoing // state. Invalid entries can safely fall back to the existing prefix. if let Some(image) = &incoming && let Err(e) = engine.snapshot_validate(image) { self.events.push(format!("conversation cache: discard invalid snapshot ({e})")); - incoming = None; + return None; } - // Preserve the outgoing branch before any checkpoint rewind, reset or - // incoming restore overwrites the positional state it requires. - if !from_live || incoming.is_some() { - let held = incoming.as_ref().map_or(0, SavedConversation::bytes); - self.park_current(engine, held)?; - } - let mut restored = None; - if let Some(mut image) = incoming { - match engine.snapshot_restore(&image) { - RestoreOutcome::Restored => {} - // Already prevalidated: a failure here is fatal, never - // permission to decode from a partially restored session. - RestoreOutcome::Invalid(e) | RestoreOutcome::TransferFailed(e) => { - return Err(ConvError(format!("restoring parked conversation: {e}"))); - } + incoming + } + + /// Put the device into the state of the parked conversation `image` (already validated: a failure here is fatal, + /// never permission to decode from a partially restored session). Returns `(resume, from_live)`. + fn restore_parked( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + mut image: SavedConversation, + parked: &crate::conversation::cache::Match, + ) -> ConvResult<(usize, bool)> { + match engine.snapshot_restore(&image) { + RestoreOutcome::Restored => {} + RestoreOutcome::Invalid(e) | RestoreOutcome::TransferFailed(e) => { + return Err(ConvError(format!("restoring parked conversation: {e}"))); } - self.live = std::mem::take(&mut image.live.ids); - self.live_imgs = std::mem::take(&mut image.live.imgs); - self.checks = std::mem::take(&mut image.checkpoints); - self.cvec_cached = image.cvec; - resume = parked.tokens as usize; - from_live = parked.live; - restored = Some((resume, from_live)); - if self.options.incremental_capture { - self.cache.retain(std::mem::take(&mut image.kv), self.live.len() as i64); - } - self.events.push(format!( - "conversation cache: restored {resume} tokens ({}); parked={} bytes={}", - if from_live { "live" } else { "checkpoint" }, - self.cache.size(), - self.cache.bytes() - )); } + self.live = std::mem::take(&mut image.live.ids); + self.live_imgs = std::mem::take(&mut image.live.imgs); + self.checks = std::mem::take(&mut image.checkpoints); + self.cvec_cached = image.cvec; + let (resume, from_live) = (parked.tokens as usize, parked.live); + if self.options.incremental_capture { + self.cache.retain(std::mem::take(&mut image.kv), self.live.len() as i64); + } + self.events.push(format!( + "conversation cache: restored {resume} tokens ({}); parked={} bytes={}", + if from_live { "live" } else { "checkpoint" }, + self.cache.size(), + self.cache.bytes() + )); + Ok((resume, from_live)) + } + + /// Steering follows the request; a checkpoint past `resume` (or not on this prompt's path) no longer has its + /// cells, because this request rewrites every cell from `resume` on; the ones kept are prefixes of both the old + /// tokens and the new. + fn align_to_request( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + want_cvec: bool, + resume: usize, + (ids, req_imgs): (&[i32], &[ConversationImageKey]), + ) { if want_cvec != self.cvec_cached { self.live_ok = false; self.checks.clear(); self.cvec_cached = want_cvec; } engine.set_steering(want_cvec); - // This request rewrites every cell from `resume` on, so a checkpoint - // past it (or not on this prompt's path) no longer has its cells; the - // ones kept are prefixes of both the old tokens and the new. self.checks.retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs)); self.live_ok = false; // until this request has finished, the session is in between + } + + /// Bring the device to `resume` tokens: empty, the live session as it is, or a checkpoint restored (or, under + /// `STRATA_CKPT_REREAD`, read again from 0: the position to read to is returned). + fn position_device( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + resume: usize, + from_live: bool, + ) -> ConvResult> { let mut reread_to = None; if resume == 0 { engine.zero_session()?; self.checks.clear(); } else if !from_live { - let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else { - return Err(ConvError("restoring a conversation checkpoint failed".into())); - }; - self.check_clock += 1; - self.checks[index].used = self.check_clock; - if self.options.reread_checkpoints { - // THE CHECK OF THE CHECKPOINT: read its tokens again from - // position 0 instead of restoring it; with the expert set - // fixed the answer must match the restored one token for token. - engine.zero_session()?; - reread_to = Some(resume); - self.events.push(format!("STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring")); - } else { - let c = &self.checks[index]; - if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() { - return Err(ConvError("restoring a conversation checkpoint failed".into())); - } - } + reread_to = self.restore_checkpoint(engine, resume)?; } // KV streaming: the drafter's ring may hold cells past `resume` from a // longer turn; the main layers' host copies and slots are always @@ -114,11 +115,97 @@ impl ConversationManager { if resume > 0 && reread_to.is_none() { engine.restore_draft(resume)?; } + Ok(reread_to) + } + + /// Restore the checkpoint at `resume` tokens (the most recent one of that length becomes the most recently used). + fn restore_checkpoint( + &mut self, + engine: &mut (impl SessionEngine + ?Sized), + resume: usize, + ) -> ConvResult> { + let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else { + return Err(ConvError("restoring a conversation checkpoint failed".into())); + }; + self.check_clock += 1; + self.checks[index].used = self.check_clock; + if self.options.reread_checkpoints { + // THE CHECK OF THE CHECKPOINT: read its tokens again from + // position 0 instead of restoring it; with the expert set + // fixed the answer must match the restored one token for token. + engine.zero_session()?; + self.events.push(format!("STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring")); + return Ok(Some(resume)); + } + let c = &self.checks[index]; + if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() { + return Err(ConvError("restoring a conversation checkpoint failed".into())); + } + Ok(None) + } + + /// The record of how the request starts; also limits the retained K/V reuse and schedules the next checkpoint. + fn request_start( + &mut self, + resume: usize, + from_live: bool, + restored: Option<(usize, bool)>, + reread_to: Option, + ) -> RequestStart { let read_from = if reread_to.is_some() { 0 } else { resume }; self.cache.limit_reuse(read_from as i64); self.pp_next_check = if reread_to.is_some() { i64::MAX } else { resume as i64 + self.options.prompt_cache_every }; - Ok(RequestStart { resume, from_live, restored, reread_to, read_from }) + RequestStart { resume, from_live, restored, reread_to, read_from } + } + + /// Decide where `ids` starts reading and put the device in that state: + /// continue the live session, restore a checkpoint, restore a parked + /// conversation (parking the outgoing one first), or start empty. Any + /// error is fatal for the request and the device state is then undefined. + pub fn begin_request( + &mut self, + engine: &mut dyn SessionEngine, + ids: &[i32], + req_imgs: &[ConversationImageKey], + want_cvec: bool, + ) -> ConvResult { + let (mut resume, mut from_live) = self.pick_resume(ids, req_imgs, want_cvec); + let parked = self.cache.best(ids, req_imgs, want_cvec); + let incoming = self.take_incoming(engine, &parked, resume); + // Preserve the outgoing branch before any checkpoint rewind, reset or + // incoming restore overwrites the positional state it requires. + if !from_live || incoming.is_some() { + let held = incoming.as_ref().map_or(0, SavedConversation::bytes); + self.park_current(engine, held)?; + } + let mut restored = None; + if let Some(image) = incoming { + (resume, from_live) = self.restore_parked(engine, image, &parked)?; + restored = Some((resume, from_live)); + } + self.align_to_request(engine, want_cvec, resume, (ids, req_imgs)); + let reread_to = self.position_device(engine, resume, from_live)?; + Ok(self.request_start(resume, from_live, restored, reread_to)) + } + + /// The checkpoint at `position` is already there: it just becomes the most recently used. + fn touch_checkpoint(&mut self, position: usize) -> bool { + let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) else { + return false; + }; + self.check_clock += 1; + existing.used = self.check_clock; + true + } + + /// Evict checkpoints (least valuable first) while there are more than `prompt_cache`. + fn evict_surplus_checkpoints(&mut self) { + while self.checks.len() as i64 > self.options.prompt_cache { + let stamps: Vec = self.checks.iter().map(|k| k.used).collect(); + let victim = eviction_victim(&stamps, self.options.prompt_cache); + self.checks.remove(victim); + } } /// A checkpoint of the state after `ids[..position]`. `Ok` also when @@ -137,9 +224,7 @@ impl ConversationManager { if position > ids.len() { return Err(ConvError("conversation checkpoint beyond the prompt".into())); } - if let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) { - self.check_clock += 1; - existing.used = self.check_clock; + if self.touch_checkpoint(position) { return Ok(()); } let mut c = ConversationCheckpoint { @@ -152,11 +237,7 @@ impl ConversationManager { self.check_clock += 1; c.used = self.check_clock; self.checks.push(c); - while self.checks.len() as i64 > self.options.prompt_cache { - let stamps: Vec = self.checks.iter().map(|k| k.used).collect(); - let victim = eviction_victim(&stamps, self.options.prompt_cache); - self.checks.remove(victim); - } + self.evict_surplus_checkpoints(); Ok(()) } diff --git a/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs b/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs index 78c6f440..7fb31d2c 100644 --- a/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs +++ b/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Default_for_ConversationOptions, fn images_below, fn starts_with, fn is_allocation. +//! Moved out of the parent module by STRA-338: impl Default_for_ConversationOptions, fn images_below, fn starts_with, +//! fn is_allocation. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs index 84a5edbe..64187391 100644 --- a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs +++ b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs @@ -1,4 +1,8 @@ -//! Tests of manager_tests by topic (moved out of the test file by STRA-338): the_byte_budget_and_slot_limit_evict_oldest_first, an_incompatible_parked_image_is_discarded_and_the_request_falls_back, a_failed_restore_transfer_is_fatal_to_the_request, switching_steering_invalidates_checkpoints_and_isolates_parked_images .... +//! Tests of manager_tests by topic (moved out of the test file by STRA-338): +//! the_byte_budget_and_slot_limit_evict_oldest_first, +//! an_incompatible_parked_image_is_discarded_and_the_request_falls_back, +//! a_failed_restore_transfer_is_fatal_to_the_request, +//! switching_steering_invalidates_checkpoints_and_isolates_parked_images .... #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs index 37d7b641..bf0cf6dd 100644 --- a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs +++ b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs @@ -1,4 +1,7 @@ -//! Tests of manager_tests by topic (moved out of the test file by STRA-338): a_continuing_chat_reuses_the_live_session_without_a_copy, an_identical_prompt_still_reads_its_last_token, a_rewritten_tail_resumes_from_the_turn_boundary_checkpoint, the_shared_root_is_pinned_while_other_checkpoints_rotate .... +//! Tests of manager_tests by topic (moved out of the test file by STRA-338): +//! a_continuing_chat_reuses_the_live_session_without_a_copy, an_identical_prompt_still_reads_its_last_token, +//! a_rewritten_tail_resumes_from_the_turn_boundary_checkpoint, the_shared_root_is_pinned_while_other_checkpoints_rotate +//! .... #[allow(unused_imports)] use super::*; @@ -111,9 +114,10 @@ fn switching_between_conversations_parks_and_restores_exactly() { #[test] fn a_restored_conversations_retained_kv_never_serves_another_conversation() { - // Upstream f8ff3420: a retained K/V image tracked a token COUNT, so after another conversation took the session the next park - // reused the first conversation's K/V for the new one. Here the retained image is dropped as soon as a request rewrites the - // session below the cells it claims, and every restore below is checked cell by cell against the tokens it names. + // Upstream f8ff3420: a retained K/V image tracked a token COUNT, so after another conversation took the session the + // next park reused the first conversation's K/V for the new one. Here the retained image is dropped as soon as a + // request rewrites the session below the cells it claims, and every restore below is checked cell by cell against + // the tokens it names. let mut w = world(options(), false); let a1 = chat(1, 20, &[10]); let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); @@ -127,7 +131,8 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { assert!(r.start.restored.is_some()); assert!(w.mgr.cache().retained_bytes() > 0, "the restore retained A's K/V"); w.mgr.take_events(); - // a third conversation takes the session from A (resume 0): A is parked, and the retained image is consumed by A's own park only + // a third conversation takes the session from A (resume 0): A is parked, and the retained image is consumed by A's + // own park only let c1 = chat(3, 16, &[12]); let rc = w.request(&c1, &[], true, &gen_tokens(4, 6), None, 8).unwrap(); assert_eq!(rc.start.resume, 0); @@ -136,7 +141,8 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { let parked_a = events.iter().filter(|e| e.contains("parked ") && e.contains(&format!("{} tokens", r.consumed.len()))).count(); assert_eq!(parked_a, 1, "{events:?}"); - // every conversation comes back with exactly its own cells (the harness asserts the device state after each begin_request) + // every conversation comes back with exactly its own cells (the harness asserts the device state after each + // begin_request) for (conv, tag) in [(r.consumed.clone(), 5), (rb.consumed.clone(), 6), (rc.consumed.clone(), 7)] { let mut next = conv.clone(); next.extend([TURN, tag, tag, tag]); diff --git a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs index 927f2d39..f2713008 100644 --- a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs +++ b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn hash, fn pat, fn pattern, fn idx, impl SimDevice, impl StateMemory_for_SimDevice. +//! Moved out of the parent module by STRA-338: fn hash, fn pat, fn pattern, fn idx, impl SimDevice, impl +//! StateMemory_for_SimDevice. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs index cf601378..e7ffd319 100644 --- a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs +++ b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl SessionDevice_for_SimDevice, fn options, fn world, fn prompt_options, fn chat, impl World .... +//! Moved out of the parent module by STRA-338: impl SessionDevice_for_SimDevice, fn options, fn world, fn +//! prompt_options, fn chat, impl World .... #[allow(unused_imports)] use super::*; @@ -38,8 +39,9 @@ pub(super) fn options() -> ConversationOptions { } } -pub(super) fn world(options: ConversationOptions, ple: bool) -> World { - let g = ModelGeometry { +/// The small model the simulated device runs. +fn world_geometry() -> ModelGeometry { + ModelGeometry { n_layers: 4, ssm_state_size: 2, ssm_v_heads: 2, @@ -48,7 +50,27 @@ pub(super) fn world(options: ConversationOptions, ple: bool) -> World { head_dim: 64, idx_key_dim: 8, ..ModelGeometry::default() - }; + } +} + +/// The session owning one QSA layer with the state `st`. +fn world_session(g: &ModelGeometry, ple: bool, st: crate::conversation::model::QsaDesc) -> SessionSpec { + SessionSpec { + shape: SessionShape { + max_cells: MAX_CELLS as i64, + layer_hi: g.n_layers, + gdn_alloc: g.n_gdn_layers(), + qsa_alloc: g.n_qsa_layers(), + has_gdn_state: true, + has_ple_hist: ple, + ..Default::default() + }, + qsa: vec![st], + } +} + +pub(super) fn world(options: ConversationOptions, ple: bool) -> World { + let g = world_geometry(); let mut mem = HostMemory::new(); let pages = (MAX_CELLS / PAGE) as i64; let main = Fixture::with_geometry(&mut mem, KvLayer::Main(0), 0, 0, g, pages); @@ -63,18 +85,7 @@ pub(super) fn world(options: ConversationOptions, ple: bool) -> World { st.idx_tail = true; st.idx_dead = true; st.idx_block_pos = true; - let ss = SessionSpec { - shape: SessionShape { - max_cells: MAX_CELLS as i64, - layer_hi: g.n_layers, - gdn_alloc: g.n_gdn_layers(), - qsa_alloc: g.n_qsa_layers(), - has_gdn_state: true, - has_ple_hist: ple, - ..Default::default() - }, - qsa: vec![st], - }; + let ss = world_session(&g, ple, st); let dev = SimDevice { mem, g, @@ -104,6 +115,33 @@ pub(super) fn chat(salt: i32, system: usize, turns: &[usize]) -> Vec { } impl World { + /// Read the prompt per the plan with the manager's checkpoints; the position reached, or `None` when the request + /// was cancelled after `stop_after` actions. + fn read_plan( + &mut self, + ids: &[i32], + imgs: &[ConversationImageKey], + plan: PromptPlan<'_>, + (read_from, stop_after): (usize, Option), + ) -> Result, String> { + let mut at = read_from; + for (done_actions, action) in plan.enumerate() { + if action.path == PromptPath::FinalSeed { + break; + } + if stop_after == Some(done_actions) { + return Ok(None); + } + assert_eq!(action.first, at, "plan is contiguous"); + self.dev.read(ids, action.first, action.first + action.count); + at += action.count; + let mut engine = + DeviceEngine { device: &mut self.dev, geometry: &self.g, session: &self.ss, draft: &self.draft }; + self.mgr.after_prompt_action(&mut engine, ids, imgs, &action).map_err(|e| e.0)?; + } + Ok(Some(at)) + } + /// One whole request: begin, read the prompt per the plan with the /// manager's checkpoints, decode `gen` (all but the last token commit), /// finish. `stop_after` cancels after that many prompt actions. @@ -124,22 +162,10 @@ impl World { let prompt: Vec = ids.iter().map(|&i| i as u32).collect(); let plan = PromptPlan::new(&prompt, start.resume, start.reread_to, None, prompt_options(root_min), 256) .map_err(|e| format!("{e:?}"))?; - let mut at = start.read_from; - for (done_actions, action) in plan.enumerate() { - if action.path == PromptPath::FinalSeed { - break; - } - if stop_after == Some(done_actions) { - self.mgr.finish_request(Vec::new(), imgs, true); - return Ok(Run { start, consumed: Vec::new() }); - } - assert_eq!(action.first, at, "plan is contiguous"); - self.dev.read(ids, action.first, action.first + action.count); - at += action.count; - let mut engine = - DeviceEngine { device: &mut self.dev, geometry: &self.g, session: &self.ss, draft: &self.draft }; - self.mgr.after_prompt_action(&mut engine, ids, imgs, &action).map_err(|e| e.0)?; - } + let Some(at) = self.read_plan(ids, imgs, plan, (start.read_from, stop_after))? else { + self.mgr.finish_request(Vec::new(), imgs, true); + return Ok(Run { start, consumed: Vec::new() }); + }; // The last prompt token and the committed generated tokens read through verify windows. let mut consumed = ids.to_vec(); consumed.extend_from_slice(&gen_tokens[..gen_tokens.len().saturating_sub(1)]); diff --git a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs index c1e109ab..952c72ef 100644 --- a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs +++ b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs @@ -1,4 +1,5 @@ -//! Tests of manager_tests by topic (moved out of the test file by STRA-338): random_conversation_traffic_always_resumes_into_the_exact_prefix_state. +//! Tests of manager_tests by topic (moved out of the test file by STRA-338): +//! random_conversation_traffic_always_resumes_into_the_exact_prefix_state. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/model.rs b/crates/engine-core/src/conversation/model.rs index ad3cdb2f..e32d985e 100644 --- a/crates/engine-core/src/conversation/model.rs +++ b/crates/engine-core/src/conversation/model.rs @@ -197,34 +197,17 @@ impl QsaDesc { /// authoritative copy (`resident == false`, host pools when streamed) or /// the VRAM slots (`resident == true`). pub fn pools(&self, resident: bool) -> [bool; 5] { - let host = self.kv_mode != 0 && !resident; - let h = &self.host; + let from_host = self.kv_mode != 0 && !resident; + let (h, pick) = (&self.host, |host: bool, own: bool| if from_host { host } else { own }); if self.kv_hybrid { [self.k_q, self.v_q4, self.k_scale, false, self.idx_pooled] } else if self.kv_q4 { - [ - if host { h.k_q4 } else { self.k_q4 }, - if host { h.v_q4 } else { self.v_q4 }, - false, - false, - self.idx_pooled, - ] + [pick(h.k_q4, self.k_q4), pick(h.v_q4, self.v_q4), false, false, self.idx_pooled] } else if self.kv_int8 { - [ - if host { h.k_q } else { self.k_q }, - if host { h.v_q } else { self.v_q }, - if host { h.k_scale } else { self.k_scale }, - if host { h.v_scale } else { self.v_scale }, - self.idx_pooled, - ] + let (k, v) = (pick(h.k_q, self.k_q), pick(h.v_q, self.v_q)); + [k, v, pick(h.k_scale, self.k_scale), pick(h.v_scale, self.v_scale), self.idx_pooled] } else { - [ - if host { h.k_pool } else { self.k_pool }, - if host { h.v_pool } else { self.v_pool }, - false, - false, - self.idx_pooled, - ] + [pick(h.k_pool, self.k_pool), pick(h.v_pool, self.v_pool), false, false, self.idx_pooled] } } } diff --git a/crates/engine-core/src/conversation/snapshot.rs b/crates/engine-core/src/conversation/snapshot.rs index a9c37360..4126ac8f 100644 --- a/crates/engine-core/src/conversation/snapshot.rs +++ b/crates/engine-core/src/conversation/snapshot.rs @@ -37,33 +37,40 @@ pub enum RestoreOutcome { TransferFailed(String), } +/// The checkpoint is a non-empty live token prefix of the view, and a whole one. +fn is_live_prefix(c: &ConversationCheckpoint, ids: &[i32]) -> bool { + c.stage_parts.is_empty() && !c.ids.is_empty() && c.ids.len() <= ids.len() && c.ids[..] == ids[..c.ids.len()] +} + +/// The images below the checkpoint's end are exactly the checkpoint's own. +fn check_checkpoint_images(c: &ConversationCheckpoint, images: &[ConversationImageKey]) -> ConvResult<()> { + let mut image = 0; + for key in images { + if key.start as u64 >= c.ids.len() as u64 { + break; + } + if image >= c.imgs.len() || c.imgs[image] != *key { + return fail("checkpoint image identity differs"); + } + image += 1; + } + if image != c.imgs.len() { + return fail("checkpoint image prefix differs"); + } + Ok(()) +} + fn view_validate(view: &ConversationView<'_>, ss: &SessionSpec, g: &ModelGeometry) -> ConvResult<()> { checkpoint_targets(ss, g, view.ids.len())?; if view.ids.is_empty() || !image_keys(view.images, view.ids.len()) || view.ids.iter().any(|&id| id < 0) { return fail("invalid live token/image metadata"); } for c in view.checkpoints { - if !c.stage_parts.is_empty() - || c.ids.is_empty() - || c.ids.len() > view.ids.len() - || c.ids[..] != view.ids[..c.ids.len()] - { + if !is_live_prefix(c, view.ids) { return fail("checkpoint is not a live token prefix"); } checkpoint_validate(c, ss, g)?; - let mut image = 0; - for key in view.images { - if key.start as u64 >= c.ids.len() as u64 { - break; - } - if image >= c.imgs.len() || c.imgs[image] != *key { - return fail("checkpoint image identity differs"); - } - image += 1; - } - if image != c.imgs.len() { - return fail("checkpoint image prefix differs"); - } + check_checkpoint_images(c, view.images)?; } Ok(()) } @@ -88,6 +95,35 @@ fn layer_state<'a>(ss: &'a SessionSpec, draft: &'a QsaDesc, i: usize) -> ConvRes } } +/// Bytes of everything a snapshot carries besides the K/V: the live ids and image keys, the checkpoint chain and the +/// state buffers. +fn metadata_total(view: &ConversationView<'_>, ss: &SessionSpec, z: &StateSizes) -> ConvResult { + let qsa = ss.owned_qsa() as u64; + let counts = [ + (view.ids.len() as u64, size_of::() as u64), + (view.images.len() as u64, size_of::() as u64), + (view.checkpoints.len() as u64, size_of::() as u64), + (qsa + 1, size_of::() as u64), + (qsa, z.tail as u64), + (qsa, z.dead as u64), + (qsa, z.block_pos as u64), + ]; + let mut parts = Vec::with_capacity(counts.len() + 2); + for (n, unit) in counts { + let overflow = || ConvError("conversation snapshot: snapshot metadata byte count overflow".into()); + parts.push(product(&[n, unit]).ok_or_else(overflow)?); + } + parts.extend([z.gdn, if ss.shape.has_ple_hist { z.ple } else { 0 }]); + let mut bytes = 0usize; + if !parts.into_iter().all(|n| add(&mut bytes, n)) { + return fail("snapshot byte count overflow"); + } + if !view.checkpoints.iter().all(|c| metadata_bytes(c, &mut bytes)) { + return fail("checkpoint byte count overflow"); + } + Ok(bytes) +} + /// `conversation_snapshot_bytes`: exact bytes a fresh capture of `view` takes. pub fn snapshot_bytes( view: &ConversationView<'_>, @@ -97,28 +133,7 @@ pub fn snapshot_bytes( ) -> ConvResult { view_validate(view, ss, g)?; let z: StateSizes = session_sizes(g, ss)?; - let qsa = ss.owned_qsa() as u64; - let overflow = || ConvError("conversation snapshot: snapshot metadata byte count overflow".into()); - let ids = product(&[view.ids.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; - let images = product(&[view.images.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; - let checkpoints = - product(&[view.checkpoints.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; - let layers = product(&[qsa + 1, size_of::() as u64]).ok_or_else(overflow)?; - let tails = product(&[qsa, z.tail as u64]).ok_or_else(overflow)?; - let dead = product(&[qsa, z.dead as u64]).ok_or_else(overflow)?; - let positions = product(&[qsa, z.block_pos as u64]).ok_or_else(overflow)?; - let mut bytes = 0usize; - let ple = if ss.shape.has_ple_hist { z.ple } else { 0 }; - for n in [ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ple] { - if !add(&mut bytes, n) { - return fail("snapshot byte count overflow"); - } - } - for c in view.checkpoints { - if !metadata_bytes(c, &mut bytes) { - return fail("checkpoint byte count overflow"); - } - } + let mut bytes = metadata_total(view, ss, &z)?; let upto = view.ids.len() as i64; // view_validate bounds this by signed max_cells for i in 0..=ss.owned_qsa() { let st = layer_state(ss, draft, i)?; @@ -130,6 +145,41 @@ pub fn snapshot_bytes( Ok(bytes) } +/// The retained K/V prefix describes this view: one image per layer, never more unchanged than captured or live. +fn reuse_is_valid(reuse: &ConversationKvReuse, view: &ConversationView<'_>, layers: usize) -> bool { + reuse.kv.len() == layers + && reuse.unchanged_tokens >= 0 + && reuse.unchanged_tokens <= reuse.captured_tokens + && reuse.unchanged_tokens <= view.ids.len() as i64 +} + +/// Replace the fresh estimate of every layer by what its retained image allocates, and add the directory capacity. +fn retained_adjust( + bytes: &mut usize, + reuse: &ConversationKvReuse, + view: &ConversationView<'_>, + (ss, g, draft): (&SessionSpec, &ModelGeometry, &QsaDesc), +) -> ConvResult<()> { + let layers = ss.owned_qsa() + 1; + for (i, image) in reuse.kv.iter().enumerate() { + let index = i + 1 != layers; + let st = layer_state(ss, draft, i)?; + kv_validate(image, st, g, reuse.captured_tokens, index)?; + let fresh = kv_bytes(st, g, view.ids.len() as i64, index); + let retained = kv_capture_bytes(image, st, g, view.ids.len() as i64, index)?; + *bytes -= fresh; + if !add(bytes, retained) { + return fail("retained K/V allocation overflow"); + } + } + let directory = product(&[(reuse.kv.capacity() - layers) as u64, size_of::() as u64]) + .ok_or_else(|| ConvError("conversation snapshot: retained K/V directory overflow".into()))?; + if !add(bytes, directory) { + return fail("retained K/V directory overflow"); + } + Ok(()) +} + /// `conversation_snapshot_capture_bytes`: the capture estimate including /// retained capacity and transient segment directories. Only the estimate /// minus `reuse.bytes()` requires additional physical RAM. @@ -144,37 +194,67 @@ pub fn snapshot_capture_bytes( if reuse.kv.is_empty() { return Ok(bytes); } - let layers = ss.owned_qsa() + 1; - if reuse.kv.len() != layers - || reuse.unchanged_tokens < 0 - || reuse.unchanged_tokens > reuse.captured_tokens - || reuse.unchanged_tokens > view.ids.len() as i64 - { + if !reuse_is_valid(reuse, view, ss.owned_qsa() + 1) { return fail("invalid retained K/V prefix"); } - for (i, image) in reuse.kv.iter().enumerate() { - let index = i + 1 != layers; - let st = layer_state(ss, draft, i)?; - kv_validate(image, st, g, reuse.captured_tokens, index)?; - let fresh = kv_bytes(st, g, view.ids.len() as i64, index); - let retained = kv_capture_bytes(image, st, g, view.ids.len() as i64, index)?; - bytes -= fresh; - if !add(&mut bytes, retained) { - return fail("retained K/V allocation overflow"); - } - } - let directory = product(&[(reuse.kv.capacity() - layers) as u64, size_of::() as u64]) - .ok_or_else(|| ConvError("conversation snapshot: retained K/V directory overflow".into()))?; - if !add(&mut bytes, directory) { - return fail("retained K/V directory overflow"); - } + retained_adjust(&mut bytes, reuse, view, (ss, g, draft))?; Ok(bytes) } -fn synchronize(mem: &mut dyn StateMemory) -> ConvResult<()> { +fn synchronize(mem: &mut (impl StateMemory + ?Sized)) -> ConvResult<()> { mem.synchronize().map_err(|message| ConvError(format!("conversation snapshot synchronize: {message}"))) } +/// The image to capture into: the view's identity, the retained K/V storage (or none) with room for every layer, and +/// the number of leading tokens of it that are unchanged. +fn begin_capture( + view: &ConversationView<'_>, + ss: &SessionSpec, + g: &ModelGeometry, + reuse: ConversationKvReuse, +) -> ConvResult<(SavedConversation, i64)> { + let mut captured = SavedConversation { + geometry: g.key(), + layer_lo: ss.shape.layer_lo, + layer_hi: ss.shape.layer_hi, + cvec: view.cvec, + ..SavedConversation::default() + }; + captured.live.ids = view.ids.to_vec(); + captured.live.imgs = view.images.to_vec(); + captured.checkpoints = view.checkpoints.to_vec(); + let unchanged = if reuse.kv.is_empty() { 0 } else { reuse.unchanged_tokens }; + captured.kv = reuse.kv; + let layers = ss.owned_qsa(); + let missing = (layers + 1).saturating_sub(captured.kv.len()); + captured.kv.try_reserve_exact(missing).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; + captured.kv.resize_with(layers + 1, ConversationKv::default); + Ok((captured, unchanged)) +} + +/// Capture the K/V of every layer, then the draft's; returns the bytes the retained storage let it skip. +fn capture_kv( + captured: &mut SavedConversation, + view: &ConversationView<'_>, + (ss, g, draft): (&SessionSpec, &ModelGeometry, &QsaDesc), + mem: &mut dyn StateMemory, + unchanged: i64, +) -> ConvResult { + let layers = ss.owned_qsa(); + let upto = view.ids.len() as i64; + let mut reused = 0usize; + for j in 0..layers { + let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; + kv_save(&mut captured.kv[j], KvLayer::Main(j), st, g, upto, true, unchanged, mem, Some(&mut reused))?; + } + // The draft's final cell may not have been computed when the output cap was + // reached. Refresh that page even when the main prefix continued unchanged. + let draft_unchanged = (unchanged - 1).max(0); + let draft_kv = &mut captured.kv[layers]; + kv_save(draft_kv, KvLayer::Draft, draft, g, upto, false, draft_unchanged, mem, Some(&mut reused))?; + Ok(reused) +} + /// `conversation_snapshot_save`: capture the live session into a new image. /// Builds into a new object so a failure cannot publish a partial snapshot. /// `reuse` is consumed, including on failure. The caller admits the estimate @@ -191,56 +271,17 @@ pub fn snapshot_save( ) -> ConvResult { snapshot_capture_bytes(&reuse, view, ss, g, draft)?; synchronize(mem)?; - let mut captured = SavedConversation { - geometry: g.key(), - layer_lo: ss.shape.layer_lo, - layer_hi: ss.shape.layer_hi, - cvec: view.cvec, - ..SavedConversation::default() - }; - captured.live.ids = view.ids.to_vec(); - captured.live.imgs = view.images.to_vec(); - captured.checkpoints = view.checkpoints.to_vec(); - let unchanged = if reuse.kv.is_empty() { 0 } else { reuse.unchanged_tokens }; - captured.kv = reuse.kv; - let layers = ss.owned_qsa(); - let missing = (layers + 1).saturating_sub(captured.kv.len()); - captured.kv.try_reserve_exact(missing).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; - captured.kv.resize_with(layers + 1, ConversationKv::default); + let (mut captured, unchanged) = begin_capture(view, ss, g, reuse)?; checkpoint_save(&mut captured.live, ss, g, mem)?; - let upto = view.ids.len() as i64; - let mut reused = 0usize; - for j in 0..layers { - let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; - kv_save(&mut captured.kv[j], KvLayer::Main(j), st, g, upto, true, unchanged, mem, Some(&mut reused))?; - } - // The draft's final cell may not have been computed when the output cap was - // reached. Refresh that page even when the main prefix continued unchanged. - kv_save( - &mut captured.kv[layers], - KvLayer::Draft, - draft, - g, - upto, - false, - (unchanged - 1).max(0), - mem, - Some(&mut reused), - )?; + let reused = capture_kv(&mut captured, view, (ss, g, draft), mem, unchanged)?; if let Some(total) = reused_bytes { *total += reused; } Ok(captured) } -/// Structural validation of a whole image against the target session. No -/// device access. -pub fn snapshot_validate( - image: &SavedConversation, - ss: &SessionSpec, - g: &ModelGeometry, - draft: &QsaDesc, -) -> ConvResult<()> { +/// The image belongs to this runtime: no layer-split parking, the same geometry and the same carve of layers. +fn check_image_header(image: &SavedConversation, ss: &SessionSpec, g: &ModelGeometry) -> ConvResult<()> { if !image.live.stage_parts.is_empty() { return fail("layer-split parking is not supported"); } @@ -251,6 +292,18 @@ pub fn snapshot_validate( if image.layer_lo != ss.shape.layer_lo || image.layer_hi != ss.shape.layer_hi { return fail("snapshot from another session layer range"); } + Ok(()) +} + +/// Structural validation of a whole image against the target session. No +/// device access. +pub fn snapshot_validate( + image: &SavedConversation, + ss: &SessionSpec, + g: &ModelGeometry, + draft: &QsaDesc, +) -> ConvResult<()> { + check_image_header(image, ss, g)?; let view = ConversationView { ids: &image.live.ids, images: &image.live.imgs, @@ -271,7 +324,7 @@ pub fn snapshot_validate( kv_validate(&image.kv[layers], draft, g, upto, false) } -/// Restore a whole image. Invalid images are rejected before any device +// Restore a whole image. Invalid images are rejected before any device /// write; a transfer failure may leave partial state. pub fn snapshot_restore( image: &SavedConversation, diff --git a/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs index f0cb2f4a..b0040601 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn golden_state, fn fnv, fn fnv_buf, fn assert_kv, fn assert_checkpoint, fn assert_image. +//! Moved out of the parent module by STRA-338: fn golden_state, fn fnv, fn fnv_buf, fn assert_kv, fn assert_checkpoint, +//! fn assert_image. #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs b/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs index 7671460e..3f006728 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs @@ -3,6 +3,27 @@ #[allow(unused_imports)] use super::*; +/// The buffers a state of `format` (0 fp16, 1 INT8, 2 Q4_0) has, and the indexer's. +fn mark_present(st: &mut QsaDesc, format: i32) { + if format == 2 { + st.k_q4 = true; + st.v_q4 = true; + } else if format == 1 { + st.k_q = true; + st.v_q = true; + st.k_scale = true; + st.v_scale = true; + } else { + st.k_pool = true; + st.v_pool = true; + } + st.idx_pooled = true; + st.idx_tail = true; + st.idx_dead = true; + st.idx_block_pos = true; + st.page_table = true; +} + impl Pools { pub(super) fn new(g: &ModelGeometry, format: i32) -> Self { let mut st = QsaDesc { @@ -23,23 +44,7 @@ impl Pools { data.push(vec![0xa5; 3 * g.idx_key_dim as usize * 4]); data.push(vec![0xa5; g.idx_key_dim as usize * 4]); data.push(vec![0xa5; 4]); - if format == 2 { - st.k_q4 = true; - st.v_q4 = true; - } else if format == 1 { - st.k_q = true; - st.v_q = true; - st.k_scale = true; - st.v_scale = true; - } else { - st.k_pool = true; - st.v_pool = true; - } - st.idx_pooled = true; - st.idx_tail = true; - st.idx_dead = true; - st.idx_block_pos = true; - st.page_table = true; + mark_present(&mut st, format); Self { st, data } } diff --git a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs index 39b34537..204aab90 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs @@ -1,4 +1,7 @@ -//! Tests of snapshot_tests by topic (moved out of the test file by STRA-338): layer_snapshots_are_byte_exact_across_formats_and_residency_modes, whole_session_snapshots_round_trip_exactly, validation_rejects_before_any_device_write_and_faults_are_fatal, checkpoint_save_restore_round_trips_through_host_memory .... +//! Tests of snapshot_tests by topic (moved out of the test file by STRA-338): +//! layer_snapshots_are_byte_exact_across_formats_and_residency_modes, whole_session_snapshots_round_trip_exactly, +//! validation_rejects_before_any_device_write_and_faults_are_fatal, +//! checkpoint_save_restore_round_trips_through_host_memory .... #[allow(unused_imports)] use super::*; @@ -146,6 +149,11 @@ fn golden_geometry_and_carve_sizes_match_the_original() { } } +/// The `(format, mode, rotation)` a golden K/V case runs under. +fn kv_case_key(case: &serde_json::Value) -> (i32, i32, i64) { + (case["fmt"].as_i64().unwrap() as i32, case["mode"].as_i64().unwrap() as i32, case["rot"].as_i64().unwrap()) +} + #[test] fn golden_layer_layouts_and_payload_hashes_match_the_original() { let golden = golden_state(); @@ -153,11 +161,7 @@ fn golden_layer_layouts_and_payload_hashes_match_the_original() { assert!(cases.len() > 200); let mut cached: Option<(i32, i32, i64, HostMemory, Fixture)> = None; for case in cases { - let (fmt, mode, rot) = ( - case["fmt"].as_i64().unwrap() as i32, - case["mode"].as_i64().unwrap() as i32, - case["rot"].as_i64().unwrap(), - ); + let (fmt, mode, rot) = kv_case_key(case); let upto = case["upto"].as_i64().unwrap(); if cached.as_ref().is_none_or(|c| (c.0, c.1, c.2) != (fmt, mode, rot)) { let mut mem = HostMemory::new(); diff --git a/crates/engine-core/src/conversation/state.rs b/crates/engine-core/src/conversation/state.rs index d4d22a28..771eb9eb 100644 --- a/crates/engine-core/src/conversation/state.rs +++ b/crates/engine-core/src/conversation/state.rs @@ -8,8 +8,8 @@ use super::cache::{ConversationCheckpoint, ConversationImageKey}; use super::checked::{add, product}; use super::model::{ - ConvError, ConvResult, IDX_BLOCK, IdxKind, KvLayer, KvPool, ModelGeometry, NG_HC_DIM, NG_HIST, SessionSpec, - StateMemory, StateRegion, fail, + ConvError, ConvResult, IDX_BLOCK, IdxKind, KvLayer, KvPool, ModelGeometry, NG_HC_DIM, NG_HIST, QsaDesc, + SessionSpec, StateMemory, StateRegion, fail, }; /// Byte sizes of one session's running state (`ConversationStateSizes`). @@ -22,32 +22,36 @@ pub struct StateSizes { pub block_pos: usize, } +//// The model geometry key is non-negative, and every entry but the second (the draft position) is non-zero. +fn geometry_valid(key: &[i64]) -> bool { + key.iter().enumerate().all(|(i, &value)| !(value < 0 || (i != 1 && value == 0))) +} + +/// Bytes of the GDN state of the whole model: the recurrence and the convolution history of every GDN layer. +fn gdn_bytes(g: &ModelGeometry) -> Option { + let mut recurrence = product(&[g.ssm_state_size as u64, g.ssm_v_heads as u64, g.ssm_state_size as u64])?; + let convolution = product(&[g.ssm_conv_channels as u64, (g.ssm_d_conv - 1) as u64])?; + if !add(&mut recurrence, convolution) { + return None; + } + product(&[g.n_gdn_layers() as u64, recurrence as u64, 4]) +} + /// Whole-model sizes: `gdn` covers every GDN layer, the indexer sizes are per /// QSA layer. pub fn state_sizes(g: &ModelGeometry) -> ConvResult { - let key = g.key(); - for (i, &value) in key.iter().enumerate() { - if value < 0 || (i != 1 && value == 0) { - return fail("invalid model geometry"); - } + if !geometry_valid(&g.key()) { + return fail("invalid model geometry"); } let overflow = || ConvError("conversation snapshot: running-state byte count overflow".into()); - let recurrence = - product(&[g.ssm_state_size as u64, g.ssm_v_heads as u64, g.ssm_state_size as u64]).ok_or_else(overflow)?; - let convolution = product(&[g.ssm_conv_channels as u64, (g.ssm_d_conv - 1) as u64]).ok_or_else(overflow)?; - let mut recurrence = recurrence; - if !add(&mut recurrence, convolution) { - return Err(overflow()); - } - let gdn = product(&[g.n_gdn_layers() as u64, recurrence as u64, 4]).ok_or_else(overflow)?; + let gdn = gdn_bytes(g).ok_or_else(overflow)?; let ple = product(&[NG_HIST, NG_HC_DIM, 4]).ok_or_else(overflow)?; let tail = product(&[(IDX_BLOCK - 1) as u64, g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; let dead = product(&[g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; let z = StateSizes { gdn, ple, tail, dead, block_pos: 4 }; - for part in [z.tail, z.dead, z.block_pos] { - if product(&[g.n_qsa_layers() as u64, part as u64]).is_none() { - return fail("indexer byte count overflow"); - } + if [z.tail, z.dead, z.block_pos].into_iter().any(|part| product(&[g.n_qsa_layers() as u64, part as u64]).is_none()) + { + return fail("indexer byte count overflow"); } Ok(z) } @@ -86,33 +90,40 @@ pub fn image_keys(images: &[ConversationImageKey], tokens: usize) -> bool { true } +/// The session can hold `tokens` and has its GDN state and its QSA states where the sizes say they are. +fn session_targets_ok(z: &StateSizes, ss: &SessionSpec, tokens: usize) -> bool { + let s = &ss.shape; + !(s.max_cells < 0 + || tokens as u64 > s.max_cells as u64 + || (z.gdn != 0 && !s.has_gdn_state) + || (ss.owned_qsa() != 0 && ss.qsa.is_empty())) +} + +/// One owned QSA state has every indexer buffer a checkpoint reads or writes, and room for `tokens`. +fn indexer_target_ok(st: &QsaDesc, g: &ModelGeometry, tokens: usize) -> bool { + let block = IDX_BLOCK as u64; + let pooled_bytes = product(&[tokens as u64 / block + 1, g.idx_key_dim as u64, 4]); + st.idx_tail + && st.idx_dead + && st.idx_block_pos + && st.idx_pooled + && st.max_cells >= 0 + && tokens as u64 <= st.max_cells as u64 + && !(tokens != 0 && tokens as u64 / block >= st.idx_pooled_rows.max(0) as u64) + && pooled_bytes.is_some() +} + /// `checkpoint_targets`: the session can hold `tokens` and owns every buffer a /// checkpoint reads or writes. pub fn checkpoint_targets(ss: &SessionSpec, g: &ModelGeometry, tokens: usize) -> ConvResult { let z = session_sizes(g, ss)?; - let s = &ss.shape; - let invalid = || ConvError("conversation snapshot: invalid session running-state targets".into()); - if s.max_cells < 0 - || tokens as u64 > s.max_cells as u64 - || (z.gdn != 0 && !s.has_gdn_state) - || (ss.owned_qsa() != 0 && ss.qsa.is_empty()) - { - return Err(invalid()); + if !session_targets_ok(&z, ss, tokens) { + return Err(ConvError("conversation snapshot: invalid session running-state targets".into())); } for j in 0..ss.owned_qsa() { let bad = || ConvError("conversation snapshot: invalid indexer running-state target".into()); let st = ss.owned(j).ok_or_else(bad)?; - let block = IDX_BLOCK as u64; - let pooled_bytes = product(&[tokens as u64 / block + 1, g.idx_key_dim as u64, 4]); - if !st.idx_tail - || !st.idx_dead - || !st.idx_block_pos - || !st.idx_pooled - || st.max_cells < 0 - || tokens as u64 > st.max_cells as u64 - || (tokens != 0 && tokens as u64 / block >= st.idx_pooled_rows.max(0) as u64) - || pooled_bytes.is_none() - { + if !indexer_target_ok(st, g, tokens) { return Err(bad()); } } @@ -150,20 +161,31 @@ pub fn checkpoint_validate(c: &ConversationCheckpoint, ss: &SessionSpec, g: &Mod Ok(()) } -fn read_into(mem: &mut dyn StateMemory, region: StateRegion, dst: &mut [u8]) -> ConvResult<()> { +fn read_into(mem: &mut (impl StateMemory + ?Sized), region: StateRegion, dst: &mut [u8]) -> ConvResult<()> { if dst.is_empty() { return Ok(()); } mem.read(region, 0, dst).map_err(copy_error) } -fn write_from(mem: &mut dyn StateMemory, region: StateRegion, offset: usize, src: &[u8]) -> ConvResult<()> { +fn write_from(mem: &mut (impl StateMemory + ?Sized), region: StateRegion, offset: usize, src: &[u8]) -> ConvResult<()> { if src.is_empty() { return Ok(()); } mem.write(region, offset, src).map_err(copy_error) } +//// Allocate the payloads of a checkpoint of `ss` at the sizes `z`. +fn alloc_payloads(c: &mut ConversationCheckpoint, ss: &SessionSpec, z: &StateSizes) -> ConvResult<()> { + let layers = ss.owned_qsa(); + c.gdn = exact_zeroed(z.gdn)?; + c.ple = exact_zeroed(if ss.shape.has_ple_hist { z.ple } else { 0 })?; + c.tails = exact_zeroed(layers * z.tail)?; + c.dead = exact_zeroed(layers * z.dead)?; + c.block_pos = exact_zeroed(layers * z.block_pos)?; + Ok(()) +} + /// Capture the running state at `c.ids.len()` tokens into `c`'s payloads. /// The caller synchronises the device first. pub fn checkpoint_save( @@ -173,16 +195,10 @@ pub fn checkpoint_save( mem: &mut dyn StateMemory, ) -> ConvResult<()> { let z = checkpoint_targets(ss, g, c.ids.len())?; - let layers = ss.owned_qsa(); - let (tails, dead, block_pos) = (layers * z.tail, layers * z.dead, layers * z.block_pos); - c.gdn = exact_zeroed(z.gdn)?; - c.ple = exact_zeroed(if ss.shape.has_ple_hist { z.ple } else { 0 })?; - c.tails = exact_zeroed(tails)?; - c.dead = exact_zeroed(dead)?; - c.block_pos = exact_zeroed(block_pos)?; + alloc_payloads(c, ss, &z)?; read_into(mem, StateRegion::Gdn, &mut c.gdn)?; read_into(mem, StateRegion::PleHist, &mut c.ple)?; - for j in 0..layers { + for j in 0..ss.owned_qsa() { let idx = |kind| StateRegion::Idx { layer: j, kind }; read_into(mem, idx(IdxKind::Tail), &mut c.tails[j * z.tail..(j + 1) * z.tail])?; read_into(mem, idx(IdxKind::Dead), &mut c.dead[j * z.dead..(j + 1) * z.dead])?; @@ -191,6 +207,26 @@ pub fn checkpoint_save( Ok(()) } +/// Restore the indexer state of QSA layer `j`; the spare (moving) pooled row is reconstructed from the dead key. +fn restore_indexer( + c: &ConversationCheckpoint, + j: usize, + (z, g): (&StateSizes, &ModelGeometry), + mem: &mut dyn StateMemory, +) -> ConvResult<()> { + let idx = |kind| StateRegion::Idx { layer: j, kind }; + let dead = &c.dead[j * z.dead..(j + 1) * z.dead]; + write_from(mem, idx(IdxKind::Tail), 0, &c.tails[j * z.tail..(j + 1) * z.tail])?; + write_from(mem, idx(IdxKind::Dead), 0, dead)?; + write_from(mem, idx(IdxKind::BlockPos), 0, &c.block_pos[j * z.block_pos..(j + 1) * z.block_pos])?; + if !c.ids.is_empty() { + let row = c.ids.len() / IDX_BLOCK as usize; + let region = StateRegion::Kv { layer: KvLayer::Main(j), pool: KvPool::Pooled, resident: false }; + write_from(mem, region, row * g.idx_key_dim as usize * 4, dead)?; + } + Ok(()) +} + /// Restore a validated checkpoint; invalid input writes nothing. pub fn checkpoint_restore( c: &ConversationCheckpoint, @@ -203,16 +239,7 @@ pub fn checkpoint_restore( write_from(mem, StateRegion::Gdn, 0, &c.gdn)?; write_from(mem, StateRegion::PleHist, 0, &c.ple)?; for j in 0..ss.owned_qsa() { - let idx = |kind| StateRegion::Idx { layer: j, kind }; - write_from(mem, idx(IdxKind::Tail), 0, &c.tails[j * z.tail..(j + 1) * z.tail])?; - write_from(mem, idx(IdxKind::Dead), 0, &c.dead[j * z.dead..(j + 1) * z.dead])?; - write_from(mem, idx(IdxKind::BlockPos), 0, &c.block_pos[j * z.block_pos..(j + 1) * z.block_pos])?; - if !c.ids.is_empty() { - // The spare (moving) pooled row is reconstructed from the dead key. - let row = c.ids.len() / IDX_BLOCK as usize; - let region = StateRegion::Kv { layer: KvLayer::Main(j), pool: KvPool::Pooled, resident: false }; - write_from(mem, region, row * g.idx_key_dim as usize * 4, &c.dead[j * z.dead..(j + 1) * z.dead])?; - } + restore_indexer(c, j, (&z, g), mem)?; } let tokens = c.ids.len(); mem.set_ple_prev([ diff --git a/crates/engine-core/src/conversation/testing.rs b/crates/engine-core/src/conversation/testing.rs index 26d031fd..d9ec2574 100644 --- a/crates/engine-core/src/conversation/testing.rs +++ b/crates/engine-core/src/conversation/testing.rs @@ -68,6 +68,28 @@ impl HostMemory { } } +impl HostMemory { + /// Copy the pages `begin..end` of the host pool into their slots of the resident ring. + fn restore_ring_pool(&mut self, layer: KvLayer, pool: super::model::KvPool, pages: usize, blocks: (i64, i64, i64)) { + let (begin_block, end_block, n_slots) = blocks; + let host = StateRegion::Kv { layer, pool, resident: false }; + let slots = StateRegion::Kv { layer, pool, resident: true }; + let Some(source) = self.regions.get(&host).cloned() else { + return; + }; + if source.is_empty() || !self.regions.contains_key(&slots) { + return; + } + let page_bytes = source.len() / pages; + let target = self.regions.get_mut(&slots).expect("checked above"); + for block in begin_block..end_block { + let from = block as usize * page_bytes; + let to = (block % n_slots) as usize * page_bytes; + target[to..to + page_bytes].copy_from_slice(&source[from..from + page_bytes]); + } + } +} + impl StateMemory for HostMemory { fn synchronize(&mut self) -> Result<(), String> { self.sync_calls += 1; @@ -114,21 +136,7 @@ impl StateMemory for HostMemory { super::model::KvPool::KScale, super::model::KvPool::VScale, ] { - let host = StateRegion::Kv { layer, pool, resident: false }; - let slots = StateRegion::Kv { layer, pool, resident: true }; - let Some(source) = self.regions.get(&host).cloned() else { - continue; - }; - if source.is_empty() || !self.regions.contains_key(&slots) { - continue; - } - let page_bytes = source.len() / pages; - let target = self.regions.get_mut(&slots).expect("checked above"); - for block in begin_block..end_block { - let from = block as usize * page_bytes; - let to = (block % n_slots) as usize * page_bytes; - target[to..to + page_bytes].copy_from_slice(&source[from..from + page_bytes]); - } + self.restore_ring_pool(layer, pool, pages, (begin_block, end_block, n_slots)); } Ok(()) } diff --git a/crates/engine-core/src/family.rs b/crates/engine-core/src/family.rs index c150ee98..5f3a77ff 100644 --- a/crates/engine-core/src/family.rs +++ b/crates/engine-core/src/family.rs @@ -1,7 +1,7 @@ -//! The engine family seam: what the composition root needs to start an engine, whatever model family and device sit behind -//! it. A family is a zero-sized marker that knows its start-up configuration and how to turn it into a running -//! [`Backend`]; the composition root is generic over it (`spawn::`), so the choice of family is one `match` and every -//! family below it is monomorphised, with no trait object between the root and the family's own code. +//! The engine family seam: what the composition root needs to start an engine, whatever model family and device sit +//! behind it. A family is a zero-sized marker that knows its start-up configuration and how to turn it into a running +//! [`Backend`]; the composition root is generic over it (`spawn::`), so the choice of family is one `match` and +//! every family below it is monomorphised, with no trait object between the root and the family's own code. //! //! Adapters: `leleka_runtime::backend::Qwen35Cuda` (the product engine) and `leleka-engine-fake` (a scripted engine for //! GPU-free tests). diff --git a/crates/engine-core/src/prefix_cache/budget.rs b/crates/engine-core/src/prefix_cache/budget.rs index 01fe45e4..8c2a5adc 100644 --- a/crates/engine-core/src/prefix_cache/budget.rs +++ b/crates/engine-core/src/prefix_cache/budget.rs @@ -26,8 +26,8 @@ pub struct AutoBudget { impl AutoBudget { /// The server profile: keep 4 GiB available, take 75% of the rest, never more than 96 GiB. (On the 5090 server the - /// sealed KAR memfd, the resident expert source and the pinned K/V leave only ~14 GiB available when the stack opens, - /// so a generous floor would switch the cache off exactly where it is wanted.) + /// sealed KAR memfd, the resident expert source and the pinned K/V leave only ~14 GiB available when the stack + /// opens, so a generous floor would switch the cache off exactly where it is wanted.) pub const fn server(mem_available: Option) -> Self { Self { mem_available, floor: 4 * GIB, percent: 75, cap: 96 * GIB, min_useful: GIB } } diff --git a/crates/engine-core/src/prefix_cache/store.rs b/crates/engine-core/src/prefix_cache/store.rs index 4b1c5800..50f5ff0b 100644 --- a/crates/engine-core/src/prefix_cache/store.rs +++ b/crates/engine-core/src/prefix_cache/store.rs @@ -95,8 +95,9 @@ struct Tail { } struct Node { - /// Chain values of blocks `0..k`. For a grid node the last one is the node's key; a TAIL node (a checkpoint at the end of a - /// request, between two grid points) has the key `chain_step(path[k - 1], tail tokens)` and covers `k` blocks plus its tail. + /// Chain values of blocks `0..k`. For a grid node the last one is the node's key; a TAIL node (a checkpoint at the + /// end of a request, between two grid points) has the key `chain_step(path[k - 1], tail tokens)` and covers `k` + /// blocks plus its tail. path: Box<[u64]>, tail: Option>, payload: N, @@ -170,7 +171,8 @@ pub struct PrefixStore { /// Tail nodes by the chain value of the last full block they extend. tails: HashMap>, clock: u64, - /// Wall time in milliseconds as of the last `tick_at` / `set_now`; supplied by the caller so the policy is deterministic. + /// Wall time in milliseconds as of the last `tick_at` / `set_now`; supplied by the caller so the policy is + /// deterministic. now_ms: u64, node_bytes: usize, block_bytes: usize, diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore.rs index 49c19d72..12f361b9 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore.rs @@ -3,6 +3,8 @@ #[allow(unused_imports)] use super::*; +mod admit; mod impl_prefixstore_2; mod impl_prefixstore_2_2; mod impl_prefixstore_3; +mod scoring; diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs new file mode 100644 index 00000000..28a2543d --- /dev/null +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/admit.rs @@ -0,0 +1,199 @@ +//! Admission to the store: `consider` decides whether a node is worth its bytes (making room if so), `insert` puts +//! an admitted candidate in. + +#[allow(unused_imports)] +use super::*; + +impl PrefixStore { + /// Note a rejection and report it. + fn reject(&mut self, why: Reject) -> Consider { + self.stats.rejected += 1; + Consider::Rejected(why) + } + + /// The chain of `tokens`: the hash of every block, the blocks the store does not have yet, and the last hash. + /// A block that is there with other tokens is a hash collision. + fn walk_chain(&self, tokens: &[i32]) -> Result<(Vec, Vec, u64), Reject> { + let g = self.cfg.block_tokens; + let mut path = Vec::with_capacity(tokens.len() / g); + let mut missing = Vec::new(); + let mut prev = CHAIN_SEED; + for (j, block) in tokens.chunks_exact(g).enumerate() { + let h = chain_step(prev, block); + match self.blocks.get(&h) { + Some(b) if *b.tokens != *block => return Err(Reject::Collision), + Some(_) => {} + None => missing.push(j), + } + path.push(h); + prev = h; + } + Ok((path, missing, prev)) + } + + /// The node is already cached: it just counts as used. + fn touch_existing(&mut self, key: u64) -> bool { + let Some(node) = self.nodes.get_mut(&key) else { + return false; + }; + node.touched = self.clock; + node.last_used_ms = self.now_ms; + self.stats.already_cached += 1; + true + } + + /// The cheapest node to give up, by value per byte freed (the key breaks a tie). + fn cheapest_victim(&self, removed: &HashSet, protect: &HashSet) -> Option { + self.scores(removed, protect).into_iter().min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))) + } + + /// The victims to evict so that `need` bytes (and a node slot) fit: take victims while the sacrifice stays + /// smaller than the candidate's worth. `Err`: there is nothing left to take, or it is not worth it. + fn select_victims( + &self, + need: usize, + (path, tail_len, frontier): (&[u64], usize, bool), + protect: &HashSet, + ) -> Result, Reject> { + let mut removed: Vec = Vec::new(); + let mut removed_set: HashSet = HashSet::new(); + let (mut freed_total, mut lost) = (0usize, 0.0f64); + let mut need_slot = self.nodes.len() >= self.cfg.max_nodes; + let free = self.cfg.budget_bytes.saturating_sub(self.bytes()); + while need > free + freed_total || need_slot { + let victim = self.cheapest_victim(&removed_set, protect).ok_or(Reject::NoRoom)?; + // What the candidate would be worth once this victim is gone (a victim that is its own ancestor raises its + // saving) against everything given up so far. + let mut after = removed_set.clone(); + after.insert(victim.key); + if lost + victim.value >= self.candidate_value(path, tail_len, frontier, &after) { + return Err(Reject::NotWorth); + } + lost += victim.value; + freed_total += victim.freed; + removed_set.insert(victim.key); + removed.push(victim.key); + need_slot = false; + } + Ok(removed) + } + + pub(in super::super) fn consider_at( + &mut self, + tokens: &[i32], + frontier: bool, + est_state: usize, + est_block: usize, + ) -> Consider { + let g = self.cfg.block_tokens; + let tail_len = tokens.len() % g; + self.release_orphans(); + let (path, missing, prev) = match self.walk_chain(tokens) { + Ok(walked) => walked, + Err(why) => return self.reject(why), + }; + let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) }; + if self.touch_existing(key) { + return Consider::Exists; + } + let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize; + if need > self.cfg.budget_bytes { + return self.reject(Reject::TooLarge); + } + let protect: HashSet = path.iter().copied().collect(); + let removed = match self.select_victims(need, (&path, tail_len, frontier), &protect) { + Ok(removed) => removed, + Err(why) => return self.reject(why), + }; + removed.into_iter().for_each(|victim| self.evict_keeping(victim, &protect)); + Consider::Admit(Candidate { key, path, tail_len, missing, frontier }) + } + + /// The candidate and the payloads handed over describe the same new node. + fn candidate_fits(&self, candidate: &Candidate, tokens: &[i32], blocks: &[(usize, B)]) -> bool { + let g = self.cfg.block_tokens; + tokens.len() == candidate.path.len() * g + candidate.tail_len + && blocks.len() == candidate.missing.len() + && blocks.iter().zip(&candidate.missing).all(|((j, _), m)| j == m) + && !candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) + && !self.nodes.contains_key(&candidate.key) + } + + /// Store the blocks the candidate was missing. + fn add_blocks(&mut self, candidate: &Candidate, tokens: &[i32], blocks: Vec<(usize, B)>) { + let g = self.cfg.block_tokens; + for (j, payload) in blocks { + let bytes = payload.byte_size(); + self.block_bytes += bytes; + self.blocks.insert( + candidate.path[j], + Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }, + ); + } + } + + /// The node takes a reference on every block of its path. + fn hold_path(&mut self, path: &[u64]) -> Result<(), Reject> { + for h in path { + self.orphans.remove(h); + match self.blocks.get_mut(h) { + Some(block) => block.refs += 1, + // a present block vanished between consider and commit: impossible while the caller is single-threaded + None => return Err(Reject::Mismatch), + } + } + Ok(()) + } + + /// Enter the node of the candidate (its blocks are already held). + fn add_node(&mut self, candidate: Candidate, tokens: &[i32], state: N, tail: Option) { + let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload }); + let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size()); + self.node_bytes += bytes; + if tail.is_some() { + self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key); + } + self.nodes.insert( + candidate.key, + Node { + path: candidate.path.into_boxed_slice(), + tail, + payload: state, + bytes, + touched: self.clock, + last_used_ms: self.now_ms, + hit_mass: 0.0, + hit_stamp: self.clock, + hits: 0, + shared_hits: 0, + frontier: candidate.frontier, + }, + ); + } + + pub(in super::super) fn insert( + &mut self, + candidate: Candidate, + tokens: &[i32], + state: N, + blocks: Vec<(usize, B)>, + tail: Option, + keep_end: Option, + ) -> Result<(), Reject> { + if !self.candidate_fits(&candidate, tokens, &blocks) { + return Err(Reject::Mismatch); + } + self.add_blocks(&candidate, tokens, blocks); + self.hold_path(&candidate.path)?; + let superseded = + if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() }; + let key = candidate.key; + self.add_node(candidate, tokens, state, tail); + self.stats.admitted += 1; + for old in superseded { + self.evict(old); + } + self.enforce_budget(key); + Ok(()) + } +} diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs index 3f274d69..518564e6 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs @@ -124,6 +124,30 @@ impl PrefixStore { Some(out) } + /// The deepest request-end checkpoint that extends the block `h` (ending at token `end`) and whose tokens are the + /// prompt's next ones, within `limit`; `best` when none reaches further. + fn best_tail( + &self, + h: u64, + (end, limit): (usize, usize), + tokens: &[i32], + mut best: Option, + ) -> Option { + for key in self.tails.get(&h).into_iter().flatten() { + let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { + continue; + }; + let upto = end + tail.tokens.len(); + if upto <= limit + && best.is_none_or(|b| upto > b.tokens) + && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) + { + best = Some(Match { key: *key, tokens: upto }); + } + } + best + } + /// The deepest node that is a prefix of `tokens` and covers at most `limit` tokens. The blocks are compared /// token for token, so a hash collision cannot produce a hit. pub fn longest_match(&self, tokens: &[i32], limit: usize) -> Option { @@ -136,29 +160,14 @@ impl PrefixStore { break; } let h = chain_step(prev, block); - match self.blocks.get(&h) { - Some(b) if *b.tokens == *block => {} - _ => break, + if !self.blocks.get(&h).is_some_and(|b| *b.tokens == *block) { + break; } prev = h; if self.nodes.contains_key(&h) { best = Some(Match { key: h, tokens: end }); } - // request-end checkpoints that extend this block (the longest whose tokens are the prompt's next ones) - if let Some(keys) = self.tails.get(&h) { - for key in keys { - let Some(tail) = self.nodes.get(key).and_then(|n| n.tail.as_ref()) else { - continue; - }; - let upto = end + tail.tokens.len(); - if upto <= limit - && best.is_none_or(|b| upto > b.tokens) - && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) - { - best = Some(Match { key: *key, tokens: upto }); - } - } - } + best = self.best_tail(h, (end, limit), tokens, best); } best } diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs index 863db5be..76e987b7 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs @@ -4,57 +4,6 @@ use super::*; impl PrefixStore { - /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is - /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. - /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). - pub(in super::super) fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { - let g = self.cfg.block_tokens; - let mut cover: HashMap = HashMap::new(); - for key in removed { - if let Some(node) = self.nodes.get(key) { - for h in node.path.iter() { - *cover.entry(*h).or_default() += 1; - } - } - } - let mut ancestor: HashMap = HashMap::with_capacity(self.nodes.len()); - let mut children: HashMap = HashMap::new(); - for (key, node) in &self.nodes { - if removed.contains(key) { - continue; - } - let mut depth = 0; - // a tail node's nearest ancestor may be the grid node at the end of its own path - let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 }; - for i in (0..upto).rev() { - let h = node.path[i]; - if self.nodes.contains_key(&h) && !removed.contains(&h) { - depth = (i + 1) * g; - *children.entry(h).or_default() += 1; - break; - } - } - ancestor.insert(*key, depth); - } - let mut out = Vec::with_capacity(ancestor.len()); - for (key, node) in &self.nodes { - let Some(&anc) = ancestor.get(key) else { - continue; - }; - let mut freed = node.bytes; - for h in node.path.iter() { - let block = &self.blocks[h]; - if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { - freed += block.bytes; - } - } - let marginal = (self.tokens_of(node) - anc) as f64; - let p = self.probability(node, children.get(key).copied().unwrap_or(0)); - out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); - } - out - } - /// Decide whether a node for `tokens` (a whole number of blocks) is worth its bytes, making room if so. /// `est_state` / `est_block`: the sizes the payloads are expected to have. Evictions made here are final even if /// the caller then fails to build the payloads. @@ -64,8 +13,8 @@ impl PrefixStore { self.consider_at(tokens, frontier, est_state, est_block) } - /// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a tail of - /// 1..block_tokens tokens. The tail's cells are charged as the same share of a block. + /// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a + /// tail of 1..block_tokens tokens. The tail's cells are charged as the same share of a block. pub fn consider_tail(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { let g = self.cfg.block_tokens; assert!( @@ -75,80 +24,6 @@ impl PrefixStore { self.consider_at(tokens, frontier, est_state, est_block) } - pub(in super::super) fn consider_at( - &mut self, - tokens: &[i32], - frontier: bool, - est_state: usize, - est_block: usize, - ) -> Consider { - let g = self.cfg.block_tokens; - let tail_len = tokens.len() % g; - self.release_orphans(); - let mut path = Vec::with_capacity(tokens.len() / g); - let mut missing = Vec::new(); - let mut prev = CHAIN_SEED; - for (j, block) in tokens.chunks_exact(g).enumerate() { - let h = chain_step(prev, block); - match self.blocks.get(&h) { - Some(b) if *b.tokens != *block => { - self.stats.rejected += 1; - return Consider::Rejected(Reject::Collision); - } - Some(_) => {} - None => missing.push(j), - } - path.push(h); - prev = h; - } - let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) }; - if let Some(node) = self.nodes.get_mut(&key) { - node.touched = self.clock; - node.last_used_ms = self.now_ms; - self.stats.already_cached += 1; - return Consider::Exists; - } - let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize; - if need > self.cfg.budget_bytes { - self.stats.rejected += 1; - return Consider::Rejected(Reject::TooLarge); - } - let protect: HashSet = path.iter().copied().collect(); - let mut removed: Vec = Vec::new(); - let mut removed_set: HashSet = HashSet::new(); - let mut freed_total = 0usize; - let mut lost = 0.0f64; - let mut need_slot = self.nodes.len() >= self.cfg.max_nodes; - let free = self.cfg.budget_bytes.saturating_sub(self.bytes()); - while need > free + freed_total || need_slot { - let victim = self - .scores(&removed_set, &protect) - .into_iter() - .min_by(|a, b| a.score.total_cmp(&b.score).then(a.key.cmp(&b.key))); - let Some(victim) = victim else { - self.stats.rejected += 1; - return Consider::Rejected(Reject::NoRoom); - }; - // What the candidate would be worth once this victim is gone (a victim that is its own ancestor raises its - // saving) against everything given up so far: take victims while the sacrifice stays smaller than the gain. - let mut after = removed_set.clone(); - after.insert(victim.key); - if lost + victim.value >= self.candidate_value(&path, tail_len, frontier, &after) { - self.stats.rejected += 1; - return Consider::Rejected(Reject::NotWorth); - } - lost += victim.value; - freed_total += victim.freed; - removed_set.insert(victim.key); - removed.push(victim.key); - need_slot = false; - } - for key in removed { - self.evict_keeping(key, &protect); - } - Consider::Admit(Candidate { key, path, tail_len, missing, frontier }) - } - /// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor). pub(in super::super) fn candidate_value( &self, @@ -184,8 +59,9 @@ impl PrefixStore { self.insert(candidate, tokens, state, blocks, None, None) } - /// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same history that - /// end earlier (a token-wise prefix of this one) are superseded: the next request of the session starts from this one. + /// `commit` of a tail node: `tail` holds the cells of the tokens after the last full block. Tail nodes of the same + /// history that end earlier (a token-wise prefix of this one) are superseded: the next request of the session + /// starts from this one. pub fn commit_tail( &mut self, candidate: Candidate, @@ -197,9 +73,10 @@ impl PrefixStore { self.commit_tail_keeping(candidate, tokens, state, blocks, tail, None) } - /// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a request extends - /// the same request's prompt-end checkpoint; when the client resends the history without the reply's reasoning, the next prompt - /// shares only the prompt part, so the prompt-end node must survive (the next request's own tails supersede it as usual). + /// `commit_tail` that leaves the tail node ending at `keep_end` tokens standing. The decode-end checkpoint of a + /// request extends the same request's prompt-end checkpoint; when the client resends the history without the + /// reply's reasoning, the next prompt shares only the prompt part, so the prompt-end node must survive (the next + /// request's own tails supersede it as usual). pub fn commit_tail_keeping( &mut self, candidate: Candidate, @@ -215,72 +92,6 @@ impl PrefixStore { self.insert(candidate, tokens, state, blocks, Some(tail), keep_end) } - pub(in super::super) fn insert( - &mut self, - candidate: Candidate, - tokens: &[i32], - state: N, - blocks: Vec<(usize, B)>, - tail: Option, - keep_end: Option, - ) -> Result<(), Reject> { - let g = self.cfg.block_tokens; - if tokens.len() != candidate.path.len() * g + candidate.tail_len - || blocks.len() != candidate.missing.len() - || blocks.iter().zip(&candidate.missing).any(|((j, _), m)| j != m) - || candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) - || self.nodes.contains_key(&candidate.key) - { - return Err(Reject::Mismatch); - } - for (j, payload) in blocks { - let bytes = payload.byte_size(); - self.block_bytes += bytes; - self.blocks.insert( - candidate.path[j], - Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }, - ); - } - for h in &candidate.path { - self.orphans.remove(h); - match self.blocks.get_mut(h) { - Some(block) => block.refs += 1, - // a present block vanished between consider and commit: impossible while the caller is single-threaded - None => return Err(Reject::Mismatch), - } - } - let superseded = - if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() }; - let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload }); - let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size()); - self.node_bytes += bytes; - if tail.is_some() { - self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key); - } - self.nodes.insert( - candidate.key, - Node { - path: candidate.path.into_boxed_slice(), - tail, - payload: state, - bytes, - touched: self.clock, - last_used_ms: self.now_ms, - hit_mass: 0.0, - hit_stamp: self.clock, - hits: 0, - shared_hits: 0, - frontier: candidate.frontier, - }, - ); - self.stats.admitted += 1; - for old in superseded { - self.evict(old); - } - self.enforce_budget(candidate.key); - Ok(()) - } - /// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues). pub(in super::super) fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option) -> Vec { let g = self.cfg.block_tokens; diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs index c013ce2f..816b45ab 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs @@ -39,6 +39,33 @@ impl PrefixStore { self.evict_keeping(key, &HashSet::new()); } + /// Take the tail node `key` out of the list of its parent block. + fn unlink_tail(&mut self, node: &Node, key: u64) { + let Some(parent) = node.path.last() else { return }; + let Some(list) = self.tails.get_mut(parent) else { return }; + list.retain(|k| *k != key); + if list.is_empty() { + self.tails.remove(parent); + } + } + + /// The node gives up its reference on block `h`; the block goes with the last one, unless it is in `keep` (then + /// it stays as an orphan). + fn release_block(&mut self, h: u64, keep: &HashSet) { + let gone = match self.blocks.get_mut(&h) { + Some(block) => { + block.refs -= 1; + block.refs == 0 + } + None => false, + }; + if gone && keep.contains(&h) { + self.orphans.insert(h); + } else if gone && let Some(block) = self.blocks.remove(&h) { + self.block_bytes -= block.bytes; + } + } + /// `evict`, except that blocks in `keep` stay (as orphans) when this was their last node. pub(in super::super) fn evict_keeping(&mut self, key: u64, keep: &HashSet) { let Some(node) = self.nodes.remove(&key) else { @@ -47,30 +74,10 @@ impl PrefixStore { self.node_bytes -= node.bytes; self.stats.evicted += 1; if node.tail.is_some() { - if let Some(parent) = node.path.last() { - if let Some(list) = self.tails.get_mut(parent) { - list.retain(|k| *k != key); - if list.is_empty() { - self.tails.remove(parent); - } - } - } + self.unlink_tail(&node, key); } for h in node.path.iter() { - let gone = match self.blocks.get_mut(h) { - Some(block) => { - block.refs -= 1; - block.refs == 0 - } - None => false, - }; - if gone && keep.contains(h) { - self.orphans.insert(*h); - } else if gone { - if let Some(block) = self.blocks.remove(h) { - self.block_bytes -= block.bytes; - } - } + self.release_block(*h, keep); } } diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/scoring.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/scoring.rs new file mode 100644 index 00000000..95afa24b --- /dev/null +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/scoring.rs @@ -0,0 +1,81 @@ +//! The value of every node of the store: the tokens an eviction would cost per byte it frees. + +#[allow(unused_imports)] +use super::*; + +impl PrefixStore { + /// How many of the `removed` nodes cover each block. + fn cover_counts(&self, removed: &HashSet) -> HashMap { + let mut cover: HashMap = HashMap::new(); + for key in removed { + if let Some(node) = self.nodes.get(key) { + for h in node.path.iter() { + *cover.entry(*h).or_default() += 1; + } + } + } + cover + } + + /// The nearest ancestor of `node` that is a node still standing: (blocks from the start through it, its key). + /// A tail node's nearest ancestor may be the grid node at the end of its own path. + fn nearest_surviving(&self, node: &Node, removed: &HashSet) -> Option<(usize, u64)> { + let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 }; + (0..upto).rev().find_map(|i| { + let h = node.path[i]; + (self.nodes.contains_key(&h) && !removed.contains(&h)).then_some((i + 1, h)) + }) + } + + /// For every node not removed: the tokens up to its nearest surviving ancestor, and the number of surviving + /// children of every node. + fn surviving_ancestors(&self, removed: &HashSet) -> (HashMap, HashMap) { + let g = self.cfg.block_tokens; + let mut ancestor: HashMap = HashMap::with_capacity(self.nodes.len()); + let mut children: HashMap = HashMap::new(); + for (key, node) in &self.nodes { + if removed.contains(key) { + continue; + } + let mut depth = 0; + if let Some((blocks, parent)) = self.nearest_surviving(node, removed) { + depth = blocks * g; + *children.entry(parent).or_default() += 1; + } + ancestor.insert(*key, depth); + } + (ancestor, children) + } + + /// The bytes evicting `node` frees: its own, and those of every block no other surviving node covers (blocks in + /// `protect` stay whatever happens). + fn freed_by(&self, node: &Node, cover: &HashMap, protect: &HashSet) -> usize { + let mut freed = node.bytes; + for h in node.path.iter() { + let block = &self.blocks[h]; + if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { + freed += block.bytes; + } + } + freed + } + + /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is + /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. + /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). + pub(in super::super) fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { + let cover = self.cover_counts(removed); + let (ancestor, children) = self.surviving_ancestors(removed); + let mut out = Vec::with_capacity(ancestor.len()); + for (key, node) in &self.nodes { + let Some(&anc) = ancestor.get(key) else { + continue; + }; + let freed = self.freed_by(node, &cover, protect); + let marginal = (self.tokens_of(node) - anc) as f64; + let p = self.probability(node, children.get(key).copied().unwrap_or(0)); + out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); + } + out + } +} 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 74a91ce1..779dbfbd 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 @@ -1,4 +1,8 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves, thinning_a_chain_keeps_the_deepest_node_and_the_blocks_it_needs, the_budget_is_enforced_again_when_the_real_payload_is_bigger_than_the_estimate, commit_refuses_blocks_that_are_not_the_candidates .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves, +//! thinning_a_chain_keeps_the_deepest_node_and_the_blocks_it_needs, +//! the_budget_is_enforced_again_when_the_real_payload_is_bigger_than_the_estimate, +//! commit_refuses_blocks_that_are_not_the_candidates .... #[allow(unused_imports)] use super::*; @@ -153,10 +157,10 @@ fn a_long_agent_session_costs_a_sparse_chain_not_a_node_per_block() { assert!(depths.iter().any(|d| *d < 39), "{depths:?}"); } -/// 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. +/// 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"] fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_stays_fast() { @@ -232,7 +236,8 @@ fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_ s.stats().evicted ); assert!(longest >= 170_000); - // 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 + // 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)); 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 a367603e..b764a723 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 @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): a_request_resumes_from_the_deepest_node_of_any_session, common_prefixes_are_stored_once, a_node_with_descendants_is_a_branch_point_and_a_frontier_is_not, the_prompt_end_checkpoint_survives_the_decode_end_checkpoint_of_its_request .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! a_request_resumes_from_the_deepest_node_of_any_session, common_prefixes_are_stored_once, +//! a_node_with_descendants_is_a_branch_point_and_a_frontier_is_not, +//! the_prompt_end_checkpoint_survives_the_decode_end_checkpoint_of_its_request .... #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/prompt/impl_promptoptions.rs b/crates/engine-core/src/prompt/impl_promptoptions.rs index fd254dab..d183d6bd 100644 --- a/crates/engine-core/src/prompt/impl_promptoptions.rs +++ b/crates/engine-core/src/prompt/impl_promptoptions.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl PromptOptions, fn request_capacity, fn choose_auto_capacity, impl PromptPlan, impl Iterator_for_PromptPlan, fn drive. +//! Moved out of the parent module by STRA-338: impl PromptOptions, fn request_capacity, fn choose_auto_capacity, impl +//! PromptPlan, impl Iterator_for_PromptPlan, fn drive. #[allow(unused_imports)] use super::*; @@ -32,6 +33,20 @@ pub fn request_capacity(tokens: usize, configured: usize) -> Result { Ok(rounded.min(configured)) } +//// The auto ladder skips the capacities above 8192 that exceed the auto maximum or the context. +fn ladder_skips(candidate: usize, auto_max: usize, context_tokens: usize) -> bool { + candidate > 8192 && (candidate > auto_max || candidate > context_tokens) +} + +/// A capacity whose cache-slot loan is `slots` fits: at most the cache's slots with 128 retained, and within the loan +/// percentage. +fn loan_fits(slots: usize, cache_slots: usize, lend_percent: usize) -> Result { + let retained = slots.checked_add(128).ok_or(PlanError::Overflow)?; + let used = slots.checked_mul(100).ok_or(PlanError::Overflow)?; + let allowance = lend_percent.checked_mul(cache_slots).ok_or(PlanError::Overflow)?; + Ok(retained <= cache_slots && used <= allowance) +} + /// Original auto ladder and actual cache-slot loan test. The callback must /// inspect the real cache; a returned number does not mint device storage. pub fn choose_auto_capacity( @@ -45,19 +60,70 @@ pub fn choose_auto_capacity( return Err(PlanError::InvalidInput); } for candidate in [32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256] { - if candidate > 8192 && (candidate > auto_max || candidate > context_tokens) { + if ladder_skips(candidate, auto_max, context_tokens) { continue; } - let slots = actual_lend_slots(candidate)?; - let retained = slots.checked_add(128).ok_or(PlanError::Overflow)?; - let used = slots.checked_mul(100).ok_or(PlanError::Overflow)?; - let allowance = lend_percent.checked_mul(cache_slots).ok_or(PlanError::Overflow)?; - if retained <= cache_slots && used <= allowance { + if loan_fits(actual_lend_slots(candidate)?, cache_slots, lend_percent)? { return Ok(Some(candidate)); } } Ok(None) } + +/// The prompt, the options, the admitted capacity and the re-read end are ones the Original's planner accepts. +fn prompt_is_valid( + prompt: &[u32], + (resume, embedding_rows): (usize, Option<&[bool]>), + options: &PromptOptions, + (admitted_capacity, reread_to): (usize, Option), +) -> bool { + prompt_fits(prompt, resume, embedding_rows, options) + && options_are_valid(options, admitted_capacity, (resume, reread_to)) +} + +/// The prompt and its embedding rows are consistent with the context. +fn prompt_fits(prompt: &[u32], resume: usize, embedding_rows: Option<&[bool]>, options: &PromptOptions) -> bool { + !(prompt.is_empty() + || prompt.len() > options.context_tokens + || resume >= prompt.len() + || prompt.iter().any(|id| *id >= 248320) + || embedding_rows.is_some_and(|rows| rows.len() != prompt.len())) +} + +/// The options, the admitted capacity and the re-read end are ones the Original's planner accepts. +fn options_are_valid( + options: &PromptOptions, + admitted_capacity: usize, + (resume, reread_to): (usize, Option), +) -> bool { + !(![8192, 16384, 32768].contains(&options.auto_max) + || ![256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768].contains(&admitted_capacity) + || admitted_capacity > options.auto_max + || !(1..=4).contains(&options.verify_width) + || reread_to.is_some_and(|end| end == 0 || end > resume) + || (options.grid != 0 && (options.grid % 256 != 0 || options.grid > admitted_capacity))) +} + +/// The last turn boundary after `resume`, when the prompt cache is on. +fn find_turn(prompt: &[u32], resume: usize, options: &PromptOptions) -> Option { + if !options.prompt_cache { + return None; + } + options.turn_token.and_then(|id| (resume + 1..prompt.len()).rev().find(|index| prompt[*index] == id)) +} + +/// The root boundary: the first turn token before `turn`, at least `root_min` tokens in. +fn find_root(prompt: &[u32], options: &PromptOptions, read_from: usize, turn: Option) -> Option { + if !(options.prompt_cache && options.root_min > 0 && read_from == 0) { + return None; + } + options.turn_token.and_then(|id| { + // FIRST boundary only; a later boundary cannot substitute for + // an undersized original system root. + (1..turn.unwrap_or(0)).find(|index| prompt[*index] == id).filter(|index| *index >= options.root_min) + }) +} + impl<'a> PromptPlan<'a> { /// [`PromptPlan::new`] for a context that must also fit the serving context's `serving_cells` (the runtime passes /// the driver's cell count; the pure crate does not read the driver). @@ -85,42 +151,18 @@ impl<'a> PromptPlan<'a> { options: PromptOptions, admitted_capacity: usize, ) -> Result { - if prompt.is_empty() - || prompt.len() > options.context_tokens - || resume >= prompt.len() - || prompt.iter().any(|id| *id >= 248320) - || ![8192, 16384, 32768].contains(&options.auto_max) - || ![256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768].contains(&admitted_capacity) - || admitted_capacity > options.auto_max - || !(1..=4).contains(&options.verify_width) - || embedding_rows.is_some_and(|rows| rows.len() != prompt.len()) - || reread_to.is_some_and(|end| end == 0 || end > resume) - || (options.grid != 0 && (options.grid % 256 != 0 || options.grid > admitted_capacity)) - { + if !prompt_is_valid(prompt, (resume, embedding_rows), &options, (admitted_capacity, reread_to)) { return Err(PlanError::InvalidInput); } - let last = prompt.len() - 1; let read_from = if reread_to.is_some() { 0 } else { resume }; - let turn = if options.prompt_cache { - options.turn_token.and_then(|id| (resume + 1..prompt.len()).rev().find(|index| prompt[*index] == id)) - } else { - None - }; - let root = if options.prompt_cache && options.root_min > 0 && read_from == 0 { - options.turn_token.and_then(|id| { - // FIRST boundary only; a later boundary cannot substitute for - // an undersized original system root. - (1..turn.unwrap_or(0)).find(|index| prompt[*index] == id).filter(|index| *index >= options.root_min) - }) - } else { - None - }; + let turn = find_turn(prompt, resume, &options); + let root = find_root(prompt, &options, read_from, turn); Ok(Self { prompt, embedding_rows, options, admitted_capacity, - boundaries: [reread_to.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), last], + boundaries: [reread_to.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), prompt.len() - 1], turn, root, segment: 0, @@ -157,6 +199,27 @@ impl<'a> PromptPlan<'a> { } self.path = None; } + + /// The next action of the segment being read, along `path`. + fn step(&mut self, path: PromptPath) -> PromptAction { + let width = match path { + PromptPath::Batched { capacity } => capacity, + PromptPath::Verify => self.options.verify_width, + PromptPath::FinalSeed => unreachable!("seed is outside conditioning segments"), + }; + let mut count = width.min(self.end - self.position); + if self.options.grid != 0 && matches!(path, PromptPath::Batched { .. }) { + count = count.min(self.options.grid - self.position % self.options.grid); + } + let first = self.position; + self.position += count; + PromptAction { + first, + count, + path, + checkpoint_after: self.position == self.end && (Some(self.end) == self.turn || Some(self.end) == self.root), + } + } } impl Iterator for PromptPlan<'_> { type Item = PromptAction; @@ -165,24 +228,7 @@ impl Iterator for PromptPlan<'_> { self.next_segment(); } if let Some(path) = self.path { - let width = match path { - PromptPath::Batched { capacity } => capacity, - PromptPath::Verify => self.options.verify_width, - PromptPath::FinalSeed => unreachable!("seed is outside conditioning segments"), - }; - let mut count = width.min(self.end - self.position); - if self.options.grid != 0 && matches!(path, PromptPath::Batched { .. }) { - count = count.min(self.options.grid - self.position % self.options.grid); - } - let first = self.position; - self.position += count; - return Some(PromptAction { - first, - count, - path, - checkpoint_after: self.position == self.end - && (Some(self.end) == self.turn || Some(self.end) == self.root), - }); + return Some(self.step(path)); } if self.seed_done { return None; @@ -196,6 +242,67 @@ impl Iterator for PromptPlan<'_> { }) } } + +/// An action that is empty, overflows, or does not start where the last one ended breaks the plan's contract. +fn check_contiguous(action: &PromptAction, cursor: Option) -> core::result::Result<(), DriveError> { + if action.count == 0 || action.first.checked_add(action.count).is_none() { + return Err(DriveError::Contract("empty or overflowing action")); + } + if cursor.is_some_and(|expected| expected != action.first) { + return Err(DriveError::Contract("plan positions are not contiguous")); + } + Ok(()) +} + +/// Hand one action to the runner on its path and count it. +fn run_action( + runner: &mut R, + action: &PromptAction, + admitted_capacity: usize, + summary: &mut DriveSummary, +) -> core::result::Result<(), DriveError> { + match action.path { + PromptPath::Batched { capacity } => { + if action.count > capacity || capacity > admitted_capacity { + return Err(DriveError::Contract("batched chunk exceeds the admitted capacity")); + } + runner.batched(action).map_err(DriveError::Runner)?; + summary.batched_chunks += 1; + summary.batched_rows += action.count; + } + PromptPath::Verify => { + runner.verify_window(action).map_err(DriveError::Runner)?; + summary.verify_windows += 1; + summary.verify_rows += action.count; + } + PromptPath::FinalSeed => { + if summary.final_seed || action.count != 1 { + return Err(DriveError::Contract("the final seed is one row, once")); + } + runner.final_seed(action).map_err(DriveError::Runner)?; + summary.final_seed = true; + } + } + Ok(()) +} + +/// The checkpoint a segment end asks for; never after the final seed. +fn checkpoint_if_due( + runner: &mut R, + action: &PromptAction, + end: usize, + summary: &mut DriveSummary, +) -> core::result::Result<(), DriveError> { + if action.checkpoint_after { + if matches!(action.path, PromptPath::FinalSeed) { + return Err(DriveError::Contract("checkpoint after the final seed")); + } + runner.checkpoint(end).map_err(DriveError::Runner)?; + summary.checkpoints += 1; + } + Ok(()) +} + /// The prompt scheduler caller: walks a plan to its end, checking the contract the Original relies on between /// `generate.cpp` and `Prefill::run` (contiguous positions, `count <= capacity`, one final seed, checkpoints only on /// segment ends) and delegating every action to the runner. Stops at the first runner error. @@ -210,45 +317,13 @@ pub fn drive( if runner.cancelled() { return Err(DriveError::Cancelled { at: action.first }); } - if action.count == 0 || action.first.checked_add(action.count).is_none() { - return Err(DriveError::Contract("empty or overflowing action")); - } - if cursor.is_some_and(|expected| expected != action.first) { - return Err(DriveError::Contract("plan positions are not contiguous")); - } + check_contiguous(&action, cursor)?; if cursor.is_none() { summary.first = action.first; } let end = action.first + action.count; - match action.path { - PromptPath::Batched { capacity } => { - if action.count > capacity || capacity > admitted_capacity { - return Err(DriveError::Contract("batched chunk exceeds the admitted capacity")); - } - runner.batched(&action).map_err(DriveError::Runner)?; - summary.batched_chunks += 1; - summary.batched_rows += action.count; - } - PromptPath::Verify => { - runner.verify_window(&action).map_err(DriveError::Runner)?; - summary.verify_windows += 1; - summary.verify_rows += action.count; - } - PromptPath::FinalSeed => { - if summary.final_seed || action.count != 1 { - return Err(DriveError::Contract("the final seed is one row, once")); - } - runner.final_seed(&action).map_err(DriveError::Runner)?; - summary.final_seed = true; - } - } - if action.checkpoint_after { - if matches!(action.path, PromptPath::FinalSeed) { - return Err(DriveError::Contract("checkpoint after the final seed")); - } - runner.checkpoint(end).map_err(DriveError::Runner)?; - summary.checkpoints += 1; - } + run_action(runner, &action, admitted_capacity, &mut summary)?; + checkpoint_if_due(runner, &action, end, &mut summary)?; cursor = Some(end); summary.end = end; } diff --git a/crates/engine-core/src/request.rs b/crates/engine-core/src/request.rs index 6be0822d..739d513a 100644 --- a/crates/engine-core/src/request.rs +++ b/crates/engine-core/src/request.rs @@ -1,18 +1,20 @@ //! Request-level rules of the Original serve path that need no device: admission, the sequencing of one request over -//! the owners, and the classes a request ends in. The device owners sit behind [`Lifecycle`], so the order (reset when the -//! previous request left state behind, condition the prompt up to its last token, decode) and its failure classes run -//! over any owners, a scripted fake included. +//! the owners, and the classes a request ends in. The device owners sit behind [`Lifecycle`], so the order (reset when +//! the previous request left state behind, condition the prompt up to its last token, decode) and its failure classes +//! run over any owners, a scripted fake included. //! -//! Original reference (`generate.cpp` serve): a request with `n + max_new + 8 > max_context` is refused before any work; -//! the prompt is read through token n-2 and token n-1 is the first verify input. With the conversation cache +//! Original reference (`generate.cpp` serve): a request with `n + max_new + 8 > max_context` is refused before any +//! work; the prompt is read through token n-2 and token n-1 is the first verify input. With the conversation cache //! ([`Lifecycle::resume`]) a request starts reading where an earlier one left a reusable prefix; without it every //! request starts from the empty prompt. -/// `<|endoftext|>`: the Original's `--eos-ids` default is {248044, 248046}; the GGUF's `tokenizer.ggml.eos_token_id` is only 248046 -/// (`<|im_end|>`), so a request that stops on the metadata id alone runs on past an `<|endoftext|>` (quality gate, docs/quality-gate.md). +/// `<|endoftext|>`: the Original's `--eos-ids` default is {248044, 248046}; the GGUF's `tokenizer.ggml.eos_token_id` is +/// only 248046 (`<|im_end|>`), so a request that stops on the metadata id alone runs on past an `<|endoftext|>` +/// (quality gate, docs/quality-gate.md). pub const ENDOFTEXT_TOKEN: i32 = 248_044; -/// The stop set of a request on the Original serve path: generate.cpp's `eos_ids` ({248044, 248046}) plus the model's own EOS id. +/// The stop set of a request on the Original serve path: generate.cpp's `eos_ids` ({248044, 248046}) plus the model's +/// own EOS id. pub fn original_stop_tokens(eos: u32) -> Vec { let eos = eos as i32; if eos == ENDOFTEXT_TOKEN { vec![eos] } else { vec![eos, ENDOFTEXT_TOKEN] } @@ -94,8 +96,8 @@ pub trait Lifecycle { /// when the cache is off or could not place the owners; the request then starts from the empty prompt through /// `is_fresh`/`reset`. fn resume(&mut self, request: &Self::Request) -> Option; - /// Condition `prompt[resume..n-1]` into the session and the draft ring (they stand at `resume`). The interruption is - /// a cancel only when the caller's flag fired. + /// Condition `prompt[resume..n-1]` into the session and the draft ring (they stand at `resume`). The interruption + /// is a cancel only when the caller's flag fired. fn prefill bool>( &mut self, request: &Self::Request, @@ -113,6 +115,28 @@ pub trait Lifecycle { fn finish(&mut self, ended: Result<(), ServeError>); } +/// Place the request: how many prompt tokens are not read again. A cache that could not place the owners starts +/// from the empty prompt (reset if the session is not fresh); a position past the prompt breaks the request. +fn place_resume(owners: &mut L, request: &L::Request) -> Result> { + match owners.resume(request) { + Some(resume) if resume >= L::prompt_len(request) => { + // the last prompt token always starts the first verify window + owners.finish(Err(ServeError::Broken(L::invalid_position()))); + Err(ServeError::Broken(L::invalid_position())) + } + Some(resume) => Ok(resume), + None => { + if !owners.is_fresh() { + owners.reset().map_err(ServeError::Broken)?; + if !owners.is_fresh() { + return Err(ServeError::Broken(L::identity_mismatch())); + } + } + Ok(0) + } + } +} + /// One request over the owners. pub fn run_request Result<(), L::Error>, C: FnMut() -> bool>( owners: &mut L, @@ -125,25 +149,7 @@ pub fn run_request Result<(), L::Error>, C: Fn if cancel() { return Err(ServeError::Cancelled); } - let resume = match owners.resume(request) { - Some(resume) => { - if resume >= L::prompt_len(request) { - // the last prompt token always starts the first verify window - owners.finish(Err(ServeError::Broken(L::invalid_position()))); - return Err(ServeError::Broken(L::invalid_position())); - } - resume - } - None => { - if !owners.is_fresh() { - owners.reset().map_err(ServeError::Broken)?; - if !owners.is_fresh() { - return Err(ServeError::Broken(L::identity_mismatch())); - } - } - 0 - } - }; + let resume = place_resume(owners, request)?; let served = owners .prefill(request, resume, cancel) .and_then(|()| owners.decode(request, emit, cancel)) diff --git a/crates/engine-core/src/spec/adaptive.rs b/crates/engine-core/src/spec/adaptive.rs index ac3f6c1b..ea02738d 100644 --- a/crates/engine-core/src/spec/adaptive.rs +++ b/crates/engine-core/src/spec/adaptive.rs @@ -14,10 +14,11 @@ //! * MTP draft i with own probability p: `a = cell[depth][bucket(p)]`, shrunk toward the depth-independent //! `cell[bucket(p)]`, shrunk toward a prior calibrated from the bucket centre; plus a fast scalar logit bias that //! tracks the current content (code edit vs prose vs tool-call JSON) with a rate of a few rounds. -//! * suffix rows: first row and continuation rows by match-length bucket, separately for suffix tokens that AGREE with -//! the MTP's first draft and for those that do not (the Original only ever used the agreeing ones). +//! * suffix rows: first row and continuation rows by match-length bucket, separately for suffix tokens that AGREE +//! with the MTP's first draft and for those that do not (the Original only ever used the agreeing ones). //! * T(t): decayed mean of (round ms - draft ms) per width, winsorised, blended with a fit `a + c (t-1)` whose slope -//! is ridge-regularised toward a typical value; the slope is what the expert tier / CPU pool / PCIe state shows up as. +//! is ridge-regularised toward a typical value; the slope is what the expert tier / CPU pool / PCIe state shows +//! up as. use super::policy::MAX_T; const P_BUCKETS: usize = 8; @@ -30,19 +31,21 @@ const S_FIRST_AGREE: [f64; M_BUCKETS] = [0.75, 0.88, 0.93, 0.96, 0.97]; const S_FIRST_OTHER: [f64; M_BUCKETS] = [0.25, 0.35, 0.45, 0.55, 0.65]; const S_CONT_AGREE: [f64; M_BUCKETS] = [0.88, 0.93, 0.96, 0.97, 0.98]; const S_CONT_OTHER: [f64; M_BUCKETS] = [0.75, 0.85, 0.90, 0.93, 0.95]; -/// Upper bound of the chain's confidence floor when the request carries none (`spec_min_p` 0, the product profile). The computed floor (`draft_plan`) is the -/// lower edge of the first probability bucket whose calibrated acceptance clears the bar of a further draft; at 245k context (1.8 ms per verified row, a faster -/// draft round) that bar sits at the acceptance of the 0.7-0.8 bucket, so the floor flips between 0.7 and 0.8 and every flip prunes a tenth of the chain's -/// continuations, drafts that the verify-time choice (calibrated acceptance of the actual row, a better-informed test than one draft's own probability) -/// would have kept. A lower ceiling leaves that choice to `choose`. `LELEKA_SPEC_POLICY=legacy` restores [`FLOOR_CEILING_LEGACY`]. +/// Upper bound of the chain's confidence floor when the request carries none (`spec_min_p` 0, the product profile). The +/// computed floor (`draft_plan`) is the lower edge of the first probability bucket whose calibrated acceptance clears +/// the bar of a further draft; at 245k context (1.8 ms per verified row, a faster draft round) that bar sits at the +/// acceptance of the 0.7-0.8 bucket, so the floor flips between 0.7 and 0.8 and every flip prunes a tenth of the +/// chain's continuations, drafts that the verify-time choice (calibrated acceptance of the actual row, a +/// better-informed test than one draft's own probability) would have kept. A lower ceiling leaves that choice to +/// `choose`. `LELEKA_SPEC_POLICY=legacy` restores [`FLOOR_CEILING_LEGACY`]. pub const FLOOR_CEILING: f32 = 0.60; /// The ceiling the policy shipped with (a request with `spec_min_p` 0 meant 0.9). pub const FLOOR_CEILING_LEGACY: f32 = 0.90; const N0_BUCKET: f64 = 6.0; const N0_DEPTH: f64 = 10.0; const N0_SUFFIX: f64 = 4.0; -/// Typical extra cost per verified row as a fraction of the one-row window (docs/roofline.md: chain 8 + 1.6 T ms plus the expert -/// misses; about 0.12-0.2 with a converged tier, more with a cold one). Only the prior of the slope fit. +/// Typical extra cost per verified row as a fraction of the one-row window (docs/roofline.md: chain 8 + 1.6 T ms plus +/// the expert misses; about 0.12-0.2 with a converged tier, more with a cold one). Only the prior of the slope fit. const PRIOR_SLOPE: f64 = 0.15; #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -72,12 +75,15 @@ pub struct AdaptiveConfig { pub decay: f64, /// Rate of the fast content bias. pub bias_rate: f64, - /// Share of a verified row's cost that a DRAFTED row is expected to cost: a draft is produced for `draft_step_ms` and is verified (pays the row slope) only when - /// the next round chooses it (1.0 = the earlier rule, every produced draft is verified). + /// Share of a verified row's cost that a DRAFTED row is expected to cost: a draft is produced for `draft_step_ms` + /// and is verified (pays the row slope) only when the next round chooses it (1.0 = the earlier rule, every produced + /// draft is verified). pub row_q: f64, - /// The draft floor follows the calibrated acceptance curve continuously (linear between the bucket centres) instead of jumping between the bucket edges. + /// The draft floor follows the calibrated acceptance curve continuously (linear between the bucket centres) instead + /// of jumping between the bucket edges. pub smooth_floor: bool, - /// The draft floor's bar uses the measured token rate of the recent rounds instead of the rate the chosen candidate was predicted to have. + /// The draft floor's bar uses the measured token rate of the recent rounds instead of the rate the chosen candidate + /// was predicted to have. pub measured_rate: bool, } @@ -145,7 +151,8 @@ pub struct AdaptivePolicy { rounds: u64, since_explore: u64, last: Option<(Origin, usize)>, - /// A probe in progress: the width being measured and how many more rounds it runs (a single sample moves a decayed mean too little). + /// A probe in progress: the width being measured and how many more rounds it runs (a single sample moves a decayed + /// mean too little). probe: Option<(usize, u32)>, hold_t: f64, drafts_ewma: f64, @@ -186,5 +193,7 @@ use impl_adaptiveconfig::m_bucket; use impl_adaptiveconfig::p_bucket; #[allow(unused_imports)] use impl_adaptiveconfig::sigmoid; +mod decide; mod impl_adaptivepolicy; mod impl_specstats; +mod learn; diff --git a/crates/engine-core/src/spec/adaptive/decide.rs b/crates/engine-core/src/spec/adaptive/decide.rs new file mode 100644 index 00000000..b7fd40dc --- /dev/null +++ b/crates/engine-core/src/spec/adaptive/decide.rs @@ -0,0 +1,168 @@ +//! The decision of one round: which origin and width to verify, the exploration of neighbouring widths, and how deep +//! the next MTP chain should go. + +#[allow(unused_imports)] +use super::*; + +/// The candidate with the highest rate (the first one on a tie). +fn best_candidate(cands: &[Cand]) -> Cand { + let mut best = cands[0]; + for c in cands { + if c.rate > best.rate { + best = *c; + } + } + best +} + +/// A neighbouring width (one row more or fewer than `best`) whose model says it is nearly as good. +fn is_neighbour_in_reach(c: &Cand, best: &Cand) -> bool { + c.t != best.t && (c.t as i64 - best.t as i64).abs() == 1 && !(c.rate < 0.88 * best.rate) +} + +/// The decision, with the probabilities and the suffix match the learning needs. +fn choice_of(best: Cand, explored: bool, offer: &Offer<'_>) -> Choice { + let mut probs = [0.0f32; MAX_T]; + for (d, &p) in offer.mtp_probs.iter().take(MAX_T).enumerate() { + probs[d] = p; + } + Choice { + origin: best.origin, + t: best.t, + expected: best.expected, + rate: best.rate, + explored, + probs, + matched: offer.suffix_match, + agrees: offer.suffix_agrees, + } +} + +/// The smallest draft probability at which the calibrated acceptance (linear between the bucket centres) reaches the +/// bar `a_req`; `None` when no bucket does. +fn smooth_floor(rates: &[f64; P_BUCKETS], a_req: f64) -> Option { + let centre = + |b: usize| -> f64 { if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 } }; + let b = rates.iter().position(|&r| r >= a_req)?; + if b == 0 { + return Some(0.0); + } + let (c0, c1, r0, r1) = (centre(b - 1), centre(b), rates[b - 1], rates[b]); + Some(c0 + (c1 - c0) * ((a_req - r0) / (r1 - r0).max(1e-9)).clamp(0.0, 1.0)) +} + +/// The lower edge of the first bucket whose calibrated acceptance reaches the bar `a_req`. +fn bucket_floor(rates: &[f64; P_BUCKETS], a_req: f64) -> Option { + rates.iter().position(|&r| r >= a_req).map(|b| P_EDGES[b]) +} + +impl AdaptivePolicy { + /// Keep the previous round's (origin, width) unless the best is clearly better. + fn keep_previous(&self, cands: &[Cand], best: Cand) -> Cand { + let Some((o, t)) = self.last else { return best }; + match cands.iter().find(|c| c.origin == o && c.t == t) { + Some(prev) if prev.rate * (1.0 + self.cfg.margin) >= best.rate => *prev, + _ => best, + } + } + + /// Continue the probe while its width is still on offer; true when it did (and `best` is the probed candidate). + fn continue_probe(&mut self, cands: &[Cand], best: &mut Cand) -> bool { + let Some((t, left)) = self.probe else { return false }; + match cands.iter().filter(|c| c.t == t).max_by(|a, b| a.rate.total_cmp(&b.rate)) { + Some(c) if left > 0 => { + *best = *c; + self.probe = Some((t, left - 1)); + true + } + _ => { + self.probe = None; + false + } + } + } + + /// The width `t` was measured at least three times, the last one within 48 rounds. + fn measured_lately(&self, t: usize) -> bool { + self.cost_n[t] >= 3.0 && self.rounds.saturating_sub(self.seen[t]) < 48 + } + + /// `c` has fewer measurements than `p`, or as many and a better rate. + fn less_measured(&self, c: &Cand, p: &Cand) -> bool { + self.cost_n[c.t] < self.cost_n[p.t] || (self.cost_n[c.t] == self.cost_n[p.t] && c.rate > p.rate) + } + + /// The neighbouring width to explore: nearly as good as `best` by the model, and not measured lately. + fn stale_neighbour(&self, cands: &[Cand], best: Cand) -> Option { + let mut pick: Option = None; + for c in cands { + if !is_neighbour_in_reach(c, &best) || self.measured_lately(c.t) { + continue; + } + if pick.is_none_or(|p| self.less_measured(c, &p)) { + pick = Some(*c); + } + } + pick + } + + /// Exploration: when it is due, a neighbouring width whose model says it is nearly as good, when it has not been + /// measured lately; the probe of it is armed for the next three rounds. + fn explore(&mut self, cands: &[Cand], best: Cand) -> Option { + let period = if self.rounds < 24 { (self.cfg.explore_period / 4).max(2) } else { self.cfg.explore_period }; + if self.cfg.explore_period == 0 || self.since_explore < period { + return None; + } + let pick = self.stale_neighbour(cands, best)?; + self.since_explore = 0; + self.probe = Some((pick.t, 3)); + Some(pick) + } + + pub fn choose(&mut self, offer: &Offer<'_>) -> Choice { + let mut cands = Vec::with_capacity(2 * MAX_T); + self.candidates(offer, &mut cands); + let mut best = self.keep_previous(&cands, best_candidate(&cands)); + let mut explored = self.continue_probe(&cands, &mut best); + self.since_explore += 1; + if !explored && let Some(p) = self.explore(&cands, best) { + best = p; + explored = true; + } + choice_of(best, explored, offer) + } + + // ---- next draft chain ------------------------------------------------------------------------------------- + + /// The calibrated acceptance a further draft must promise to be worth producing: `rate * (row_q * row slope + chain + /// step) / survival` (see `draft_plan`). + pub fn bar(&self) -> f64 { + let rate = if self.cfg.measured_rate && self.meas_ms > 0.0 { + self.meas_tok / self.meas_ms + } else if self.rate_ewma > 0.0 { + self.rate_ewma + } else { + 0.04 + }; + (rate * (self.cfg.row_q * self.row_slope_ms() + self.cfg.draft_step_ms) / self.survive_ewma.max(0.2)) + .clamp(0.0, 0.99) + } + + /// How deep the next MTP chain should go and the draft probability below which it stops. A chain step costs + /// `draft_step_ms`; a verified row costs `row_slope_ms` and is worth it when `survival * a / slope` beats the + /// current tokens-per-ms, so the floor is the smallest draft probability whose calibrated acceptance clears that + /// bar. + pub fn draft_plan(&self) -> DraftPlan { + let max_drafts = ((self.hold_t.ceil() as usize).max(2)).min(self.cfg.max_drafts.max(1)); + let a_req = self.bar(); + let rates: [f64; P_BUCKETS] = + std::array::from_fn(|b| sigmoid(logit(self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + self.bias_mtp)); + let found = if self.cfg.smooth_floor { + smooth_floor(&rates, a_req).map(|p| p as f32) + } else { + bucket_floor(&rates, a_req) + }; + let min_p = found.unwrap_or(self.cfg.min_p_hi); + DraftPlan { max_drafts, min_p: min_p.clamp(self.cfg.min_p_lo, self.cfg.min_p_hi) } + } +} diff --git a/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs b/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs index 88ef347b..5d752b46 100644 --- a/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs +++ b/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl AdaptiveConfig, impl Cell, fn p_bucket, fn m_bucket, fn logit, fn sigmoid. +//! Moved out of the parent module by STRA-338: impl AdaptiveConfig, impl Cell, fn p_bucket, fn m_bucket, fn logit, fn +//! sigmoid. #[allow(unused_imports)] use super::*; @@ -22,18 +23,25 @@ impl AdaptiveConfig { measured_rate: false, } } - /// `LELEKA_SPEC_POLICY`: unset / `current` = the defaults of [`Self::new`]; `legacy` (also `v1`) = the constants of the earlier policy (the draft-floor ceiling 0.9). + /// `LELEKA_SPEC_POLICY`: unset / `current` = the defaults of [`Self::new`]; `legacy` (also `v1`) = the constants of + /// the earlier policy (the draft-floor ceiling 0.9). pub fn with_policy(mut self, policy: Option<&str>) -> Self { if matches!(policy.map(str::trim), Some("legacy" | "v1")) { self.min_p_hi = FLOOR_CEILING_LEGACY; } self } - /// One named constant of a replay arm (`adaptive@0~step=0.3~explore=0`, `OriginalServeSettings::arms_from_environment`): the same - /// constants as the `LELEKA_SPEC_*` variables, so that policy variants can be compared inside one process on the same forced text. - /// False when the key or the value is not understood. + /// One named constant of a replay arm (`adaptive@0~step=0.3~explore=0`, + /// `OriginalServeSettings::arms_from_environment`): the same constants as the `LELEKA_SPEC_*` variables, so that + /// policy variants can be compared inside one process on the same forced text. False when the key or the value is + /// not understood. pub fn set_option(&mut self, key: &str, value: &str) -> bool { let Ok(v) = value.trim().parse::() else { return false }; + self.set_tuning(key, v) || self.set_shape(key, v) + } + + /// The constants of the cost model and the exploration. + fn set_tuning(&mut self, key: &str, v: f64) -> bool { match key { "explore" => self.explore_period = v as u64, "margin" => self.margin = v, @@ -41,6 +49,14 @@ impl AdaptiveConfig { "step" => self.draft_step_ms = v, "alpha" => self.cost_alpha = v, "decay" => self.decay = v, + _ => return false, + } + true + } + + /// The constants of the draft chain. + fn set_shape(&mut self, key: &str, v: f64) -> bool { + match key { "bias" => self.bias_rate = v, "ceil" => self.min_p_hi = v as f32, "rowq" => self.row_q = v, diff --git a/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs b/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs index 9c1d97cb..5e1eaae4 100644 --- a/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs +++ b/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs @@ -71,8 +71,8 @@ impl AdaptivePolicy { // ---- cost ------------------------------------------------------------------------------------------------- - /// Trust in the per-width mean: it fades as it ages (the machine's state drifts), so a stale width falls back to what - /// the recent rounds imply. + /// Trust in the per-width mean: it fades as it ages (the machine's state drifts), so a stale width falls back to + /// what the recent rounds imply. pub(super) fn weight(&self, t: usize) -> f64 { let age = self.rounds.saturating_sub(self.seen[t]) as f64; self.cost_n[t].min(10.0) * (-age / 24.0).exp() @@ -133,229 +133,4 @@ impl AdaptivePolicy { } } } - - pub fn choose(&mut self, offer: &Offer<'_>) -> Choice { - let mut cands = Vec::with_capacity(2 * MAX_T); - self.candidates(offer, &mut cands); - let mut best = cands[0]; - for c in &cands { - if c.rate > best.rate { - best = *c; - } - } - // hysteresis: keep the previous round's (origin, width) unless the best is clearly better - if let Some((o, t)) = self.last { - if let Some(prev) = cands.iter().find(|c| c.origin == o && c.t == t) { - if prev.rate * (1.0 + self.cfg.margin) >= best.rate { - best = *prev; - } - } - } - // exploration: a neighbouring width whose model says it is nearly as good, when it has not been measured lately - let mut explored = false; - if let Some((t, left)) = self.probe { - // continue the probe while its width is still on offer - match cands.iter().filter(|c| c.t == t).max_by(|a, b| a.rate.total_cmp(&b.rate)) { - Some(c) if left > 0 => { - best = *c; - explored = true; - self.probe = Some((t, left - 1)); - } - _ => self.probe = None, - } - } - self.since_explore += 1; - let period = if self.rounds < 24 { (self.cfg.explore_period / 4).max(2) } else { self.cfg.explore_period }; - if self.cfg.explore_period > 0 && !explored && self.since_explore >= period { - let mut pick: Option = None; - for c in &cands { - if c.t == best.t || (c.t as i64 - best.t as i64).abs() != 1 || c.rate < 0.88 * best.rate { - continue; - } - let stale = self.rounds.saturating_sub(self.seen[c.t]); - if self.cost_n[c.t] >= 3.0 && stale < 48 { - continue; - } - if pick.is_none_or(|p| { - self.cost_n[c.t] < self.cost_n[p.t] || (self.cost_n[c.t] == self.cost_n[p.t] && c.rate > p.rate) - }) { - pick = Some(*c); - } - } - if let Some(p) = pick { - best = p; - explored = true; - self.since_explore = 0; - self.probe = Some((p.t, 3)); - } - } - let mut probs = [0.0f32; MAX_T]; - for (d, &p) in offer.mtp_probs.iter().take(MAX_T).enumerate() { - probs[d] = p; - } - Choice { - origin: best.origin, - t: best.t, - expected: best.expected, - rate: best.rate, - explored, - probs, - matched: offer.suffix_match, - agrees: offer.suffix_agrees, - } - } - - // ---- learning --------------------------------------------------------------------------------------------- - - /// `accepted` of the `t-1` offered rows were accepted; `round_ms` is the whole round (verify, commit, emit, draft, - /// adaptation) and `drafts_after` the MTP drafts that round's chain produced. - pub fn observe(&mut self, c: &Choice, accepted: usize, round_ms: f64, drafts_after: usize) { - self.rounds += 1; - let tested = (accepted + 1).min(c.t - 1); - let (decay, eta) = (self.cfg.decay, self.cfg.bias_rate); - for j in 1..=tested { - let hit = j <= accepted; - match c.origin { - Origin::Mtp => { - let p = c.probs[j - 1]; - let b = p_bucket(p); - let predicted = self.mtp_rate(j, p); - self.mtp_bucket[b].add(hit, decay); - self.mtp_depth[j.min(MAX_T - 1)][b].add(hit, decay); - self.bias_mtp = (self.bias_mtp + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5); - } - Origin::Suffix => { - let (cl, m) = (c.agrees as usize ^ 1, m_bucket(c.matched)); - let predicted = self.suffix_row_rate(j, c.matched, c.agrees); - if j == 1 { - self.suf_first[cl][m].add(hit, decay) - } else { - self.suf_cont[cl][m].add(hit, decay) - } - self.bias_suf[cl] = (self.bias_suf[cl] + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5); - } - } - } - // the bias fades back to the cell statistics - self.bias_mtp *= 0.995; - for b in &mut self.bias_suf { - *b *= 0.995; - } - if round_ms.is_finite() && round_ms > 0.0 { - let y = (round_ms - self.cfg.draft_step_ms * drafts_after as f64).max(1.0); - let t = c.t.clamp(1, MAX_T); - // a probe that came out clearly cheaper than the model said: the machine is in another state, look further now - if c.explored && y < 0.9 * self.window_ms(t) { - self.since_explore = u64::MAX / 2; - } - if self.cost_n[t] <= 0.0 { - self.cost[t] = y; - } else { - let m = self.cost[t]; - let w = if self.cost_n[t] < 3.0 { 0.35 } else { self.cfg.cost_alpha }; - let yc = y.clamp(0.6 * m, 1.8 * m); - self.cost[t] = m + w * (yc - m); - // a change of the machine's state (tier hit rate, CPU leg, context) moves every width: the other - // widths follow part of the way so they are not judged by stale numbers - let ratio = yc / m; - for u in 1..=MAX_T { - if u != t && self.cost_n[u] > 0.0 { - self.cost[u] *= 1.0 + 0.5 * w * (ratio - 1.0); - } - } - } - self.cost_n[t] += 1.0; - self.seen[t] = self.rounds; - let x = (t - 1) as f64; - let f = &mut self.fitstat; - for v in f.iter_mut() { - *v *= 0.97; - } - f[0] += 1.0; - f[1] += x; - f[2] += x * x; - f[3] += y; - f[4] += x * y; - f[5] += y / (1.0 + PRIOR_SLOPE * x); - } - self.drafts_ewma += 0.1 * (drafts_after as f64 - self.drafts_ewma); - self.hold_t = (c.t as f64).max(self.hold_t * 0.92); - let surv = if c.t > 1 { (c.expected - self.expected_without_last(c)).clamp(0.0, 1.0) } else { 0.0 }; - if c.t > 1 { - self.survive_ewma += 0.1 * (surv - self.survive_ewma); - } - self.rate_ewma = if self.rate_ewma > 0.0 { self.rate_ewma + 0.1 * (c.rate - self.rate_ewma) } else { c.rate }; - if round_ms.is_finite() && round_ms > 0.0 { - self.meas_tok = 0.95 * self.meas_tok + (accepted + 1) as f64; - self.meas_ms = 0.95 * self.meas_ms + round_ms; - } - self.last = Some((c.origin, c.t)); - } - /// E of the chosen window without its last row (`expected` is a prefix sum of the cumulative acceptances). - pub(super) fn expected_without_last(&self, c: &Choice) -> f64 { - let (mut e, mut cum) = (1.0, 1.0); - for j in 1..c.t - 1 { - cum *= match c.origin { - Origin::Mtp => self.mtp_rate(j, c.probs[j - 1]), - Origin::Suffix => self.suffix_row_rate(j, c.matched, c.agrees), - }; - e += cum; - } - e - } - - // ---- next draft chain ------------------------------------------------------------------------------------- - - /// The calibrated acceptance a further draft must promise to be worth producing: `rate * (row_q * row slope + chain step) / survival` (see `draft_plan`). - pub fn bar(&self) -> f64 { - let rate = if self.cfg.measured_rate && self.meas_ms > 0.0 { - self.meas_tok / self.meas_ms - } else if self.rate_ewma > 0.0 { - self.rate_ewma - } else { - 0.04 - }; - (rate * (self.cfg.row_q * self.row_slope_ms() + self.cfg.draft_step_ms) / self.survive_ewma.max(0.2)) - .clamp(0.0, 0.99) - } - - /// How deep the next MTP chain should go and the draft probability below which it stops. A chain step costs - /// `draft_step_ms`; a verified row costs `row_slope_ms` and is worth it when `survival * a / slope` beats the current - /// tokens-per-ms, so the floor is the smallest draft probability whose calibrated acceptance clears that bar. - pub fn draft_plan(&self) -> DraftPlan { - let max_drafts = ((self.hold_t.ceil() as usize).max(2)).min(self.cfg.max_drafts.max(1)); - let a_req = self.bar(); - let rates: [f64; P_BUCKETS] = - std::array::from_fn(|b| sigmoid(logit(self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + self.bias_mtp)); - let mut min_p = self.cfg.min_p_hi; - if self.cfg.smooth_floor { - // the smallest p at which the calibrated acceptance (linear between the bucket centres) reaches the bar - let centre = |b: usize| -> f64 { - if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 } - }; - let mut found = None; - for b in 0..P_BUCKETS { - if rates[b] >= a_req { - found = Some(if b == 0 { - 0.0 - } else { - let (c0, c1, r0, r1) = (centre(b - 1), centre(b), rates[b - 1], rates[b]); - c0 + (c1 - c0) * ((a_req - r0) / (r1 - r0).max(1e-9)).clamp(0.0, 1.0) - }); - break; - } - } - if let Some(p) = found { - min_p = p as f32; - } - } else { - for b in 0..P_BUCKETS { - if rates[b] >= a_req { - min_p = P_EDGES[b]; - break; - } - } - } - DraftPlan { max_drafts, min_p: min_p.clamp(self.cfg.min_p_lo, self.cfg.min_p_hi) } - } } diff --git a/crates/engine-core/src/spec/adaptive/impl_specstats.rs b/crates/engine-core/src/spec/adaptive/impl_specstats.rs index 0d795365..1f05ffe2 100644 --- a/crates/engine-core/src/spec/adaptive/impl_specstats.rs +++ b/crates/engine-core/src/spec/adaptive/impl_specstats.rs @@ -24,7 +24,8 @@ impl SpecStats { ) .collect(); format!( - "rounds={} tokens={} tok_per_round={:.3} lookup_rounds={} explored={} accepted={}/{} round_ms={:.2} T_hist[0..={}]={} acc_hist={} ms_by_T={} healed={}", + "rounds={} tokens={} tok_per_round={:.3} lookup_rounds={} explored={} accepted={}/{} round_ms={:.2} \ + T_hist[0..={}]={} acc_hist={} ms_by_T={} healed={}", self.rounds, self.tokens, self.tokens as f64 / self.rounds.max(1) as f64, diff --git a/crates/engine-core/src/spec/adaptive/learn.rs b/crates/engine-core/src/spec/adaptive/learn.rs new file mode 100644 index 00000000..6418b96b --- /dev/null +++ b/crates/engine-core/src/spec/adaptive/learn.rs @@ -0,0 +1,133 @@ +//! What one finished round teaches the policy: the acceptance cells and biases, the per-width costs and the fit +//! through them, and the running rates the next draft chain is judged by. + +#[allow(unused_imports)] +use super::*; + +impl AdaptivePolicy { + /// The row `j` (1-based) of an MTP window: its draft probability's cell and the global bias learn the outcome. + fn learn_mtp_row(&mut self, c: &Choice, j: usize, hit: bool) { + let (decay, eta) = (self.cfg.decay, self.cfg.bias_rate); + let p = c.probs[j - 1]; + let b = p_bucket(p); + let predicted = self.mtp_rate(j, p); + self.mtp_bucket[b].add(hit, decay); + self.mtp_depth[j.min(MAX_T - 1)][b].add(hit, decay); + self.bias_mtp = (self.bias_mtp + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5); + } + + /// The row `j` (1-based) of a suffix window: the cell of the match length and the class bias learn the outcome. + fn learn_suffix_row(&mut self, c: &Choice, j: usize, hit: bool) { + let (decay, eta) = (self.cfg.decay, self.cfg.bias_rate); + let (cl, m) = (c.agrees as usize ^ 1, m_bucket(c.matched)); + let predicted = self.suffix_row_rate(j, c.matched, c.agrees); + if j == 1 { + self.suf_first[cl][m].add(hit, decay) + } else { + self.suf_cont[cl][m].add(hit, decay) + } + self.bias_suf[cl] = (self.bias_suf[cl] + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5); + } + + /// Learn the outcome of every tested row of the window, then let the biases fade back to the cell statistics. + fn learn_rows(&mut self, c: &Choice, accepted: usize) { + let tested = (accepted + 1).min(c.t - 1); + for j in 1..=tested { + let hit = j <= accepted; + match c.origin { + Origin::Mtp => self.learn_mtp_row(c, j, hit), + Origin::Suffix => self.learn_suffix_row(c, j, hit), + } + } + self.bias_mtp *= 0.995; + for b in &mut self.bias_suf { + *b *= 0.995; + } + } + + /// Fold the measured window cost `y` (ms) of width `t` into the per-width mean. A change of the machine's state + /// (tier hit rate, CPU leg, context) moves every width: the other widths follow part of the way so they are not + /// judged by stale numbers. + fn learn_width_cost(&mut self, t: usize, y: f64) { + if self.cost_n[t] <= 0.0 { + self.cost[t] = y; + return; + } + let m = self.cost[t]; + let w = if self.cost_n[t] < 3.0 { 0.35 } else { self.cfg.cost_alpha }; + let yc = y.clamp(0.6 * m, 1.8 * m); + self.cost[t] = m + w * (yc - m); + let ratio = yc / m; + for u in 1..=MAX_T { + if u != t && self.cost_n[u] > 0.0 { + self.cost[u] *= 1.0 + 0.5 * w * (ratio - 1.0); + } + } + } + + /// Add the point `(t - 1, y)` to the decayed sums of the line fit. + fn learn_fit(&mut self, t: usize, y: f64) { + let x = (t - 1) as f64; + let f = &mut self.fitstat; + for v in f.iter_mut() { + *v *= 0.97; + } + f[0] += 1.0; + f[1] += x; + f[2] += x * x; + f[3] += y; + f[4] += x * y; + f[5] += y / (1.0 + PRIOR_SLOPE * x); + } + + /// The whole round took `round_ms`; its window cost is that less the chain steps. + fn learn_cost(&mut self, c: &Choice, round_ms: f64, drafts_after: usize) { + let y = (round_ms - self.cfg.draft_step_ms * drafts_after as f64).max(1.0); + let t = c.t.clamp(1, MAX_T); + // a probe that came out clearly cheaper than the model said: the machine is in another state, look further + // now + if c.explored && y < 0.9 * self.window_ms(t) { + self.since_explore = u64::MAX / 2; + } + self.learn_width_cost(t, y); + self.cost_n[t] += 1.0; + self.seen[t] = self.rounds; + self.learn_fit(t, y); + } + + /// `accepted` of the `t-1` offered rows were accepted; `round_ms` is the whole round (verify, commit, emit, draft, + /// adaptation) and `drafts_after` the MTP drafts that round's chain produced. + pub fn observe(&mut self, c: &Choice, accepted: usize, round_ms: f64, drafts_after: usize) { + self.rounds += 1; + self.learn_rows(c, accepted); + let timed = round_ms.is_finite() && round_ms > 0.0; + if timed { + self.learn_cost(c, round_ms, drafts_after); + } + self.drafts_ewma += 0.1 * (drafts_after as f64 - self.drafts_ewma); + self.hold_t = (c.t as f64).max(self.hold_t * 0.92); + if c.t > 1 { + let surv = (c.expected - self.expected_without_last(c)).clamp(0.0, 1.0); + self.survive_ewma += 0.1 * (surv - self.survive_ewma); + } + self.rate_ewma = if self.rate_ewma > 0.0 { self.rate_ewma + 0.1 * (c.rate - self.rate_ewma) } else { c.rate }; + if timed { + self.meas_tok = 0.95 * self.meas_tok + (accepted + 1) as f64; + self.meas_ms = 0.95 * self.meas_ms + round_ms; + } + self.last = Some((c.origin, c.t)); + } + + /// E of the chosen window without its last row (`expected` is a prefix sum of the cumulative acceptances). + pub(super) fn expected_without_last(&self, c: &Choice) -> f64 { + let (mut e, mut cum) = (1.0, 1.0); + for j in 1..c.t - 1 { + cum *= match c.origin { + Origin::Mtp => self.mtp_rate(j, c.probs[j - 1]), + Origin::Suffix => self.suffix_row_rate(j, c.matched, c.agrees), + }; + e += cum; + } + e + } +} diff --git a/crates/engine-core/src/spec/adaptive/tests.rs b/crates/engine-core/src/spec/adaptive/tests.rs index 8c913d4e..5e23d40c 100644 --- a/crates/engine-core/src/spec/adaptive/tests.rs +++ b/crates/engine-core/src/spec/adaptive/tests.rs @@ -143,7 +143,8 @@ fn cfg() -> AdaptiveConfig { AdaptiveConfig::new(8, 7) } -/// The earlier rule, kept as the reference: the floor is the lower edge of the first bucket whose calibrated acceptance clears the bar. +/// The earlier rule, kept as the reference: the floor is the lower edge of the first bucket whose calibrated acceptance +/// clears the bar. fn legacy_plan(pol: &AdaptivePolicy) -> DraftPlan { let max_drafts = ((pol.hold_t.ceil() as usize).max(2)).min(pol.cfg.max_drafts.max(1)); let rate = if pol.rate_ewma > 0.0 { pol.rate_ewma } else { 0.04 }; 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 2b1fbb9c..55c0513f 100644 --- a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs +++ b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly, the_smooth_floor_moves_continuously_with_the_bar, a_trace_is_reproducible, stats_line_reports_the_histograms. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly, +//! the_smooth_floor_moves_continuously_with_the_bar, a_trace_is_reproducible, stats_line_reports_the_histograms. #[allow(unused_imports)] use super::*; 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 52625861..a94034a2 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 @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): stationary_regimes_reach_the_best_fixed_width, it_widens_when_rows_are_cheap_and_narrows_when_they_are_not, it_follows_a_change_of_content_and_of_cost, reaction_to_a_switch_takes_tens_of_rounds_not_hundreds .... +//! Tests of tests by topic (moved out of the test file by STRA-338): stationary_regimes_reach_the_best_fixed_width, +//! it_widens_when_rows_are_cheap_and_narrows_when_they_are_not, it_follows_a_change_of_content_and_of_cost, +//! reaction_to_a_switch_takes_tens_of_rounds_not_hundreds .... #[allow(unused_imports)] use super::*; diff --git a/crates/engine-core/src/spec/policy.rs b/crates/engine-core/src/spec/policy.rs index f02684ef..01519986 100644 --- a/crates/engine-core/src/spec/policy.rs +++ b/crates/engine-core/src/spec/policy.rs @@ -224,6 +224,15 @@ impl CostController { best } } + /// The row `i` of a window was accepted (`hit` 1) or not (0): move the estimate of its source toward it. + fn learn_row(&mut self, source: Source, i: usize, hit: f64, matched: usize) { + if source == Source::Mtp { + self.mtp_p[i] += self.ema * (hit - self.mtp_p[i]); + } else { + let b = Self::bucket(matched); + self.lookup_q[b] += self.ema * (hit - self.lookup_q[b]); + } + } pub fn observe(&mut self, c: Choice, accepted: usize, matched: usize) -> Result<()> { if c.source == Source::None || c.k == 0 { return Ok(()); @@ -233,13 +242,7 @@ impl CostController { } let a = accepted.min(c.k); for i in 0..c.k.min(a + 1) { - let hit = if i < a { 1.0 } else { 0.0 }; - if c.source == Source::Mtp { - self.mtp_p[i] += self.ema * (hit - self.mtp_p[i]); - } else { - let b = Self::bucket(matched); - self.lookup_q[b] += self.ema * (hit - self.lookup_q[b]); - } + self.learn_row(c.source, i, if i < a { 1.0 } else { 0.0 }, matched); } if c.source == Source::Mtp && a == c.k && c.k < 8 { for i in c.k..8 { diff --git a/crates/engine-fake/src/lib.rs b/crates/engine-fake/src/lib.rs index 11f37675..24ca1f90 100644 --- a/crates/engine-fake/src/lib.rs +++ b/crates/engine-fake/src/lib.rs @@ -1,5 +1,6 @@ -//! The scripted engine as an [`EngineFamily`], so the composition root starts it exactly as it starts the product engine -//! (`spawn::`) and a test drives everything above the engine without a GPU, a model or a gRPC server. +//! The scripted engine as an [`EngineFamily`], so the composition root starts it exactly as it starts the product +//! engine (`spawn::`) and a test drives everything above the engine without a GPU, a model or a gRPC +//! server. //! //! It computes nothing and makes no statement about any model: what it returns is what the test scripted through the //! [`ScriptedHandle`] it receives at start-up. diff --git a/crates/leleka-memory/examples/swap_ab.rs b/crates/leleka-memory/examples/swap_ab.rs index b20a0a1d..9c321b33 100644 --- a/crates/leleka-memory/examples/swap_ab.rs +++ b/crates/leleka-memory/examples/swap_ab.rs @@ -1,10 +1,11 @@ //! A/B of the memfd residency guard under real memory pressure, model-free. Run it inside a cgroup v2 with `memory.max` -//! below `memfd + hog` (the harness script `scripts/memory/swap_ab.sh` does that and restricts the damage to the cgroup): a -//! sealed memfd stands in for the 55 GB KAR archive, an anonymous "hog" for the expert bank, and a reader streams a big -//! file through the page cache like the Original did next to the memfd. +//! below `memfd + hog` (the harness script `scripts/memory/swap_ab.sh` does that and restricts the damage to the +//! cgroup): a sealed memfd stands in for the 55 GB KAR archive, an anonymous "hog" for the expert bank, and a reader +//! streams a big file through the page cache like the Original did next to the memfd. //! //! ```text -//! swap_ab --memfd-mib 6144 --hog-mib 5120 --secs 60 [--reader FILE] [--lock off|try|require] [--heal 0|1] [--hog-release SECS] +//! swap_ab --memfd-mib 6144 --hog-mib 5120 --secs 60 [--reader FILE] [--lock off|try|require] [--heal 0|1] +//! [--hog-release SECS] //! ``` //! Prints one line per second (`AB t=.. memfd_swapped_mib=.. ...`) and a final `AB-RESULT` line. #![allow(unsafe_code)] diff --git a/crates/leleka-memory/src/census.rs b/crates/leleka-memory/src/census.rs index f7c1b162..225c5064 100644 --- a/crates/leleka-memory/src/census.rs +++ b/crates/leleka-memory/src/census.rs @@ -11,7 +11,8 @@ use serde::Serialize; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] pub struct Census { pub rss: u64, - /// `RssAnon` / `RssFile` / `RssShmem` of `/proc/self/status`: a leak is an anonymous or shmem slope; file pages are reclaimable. + /// `RssAnon` / `RssFile` / `RssShmem` of `/proc/self/status`: a leak is an anonymous or shmem slope; file pages are + /// reclaimable. pub rss_anon: u64, pub rss_file: u64, pub rss_shmem: u64, @@ -126,34 +127,34 @@ fn quarter_means(values: &[f64]) -> Option<(f64, f64)> { Some((mean(&values[..q]), mean(&values[values.len() - q..]))) } +/// How a series drifted: the means of its first and last quarter; a series too short to judge is not ok. `None` for a +/// device series that is absent (no GPU). +fn drift_of(name: &'static str, values: &[f64], tolerance: u64) -> Option { + if values.is_empty() && name.starts_with("device") { + return None; + } + Some(match quarter_means(values) { + Some((a, b)) => Drift { + series: name, + first_quarter_mean: a, + last_quarter_mean: b, + growth: b - a, + tolerance, + ok: b - a <= tolerance as f64, + }, + None => { + Drift { series: name, first_quarter_mean: 0.0, last_quarter_mean: 0.0, growth: 0.0, tolerance, ok: false } + } + }) +} + /// Judge a series of censuses taken between requests. Fewer than 8 post-warm-up samples is not a judgement: not ok. pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatReport { let tail = series.get(warmup..).unwrap_or(&[]); let mut drifts = Vec::new(); let mut add = |name: &'static str, get: &dyn Fn(&Census) -> Option, tolerance: u64| { let values: Vec = tail.iter().filter_map(get).collect(); - if values.is_empty() && name.starts_with("device") { - return; - } - let drift = match quarter_means(&values) { - Some((a, b)) => Drift { - series: name, - first_quarter_mean: a, - last_quarter_mean: b, - growth: b - a, - tolerance, - ok: b - a <= tolerance as f64, - }, - None => Drift { - series: name, - first_quarter_mean: 0.0, - last_quarter_mean: 0.0, - growth: 0.0, - tolerance, - ok: false, - }, - }; - drifts.push(drift); + drifts.extend(drift_of(name, &values, tolerance)); }; add("rss", &|c| Some(c.rss as f64), tol.rss); add("swap", &|c| Some(c.swap as f64), tol.swap); @@ -167,8 +168,9 @@ pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatRep FlatReport { samples: series.len(), warmup, drifts, ok } } -/// An ordinary-least-squares line through `(x, y)` with its 95% confidence interval, and the Theil-Sen slope (the median of the -/// pairwise slopes: robust against the steps a cache filling or a request in flight puts into a memory series). +/// An ordinary-least-squares line through `(x, y)` with its 95% confidence interval, and the Theil-Sen slope (the +/// median of the pairwise slopes: robust against the steps a cache filling or a request in flight puts into a memory +/// series). #[derive(Clone, Copy, Debug, PartialEq, Serialize)] pub struct SlopeFit { pub n: usize, @@ -187,9 +189,25 @@ impl SlopeFit { } } -/// Fit `y` against `x`; `None` with fewer than 8 points or no spread in `x`. The interval uses the normal quantile 1.96 (n is in the -/// hundreds) and treats samples as independent, which a slowly drifting series is not: read it as a lower bound of the uncertainty and -/// look at `theil_sen` next to it. +/// The Theil-Sen slope: the median of the pairwise slopes (robust against steps in the series). +fn theil_sen(points: &[(f64, f64)]) -> f64 { + let n = points.len(); + let mut slopes = Vec::with_capacity(n * (n - 1) / 2); + for i in 0..n { + for j in i + 1..n { + let dx = points[j].0 - points[i].0; + if dx != 0.0 { + slopes.push((points[j].1 - points[i].1) / dx); + } + } + } + slopes.sort_by(f64::total_cmp); + slopes.get(slopes.len() / 2).copied().unwrap_or(0.0) +} + +/// Fit `y` against `x`; `None` with fewer than 8 points or no spread in `x`. The interval uses the normal quantile 1.96 +/// (n is in the hundreds) and treats samples as independent, which a slowly drifting series is not: read it as a lower +/// bound of the uncertainty and look at `theil_sen` next to it. pub fn fit_slope(points: &[(f64, f64)]) -> Option { let n = points.len(); if n < 8 { @@ -207,23 +225,12 @@ pub fn fit_slope(points: &[(f64, f64)]) -> Option { let sse: f64 = points.iter().map(|p| (p.1 - intercept - slope * p.0).powi(2)).sum(); let syy: f64 = points.iter().map(|p| (p.1 - my).powi(2)).sum(); let se = (sse / (nf - 2.0) / sxx).sqrt(); - let mut slopes = Vec::with_capacity(n * (n - 1) / 2); - for i in 0..n { - for j in i + 1..n { - let dx = points[j].0 - points[i].0; - if dx != 0.0 { - slopes.push((points[j].1 - points[i].1) / dx); - } - } - } - slopes.sort_by(f64::total_cmp); - let theil_sen = slopes.get(slopes.len() / 2).copied().unwrap_or(0.0); Some(SlopeFit { n, slope, ci95_low: slope - 1.96 * se, ci95_high: slope + 1.96 * se, - theil_sen, + theil_sen: theil_sen(points), r2: if syy > 0.0 { 1.0 - sse / syy } else { 0.0 }, }) } diff --git a/crates/leleka-memory/src/governor.rs b/crates/leleka-memory/src/governor.rs index b199677c..1a28d28a 100644 --- a/crates/leleka-memory/src/governor.rs +++ b/crates/leleka-memory/src/governor.rs @@ -106,8 +106,8 @@ pub struct LockReport { pub decision: LockDecision, pub outcome: LockOutcome, pub mapping_bytes: u64, - /// A sparse archive (a memfd that holds only the extents the serve path reads): the bytes of those extents, which is what is - /// locked, healed and counted; `None` for a full archive, where it is `mapping_bytes`. + /// A sparse archive (a memfd that holds only the extents the serve path reads): the bytes of those extents, which + /// is what is locked, healed and counted; `None` for a full archive, where it is `mapping_bytes`. pub extent_bytes: Option, pub memlock_soft: Option, pub memlock_hard: Option, @@ -118,7 +118,8 @@ pub struct LockReport { struct Guarded { mapping: crate::lock::FdMapping, report: LockReport, - /// The extents of a sparse archive; `None` = the whole mapping is data. The heal cursor then walks their concatenation. + /// The extents of a sparse archive; `None` = the whole mapping is data. The heal cursor then walks their + /// concatenation. extents: Option>, cursor: u64, last_swapped: u64, @@ -127,6 +128,20 @@ struct Guarded { last: Option, } +/// Windows: when the working set was last trimmed (`NONE` = never), when that was last logged, and how many trims +/// happened. +struct TrimStats { + last_ms: AtomicU64, + last_log_ms: AtomicU64, + count: AtomicU64, +} + +impl TrimStats { + fn new() -> Self { + Self { last_ms: AtomicU64::new(NONE), last_log_ms: AtomicU64::new(0), count: AtomicU64::new(0) } + } +} + struct Inner { cfg: GovernorConfig, src: Arc, @@ -143,10 +158,7 @@ struct Inner { prefix_target: AtomicU64, prefix_used: AtomicU64, last_shed_ms: AtomicU64, - /// Windows: when the working set was last trimmed (`NONE` = never), when that was last logged, and how many trims happened. - last_trim_ms: AtomicU64, - last_trim_log_ms: AtomicU64, - trims: AtomicU64, + trim: TrimStats, since_ms: AtomicU64, transitions: Mutex>, counters: Counters, diff --git a/crates/leleka-memory/src/governor/impl_governor.rs b/crates/leleka-memory/src/governor/impl_governor.rs index 4307ee54..af092353 100644 --- a/crates/leleka-memory/src/governor/impl_governor.rs +++ b/crates/leleka-memory/src/governor/impl_governor.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +mod archive_guard; mod impl_governor_2; mod impl_governor_2_2; mod impl_governor_3; diff --git a/crates/leleka-memory/src/governor/impl_governor/archive_guard.rs b/crates/leleka-memory/src/governor/impl_governor/archive_guard.rs new file mode 100644 index 00000000..62e5d6ed --- /dev/null +++ b/crates/leleka-memory/src/governor/impl_governor/archive_guard.rs @@ -0,0 +1,268 @@ +//! The steps of guarding a sealed KAR memfd (map it, decide and attempt the lock, report; read the swap state and heal +//! it), split out of [`Governor::guard_archive_extents`] and [`Governor::residency_tick`]. +#![cfg(all(target_os = "linux", target_pointer_width = "64"))] + +#[allow(unused_imports)] +use super::*; +use crate::lock::{FdMapping, Residency, Span, compact_piece, raise_memlock_soft, spans_bytes}; + +/// What every lock report of one `guard_archive_extents` call shares. +pub(super) struct ReportBase { + pub(super) mode: LockMode, + pub(super) started: Instant, + pub(super) memlock: Option<(u64, u64)>, + pub(super) extent_bytes: Option, +} + +/// A refusal with the `memlock` code. +fn memlock_refusal(message: String, numbers: Vec<(String, u64)>, advice: Vec) -> Refusal { + Refusal { code: "memlock", message, numbers, advice } +} + +/// The extents of a sparse archive must lie inside the `len`-byte descriptor. +pub(super) fn check_extents(extents: Option<&[Span]>, len: u64) -> Result<(), Refusal> { + if let Some(spans) = extents + && let Err(why) = crate::lock::check_spans(spans, len) + { + let message = format!("the sparse archive extents are invalid: {why}"); + return Err(memlock_refusal(message, vec![("archive".to_owned(), len)], vec![])); + } + Ok(()) +} + +/// Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a +/// shared mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a +/// read-only description can never become writable, so the mapping is allowed everywhere and is immutable by +/// construction. +pub(super) fn map_readonly_archive(fd: std::os::fd::BorrowedFd<'_>, len: u64) -> std::io::Result { + use std::os::fd::{AsFd as _, AsRawFd as _}; + let path = format!("/proc/self/fd/{}", fd.as_raw_fd()); + let file = std::fs::OpenOptions::new() + .read(true) + .open(path) + .map_err(|e| std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}")))?; + FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) +} + +/// The refusal of `LELEKA_MEMORY_LOCK=require` when the archive could not be locked. +pub(super) fn require_refusal(decision: &LockDecision, outcome: &LockOutcome, resident: u64) -> Refusal { + let (numbers, advice) = match decision { + LockDecision::Insufficient { need, soft, hard, advice } => ( + vec![ + ("needed to lock".to_owned(), *need), + ("RLIMIT_MEMLOCK soft".to_owned(), *soft), + ("RLIMIT_MEMLOCK hard".to_owned(), *hard), + ], + advice.clone(), + ), + _ => (vec![("archive".to_owned(), resident)], vec![]), + }; + let message = format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"); + memlock_refusal(message, numbers, advice) +} + +impl Guarded { + /// The guard of a freshly locked archive: nothing swapped, nothing healed yet. + pub(super) fn new(mapping: FdMapping, report: LockReport, extents: Option<&[Span]>) -> Self { + Self { + mapping, + report, + extents: extents.map(<[_]>::to_vec), + cursor: 0, + last_swapped: 0, + warned_swapped: 0, + last_check: None, + last: None, + } + } +} + +impl Governor { + /// The report of a lock attempt that mapped `mapping_bytes` of the archive. + pub(super) fn lock_report( + &self, + base: &ReportBase, + decision: LockDecision, + outcome: LockOutcome, + mapping_bytes: u64, + ) -> LockReport { + LockReport { + mode: base.mode, + decision, + outcome, + mapping_bytes, + extent_bytes: base.extent_bytes, + memlock_soft: base.memlock.map(|m| m.0), + memlock_hard: base.memlock.map(|m| m.1), + millis: self.inner.clock.since(base.started).as_secs_f64() * 1e3, + } + } + + /// The archive could not be mapped: report it, and refuse when the lock is required. + pub(super) fn unmapped_archive( + &self, + base: &ReportBase, + decision: LockDecision, + e: &std::io::Error, + ) -> Result { + let outcome = LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }; + let report = self.lock_report(base, decision, outcome, 0); + self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); + if base.mode == LockMode::Require { + return Err(memlock_refusal(format!("mmap of the archive failed: {e}"), vec![], vec![])); + } + Ok(report) + } + + /// Act on the lock decision: do nothing, say why the lock cannot cover the archive, or lock it. + pub(super) fn apply_decision( + &self, + decision: &LockDecision, + mapping: &mut FdMapping, + extents: Option<&[Span]>, + resident: u64, + ) -> LockOutcome { + match decision { + LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, + LockDecision::Insufficient { need, soft, hard, advice } => { + self.insufficient_outcome(resident, (*need, *soft, *hard), advice) + } + LockDecision::Attempt { raise_soft_to } => self.attempt_lock(mapping, extents, *raise_soft_to, resident), + } + } + + /// `RLIMIT_MEMLOCK` cannot cover the archive: the archive stays swappable, and the log says how to change that. + fn insufficient_outcome(&self, resident: u64, limits: (u64, u64, u64), advice: &[String]) -> LockOutcome { + let (need, soft, hard) = limits; + let hard_text = if hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }; + let why = + format!("RLIMIT_MEMLOCK soft {} MiB / hard {hard_text} MiB cannot cover {} MiB", soft >> 20, need >> 20); + self.log(&format!( + "WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", + gib(resident), + advice.join(" | ") + )); + LockOutcome::NotAttempted { why } + } + + /// `mlock` the archive (or only its extents) chunk by chunk and log the outcome. + fn attempt_lock( + &self, + mapping: &mut FdMapping, + extents: Option<&[Span]>, + raise_soft_to: Option, + len: u64, + ) -> LockOutcome { + if let Some(to) = raise_soft_to + && let Err(e) = raise_memlock_soft(to) + { + self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); + } + let policy = self.policy(); + let swapped = self.mapping_swapped(mapping).unwrap_or(0); + let src = self.inner.src.clone(); + let allow = |n: u64| { + // a swapped-out chunk is read back into RAM: keep the hard floor + reserve + let need = if swapped > 0 { n } else { 0 }; + let floor = policy.hard_floor + policy.reserve; + src.facts().effective_available().is_none_or(|a| a.saturating_sub(need) >= floor) + }; + let outcome = match extents { + Some(spans) => mapping.lock_ranges(spans, GIB, allow), + None => mapping.lock(GIB, allow), + }; + self.log_lock_outcome(&outcome, len); + outcome + } + + fn log_lock_outcome(&self, outcome: &LockOutcome, len: u64) { + match outcome { + LockOutcome::Locked { bytes } => { + self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))) + } + LockOutcome::Partial { locked, why, .. } => { + self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))) + } + LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), + } + } + + /// Warn (at most once per 64 MiB step) while pages of the archive are swapped out. + pub(super) fn warn_swapped(&self, g: &mut Guarded, r: &Residency, read_ms: f64) { + if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { + g.warned_swapped = r.swapped_bytes; + let healing = if self.inner.cfg.heal { "; healing" } else { "" }; + self.log(&format!( + "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps \ + read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{healing}", + r.swapped_bytes >> 20, + gib(r.rss_bytes), + gib(r.mapping_bytes), + r.locked_bytes >> 20, + )); + } else if r.swapped_bytes < 64 * MIB { + g.warned_swapped = 0; + } + } + + /// Pull swapped pages back in, up to one tick's budget, when the host has the memory for it. + pub(super) fn heal(&self, g: &mut Guarded, r: &Residency, policy: &Policy) { + let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); + let has_room = self + .inner + .src + .facts() + .effective_available() + .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); + if !has_room { + return; + } + let done = match g.extents.clone() { + Some(spans) => heal_extents(g, &spans, budget), + None => heal_whole(g, budget), + }; + self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); + self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); + } +} + +/// Populate a sparse archive: walk the concatenation of the extents, never a hole. Returns the bytes populated. +fn heal_extents(g: &mut Guarded, spans: &[Span], budget: u64) -> u64 { + let total = spans_bytes(spans); + let mut done = 0; + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let want = (256 * MIB).min(budget - done); + let Some((offset, piece)) = compact_piece(spans, g.cursor, want) else { + break; + }; + // whole pages; the last page of the last extent may be partial and is rounded up by the kernel + let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; + if g.mapping.populate(offset, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + done +} + +/// Populate a full archive page by page from the cursor. Returns the bytes populated. +fn heal_whole(g: &mut Guarded, budget: u64) -> u64 { + let total = g.mapping.len(); + let mut done = 0; + while done < budget && done < total { + if g.cursor >= total { + g.cursor = 0; + } + let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; + if n == 0 || g.mapping.populate(g.cursor, n).is_err() { + break; + } + g.cursor += n; + done += n; + } + done +} diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs index 1f01e942..606ba800 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs @@ -3,6 +3,39 @@ #[allow(unused_imports)] use super::*; +impl Inner { + fn new(cfg: GovernorConfig, src: impl MemoryPressure + 'static, clock: AnyClock) -> Self { + let policy0 = cfg.policy; + Self { + monitor: Mutex::new(Monitor::new(policy0)), + policy: Mutex::new(policy0), + cfg, + src: Arc::new(src), + epoch: clock.now(), + ledger: Ledger::with_clock(clock.clone()), + clock, + plan: Mutex::new(None), + level: AtomicU8::new(Level::Normal as u8), + reason: Mutex::new("startup".into()), + available: AtomicU64::new(NONE), + sampled_at_ms: AtomicU64::new(0), + prefix_planned: AtomicU64::new(0), + prefix_target: AtomicU64::new(NONE), + prefix_used: AtomicU64::new(0), + last_shed_ms: AtomicU64::new(0), + trim: TrimStats::new(), + since_ms: AtomicU64::new(0), + transitions: Mutex::new(VecDeque::new()), + counters: Counters::default(), + vram: Mutex::new(None), + post_load: Mutex::new(None), + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + guarded: Mutex::new(None), + stop: AtomicBool::new(false), + } + } +} + impl Governor { pub fn new(cfg: GovernorConfig, src: Arc) -> Self { Self::with_parts(cfg, ProcPressure(src), AnyClock::System) @@ -15,39 +48,7 @@ impl Governor { /// A governor over any [`MemoryPressure`] and any clock: the composition root, and the way a test scripts both. pub fn with_parts(cfg: GovernorConfig, pressure: impl MemoryPressure + 'static, clock: AnyClock) -> Self { - let policy0 = cfg.policy; - let monitor = Monitor::new(policy0); - Self { - inner: Arc::new(Inner { - cfg, - src: Arc::new(pressure), - epoch: clock.now(), - ledger: Ledger::with_clock(clock.clone()), - clock, - plan: Mutex::new(None), - monitor: Mutex::new(monitor), - policy: Mutex::new(policy0), - level: AtomicU8::new(Level::Normal as u8), - reason: Mutex::new("startup".into()), - available: AtomicU64::new(NONE), - sampled_at_ms: AtomicU64::new(0), - prefix_planned: AtomicU64::new(0), - prefix_target: AtomicU64::new(NONE), - prefix_used: AtomicU64::new(0), - last_shed_ms: AtomicU64::new(0), - last_trim_ms: AtomicU64::new(NONE), - last_trim_log_ms: AtomicU64::new(0), - trims: AtomicU64::new(0), - since_ms: AtomicU64::new(0), - transitions: Mutex::new(VecDeque::new()), - counters: Counters::default(), - vram: Mutex::new(None), - post_load: Mutex::new(None), - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - guarded: Mutex::new(None), - stop: AtomicBool::new(false), - }), - } + Self { inner: Arc::new(Inner::new(cfg, pressure, clock)) } } /// A governor over the real `/proc`. @@ -64,7 +65,8 @@ impl Governor { } /// Replace the pressure floors at run time (diagnostics and the shed tests: move the thresholds next to the memory - /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is required. + /// the host has now, so the whole shed path runs without ever approaching the real limit). `hard < soft` is + /// required. pub fn set_floors(&self, soft_floor: u64, hard_floor: u64) -> Result<(), String> { if hard_floor >= soft_floor { return Err(format!("hard floor {hard_floor} must be below the soft floor {soft_floor}")); @@ -115,8 +117,8 @@ impl Governor { // ---- plan ------------------------------------------------------------------------------------------------- - /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and keep - /// the plan for the report. + /// Plan the budget (or refuse), log the plan, register the expected size of every fixed item in the inventory and + /// keep the plan for the report. pub fn startup(&self, input: &crate::plan::PlanInput) -> Result { let plan = match crate::plan::plan(input) { Ok(plan) => plan, @@ -125,22 +127,29 @@ impl Governor { return Err(refusal); } }; + self.register_planned_items(&plan); + self.log_budget(&plan); + for note in &plan.notes { + self.log(&format!("note: {note}")); + } + self.set_plan(plan.clone()); + Ok(plan) + } + + /// Every fixed item of the plan goes into the inventory with its expected size. + fn register_planned_items(&self, plan: &Plan) { let inv = self.inventory(); for item in &plan.fixed { - inv.set( - crate::inventory::Entry::new( - "planned", - &item.name, - item.space, - crate::inventory::When::Startup, - &item.formula, - ) - .expected(item.bytes) - .swappable(false), - ); + let when = crate::inventory::When::Startup; + let entry = crate::inventory::Entry::new("planned", &item.name, item.space, when, &item.formula); + inv.set(entry.expected(item.bytes).swappable(false)); } + } + + fn log_budget(&self, plan: &Plan) { self.log(&format!( - "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", + "budget: available {} - fixed {} - memfd to create {} = {} after the fixed footprint; floors soft {} / \ + hard {}; elastic {}: resident complement {}, prefix cache {}, conversation checkpoints {} ({}){}", plan.available_before.map_or("unknown".into(), gib), gib(plan.fixed_bytes), gib(plan.kar_to_create), @@ -154,14 +163,10 @@ impl Governor { gib(plan.conversation_bytes), if plan.blind { "; BLIND: no memory telemetry, caches off" } else { "" } )); - for note in &plan.notes { - self.log(&format!("note: {note}")); - } - self.set_plan(plan.clone()); - Ok(plan) } - /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. + /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the + /// report. pub fn check_vram( &self, vram: crate::plan::VramFacts, @@ -183,8 +188,9 @@ impl Governor { } } - /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it matters and keep it for the - /// report (`plan_check`). Returns `actual - predicted` in bytes (negative: the footprint was bigger than planned). + /// Compare the plan's prediction with what the host really has after the stack opened, log the error when it + /// matters and keep it for the report (`plan_check`). Returns `actual - predicted` in bytes (negative: the + /// footprint was bigger than planned). pub fn note_post_load(&self, actual_available: Option) -> Option { let predicted = lock(&self.inner.plan).as_ref().and_then(|p| p.available_after_fixed)?; let actual = actual_available?; @@ -193,7 +199,9 @@ impl Governor { let error = i64::try_from(error).unwrap_or(if error < 0 { i64::MIN } else { i64::MAX }); if error.unsigned_abs() > 512 * MIB { self.log(&format!( - "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured value", + "WARNING: the startup plan predicted {} available after the fixed footprint, the host has {} after \ + the stack opened ({:+} MiB): the footprint constants are off, caches are sized from the measured \ + value", gib(predicted), gib(actual), error >> 20 @@ -220,8 +228,9 @@ impl Governor { Level::from_u8(self.inner.level.load(Ordering::Acquire)) } - /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never started): - /// a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the monitor itself. + /// The caller's own sample when the sampler thread has not delivered one for five intervals (it died, or was never + /// started): a stuck `reject` must not outlive the thread that would have lifted it, so the owner thread drives the + /// monitor itself. pub(in super::super) fn ensure_fresh(&self) { let interval = self.inner.cfg.sample_interval_ms.max(50); let now = self.now_ms(); diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs index b1a57c66..7db2af0a 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs @@ -6,84 +6,89 @@ use super::*; impl Governor { // ---- admission and shedding ------------------------------------------------------------------------------- - /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, - /// then whether its own transient memory would take the host below the hard floor. + /// The refusal of a request whose prompt and completion can never fit the pinned K/V image (a 400, not a retry). + fn refuse_context(&self, shape: &RequestShape, needed: u64) -> Admission { + self.inner.counters.rejected_context.fetch_add(1, Ordering::Relaxed); + Admission::Refuse(Refuse { + status: 400, + code: "context_length_exceeded", + message: format!( + "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} \ + tokens", + shape.prompt_tokens, shape.max_new_tokens, shape.max_context + ), + retry_after_secs: 0, + }) + } + + /// The refusal while the pressure level is `reject`, or when one request's own transient would take the host + /// below the hard floor (503 `memory_pressure` with a retry hint). + fn refuse_pressure(&self, message: String, retry_after_secs: u64) -> Admission { + self.inner.counters.rejected_pressure.fetch_add(1, Ordering::Relaxed); + Admission::Refuse(Refuse { status: 503, code: "memory_pressure", message, retry_after_secs }) + } + + /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure + /// level, then whether its own transient memory would take the host below the hard floor. pub fn admit(&self, shape: &RequestShape) -> Admission { - let c = &self.inner.counters; let needed = shape.prompt_tokens.saturating_add(shape.max_new_tokens).saturating_add(8); if needed > shape.max_context { - c.rejected_context.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 400, - code: "context_length_exceeded", - message: format!( - "the request needs {needed} tokens (prompt {} + up to {} new + 8) but the pinned K/V image holds {} tokens", - shape.prompt_tokens, shape.max_new_tokens, shape.max_context - ), - retry_after_secs: 0, - }); + return self.refuse_context(shape, needed); } self.ensure_fresh(); let level = self.level(); let retry = lock(&self.inner.monitor).retry_after_secs().max(1); if level == Level::Reject { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)), - retry_after_secs: retry, - }); + let message = format!("host memory is under pressure ({}); retry shortly", lock(&self.inner.reason)); + return self.refuse_pressure(message, retry); } - // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor + // the transient of one request (checkpoint / node state / import staging) must not take the host below the + // hard floor let transient = self.policy().reserve / 4; if let Some(available) = self.available_now() && available.saturating_sub(transient) < self.policy().hard_floor { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!( - "{} available is within {} of the hard floor {}; retry shortly", - gib(available), - gib(transient), - gib(self.policy().hard_floor) - ), - retry_after_secs: retry, - }); + let floor = gib(self.policy().hard_floor); + let message = format!( + "{} available is within {} of the hard floor {floor}; retry shortly", + gib(available), + gib(transient) + ); + return self.refuse_pressure(message, retry); } - c.admitted.fetch_add(1, Ordering::Relaxed); + self.inner.counters.admitted.fetch_add(1, Ordering::Relaxed); Admission::Admit } - /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the soft floor, hand them back to - /// the standby list (at most every 250 ms) and read the host again, so that a dip caused only by trimmable mapped pages never reaches the monitor: - /// a shed evicts prefix-cache blocks, and live runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks - /// evicted, the fourth turn re-read 223k tokens in 32 minutes). + /// Windows keeps touched mapped pages in the working set, where they count as used. When the host reads below the + /// soft floor, hand them back to the standby list (at most every 250 ms) and read the host again, so that a dip + /// caused only by trimmable mapped pages never reaches the monitor: a shed evicts prefix-cache blocks, and live + /// runs showed it firing every few seconds at the floor (laptop 256k session, 2026-10-26: 113 blocks evicted, the + /// fourth turn re-read 223k tokens in 32 minutes). pub(in super::super) fn relieve_working_set(&self, facts: HostFacts) -> HostFacts { self.relieve_working_set_below(facts, self.policy().soft_floor) } - /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs `needed` bytes of it - /// (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a floor of 9.2 GiB refused a 0.2 GiB checkpoint - /// that the very next trim would have admitted, because the periodic trim only runs below the soft floor). At most one trim per 250 ms. + /// The available memory after handing the engine's trimmable working-set pages back, for a cache owner that needs + /// `needed` bytes of it (a prefix-cache checkpoint must leave the admit floor free: a reading of 8.9 GiB against a + /// floor of 9.2 GiB refused a 0.2 GiB checkpoint that the very next trim would have admitted, because the periodic + /// trim only runs below the soft floor). At most one trim per 250 ms. pub fn available_after_relief(&self, needed: u64) -> Option { let facts = self.probe(); self.relieve_working_set_below(facts, needed).effective_available() } - pub(in super::super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { - if !cfg!(windows) { - return facts; - } - // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists + /// A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists. + fn trim_disabled() -> bool { static NO_TRIM_FILE: OnceLock> = OnceLock::new(); - if NO_TRIM_FILE + NO_TRIM_FILE .get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)) .as_ref() .is_some_and(|f| f.exists()) - { + } + + pub(in super::super) fn relieve_working_set_below(&self, facts: HostFacts, threshold: u64) -> HostFacts { + if !cfg!(windows) || Self::trim_disabled() { return facts; } let Some(available) = facts.effective_available() else { return facts }; @@ -91,32 +96,37 @@ impl Governor { return facts; } let now = self.now_ms(); - let last = self.inner.last_trim_ms.load(Ordering::Acquire); + let last = self.inner.trim.last_ms.load(Ordering::Acquire); if last != NONE && now.saturating_sub(last) < WORKING_SET_TRIM_EVERY.as_millis() as u64 { return facts; } - self.inner.last_trim_ms.store(now, Ordering::Release); + self.inner.trim.last_ms.store(now, Ordering::Release); if !crate::winproc::trim_working_set() { return facts; } let after = self.probe(); - let trims = self.inner.trims.fetch_add(1, Ordering::Relaxed) + 1; - if trims == 1 || now.saturating_sub(self.inner.last_trim_log_ms.load(Ordering::Relaxed)) >= 10_000 { - self.inner.last_trim_log_ms.store(now, Ordering::Relaxed); - self.log(&format!( - "working set trimmed (#{trims}): available {} -> {} MiB", - available >> 20, - after.effective_available().unwrap_or(0) >> 20 - )); - } + self.log_trim(now, available, &after); after } - /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while shedding. + /// Log the first trim and then at most one in ten seconds. + fn log_trim(&self, now: u64, available_before: u64, after: &HostFacts) { + let trims = self.inner.trim.count.fetch_add(1, Ordering::Relaxed) + 1; + if trims == 1 || now.saturating_sub(self.inner.trim.last_log_ms.load(Ordering::Relaxed)) >= 10_000 { + self.inner.trim.last_log_ms.store(now, Ordering::Relaxed); + self.log(&format!( + "working set trimmed (#{trims}): available {} -> {} MiB", + available_before >> 20, + after.effective_available().unwrap_or(0) >> 20 + )); + } + } + + /// What the cache owners must do at this level. The prefix target steps down by a quarter per second while + /// shedding. pub fn directive(&self, prefix_used: u64) -> ShedDirective { self.ensure_fresh(); let level = self.level(); - let planned = self.inner.prefix_planned.load(Ordering::Acquire); self.inner.prefix_used.store(prefix_used, Ordering::Release); match level { Level::Normal => { @@ -124,20 +134,7 @@ impl Governor { ShedDirective { level, prefix_budget: None, drop_conversation: false } } Level::Shed => { - let now = self.now_ms(); - let last = self.inner.last_shed_ms.load(Ordering::Acquire); - let current = self.inner.prefix_target.load(Ordering::Acquire); - let target = if current == NONE || now.saturating_sub(last) >= 1000 { - let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; - let next = base / 4 * 3; - self.inner.prefix_target.store(next, Ordering::Release); - self.inner.last_shed_ms.store(now, Ordering::Release); - self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); - next - } else { - current - }; - ShedDirective { level, prefix_budget: Some(target), drop_conversation: true } + ShedDirective { level, prefix_budget: Some(self.shed_target(prefix_used)), drop_conversation: true } } Level::Reject => { self.inner.prefix_target.store(0, Ordering::Release); @@ -146,6 +143,23 @@ impl Governor { } } + /// The prefix budget to enforce while shedding: a quarter less than the current target, at most once a second. + fn shed_target(&self, prefix_used: u64) -> u64 { + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + let now = self.now_ms(); + let last = self.inner.last_shed_ms.load(Ordering::Acquire); + let current = self.inner.prefix_target.load(Ordering::Acquire); + if current != NONE && now.saturating_sub(last) < 1000 { + return current; + } + let base = if current == NONE { prefix_used.min(planned) } else { current.min(prefix_used) }; + let next = base / 4 * 3; + self.inner.prefix_target.store(next, Ordering::Release); + self.inner.last_shed_ms.store(now, Ordering::Release); + self.inner.counters.shed_steps.fetch_add(1, Ordering::Relaxed); + next + } + pub fn note_prefix_used(&self, bytes: u64) { self.inner.prefix_used.store(bytes, Ordering::Release); } diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs index 64cc6f5c..df1782ef 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs @@ -4,10 +4,10 @@ use super::*; impl Governor { - /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the - /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero - /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their - /// size, and the report says so. `None` is the whole archive. + /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything + /// else of the `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a + /// hole allocates zero pages for it, which would turn the sparse copy back into the full archive), the lock limit + /// is judged against their size, and the report says so. `None` is the whole archive. #[cfg(all(target_os = "linux", target_pointer_width = "64"))] pub fn guard_archive_extents( &self, @@ -18,151 +18,22 @@ impl Governor { let started = self.inner.clock.now(); let facts = self.probe(); let mode = self.inner.cfg.lock_mode; - if let Some(spans) = extents - && let Err(why) = crate::lock::check_spans(spans, len) - { - return Err(Refusal { - code: "memlock", - message: format!("the sparse archive extents are invalid: {why}"), - numbers: vec![("archive".to_owned(), len)], - advice: vec![], - }); - } + archive_guard::check_extents(extents, len)?; // the bytes that are resident and have to be locked let resident = extents.map_or(len, crate::lock::spans_bytes); let extent_bytes = extents.map(crate::lock::spans_bytes); + let base = archive_guard::ReportBase { mode, started, memlock: facts.memlock, extent_bytes }; let decision = plan_lock(mode, resident, facts.memlock, &facts.status); - // Map a private READ-ONLY reopen of the descriptor, never the descriptor itself: a write-sealed memfd refuses a shared - // mapping that could become writable (EPERM on kernels up to 5.15 when the description is read-write), and a read-only - // description can never become writable, so the mapping is allowed everywhere and is immutable by construction. - let readonly = { - use std::os::fd::AsRawFd; - std::fs::OpenOptions::new().read(true).open(format!("/proc/self/fd/{}", fd.as_raw_fd())) - }; - let mapped = match &readonly { - Ok(file) => { - use std::os::fd::AsFd as _; - crate::lock::FdMapping::map_readonly(file.as_fd(), usize::try_from(len).unwrap_or(usize::MAX)) - } - Err(e) => Err(std::io::Error::new(e.kind(), format!("cannot reopen the descriptor read-only: {e}"))), - }; - let mut mapping = match mapped { + let mut mapping = match archive_guard::map_readonly_archive(fd, len) { Ok(m) => m, - Err(e) => { - let report = LockReport { - mode, - decision, - outcome: LockOutcome::NotAttempted { why: format!("mmap of the archive failed: {e}") }, - mapping_bytes: 0, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: self.inner.clock.since(started).as_secs_f64() * 1e3, - }; - self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); - if mode == LockMode::Require { - return Err(Refusal { - code: "memlock", - message: format!("mmap of the archive failed: {e}"), - numbers: vec![], - advice: vec![], - }); - } - return Ok(report); - } - }; - let outcome = match &decision { - LockDecision::Off => LockOutcome::NotAttempted { why: "LELEKA_MEMORY_LOCK=off".into() }, - LockDecision::Insufficient { need, soft, hard, advice } => { - let why = format!( - "RLIMIT_MEMLOCK soft {} MiB / hard {} MiB cannot cover {} MiB", - soft >> 20, - if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, - need >> 20 - ); - self.log(&format!( - "WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", - gib(resident), - advice.join(" | ") - )); - LockOutcome::NotAttempted { why } - } - LockDecision::Attempt { raise_soft_to } => { - if let Some(to) = raise_soft_to - && let Err(e) = crate::lock::raise_memlock_soft(*to) - { - self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); - } - let policy = self.policy(); - let swapped = self.mapping_swapped(&mapping).unwrap_or(0); - let src = self.inner.src.clone(); - let allow = |n: u64| { - // a swapped-out chunk is read back into RAM: keep the hard floor + reserve - let need = if swapped > 0 { n } else { 0 }; - let floor = policy.hard_floor + policy.reserve; - src.facts().effective_available().is_none_or(|a| a.saturating_sub(need) >= floor) - }; - let outcome = match extents { - Some(spans) => mapping.lock_ranges(spans, GIB, allow), - None => mapping.lock(GIB, allow), - }; - match &outcome { - LockOutcome::Locked { bytes } => { - self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))) - } - LockOutcome::Partial { locked, why, .. } => self.log(&format!( - "WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", - gib(*locked), - gib(len) - )), - LockOutcome::NotAttempted { why } => { - self.log(&format!("sealed KAR memfd lock not attempted: {why}")) - } - } - outcome - } - }; - let report = LockReport { - mode, - decision: decision.clone(), - outcome: outcome.clone(), - mapping_bytes: len, - extent_bytes, - memlock_soft: facts.memlock.map(|m| m.0), - memlock_hard: facts.memlock.map(|m| m.1), - millis: self.inner.clock.since(started).as_secs_f64() * 1e3, + Err(e) => return self.unmapped_archive(&base, decision, &e), }; + let outcome = self.apply_decision(&decision, &mut mapping, extents, resident); + let report = self.lock_report(&base, decision.clone(), outcome.clone(), len); if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { - let (numbers, advice) = match &decision { - LockDecision::Insufficient { need, soft, hard, advice } => ( - vec![ - ("needed to lock".to_owned(), *need), - ("RLIMIT_MEMLOCK soft".to_owned(), *soft), - ("RLIMIT_MEMLOCK hard".to_owned(), *hard), - ], - advice.clone(), - ), - _ => (vec![("archive".to_owned(), resident)], vec![]), - }; - return Err(Refusal { - code: "memlock", - message: format!( - "LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})" - ), - numbers, - advice, - }); + return Err(archive_guard::require_refusal(&decision, &outcome, resident)); } - *lock(&self.inner.guarded) = Some(Guarded { - mapping, - report: report.clone(), - extents: extents.map(<[_]>::to_vec), - cursor: 0, - last_swapped: 0, - warned_swapped: 0, - last_check: None, - last: None, - }); + *lock(&self.inner.guarded) = Some(Guarded::new(mapping, report.clone(), extents)); Ok(report) } @@ -186,69 +57,9 @@ impl Governor { g.last = Some(r); g.last_check = Some(self.inner.clock.now()); g.last_swapped = r.swapped_bytes; - if r.swapped_bytes >= 64 * MIB && r.swapped_bytes.abs_diff(g.warned_swapped) >= 64 * MIB { - g.warned_swapped = r.swapped_bytes; - self.log(&format!( - "WARNING: {} MiB of the sealed KAR memfd are swapped out ({} of {} resident, locked {} MiB; smaps read {read_ms:.0} ms): PLE reads fault from swap until they are pulled back{}", - r.swapped_bytes >> 20, - gib(r.rss_bytes), - gib(r.mapping_bytes), - r.locked_bytes >> 20, - if self.inner.cfg.heal { "; healing" } else { "" } - )); - } else if r.swapped_bytes < 64 * MIB { - g.warned_swapped = 0; - } + self.warn_swapped(g, &r, read_ms); if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { - let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); - let ok = - self.inner.src.facts().effective_available().is_some_and(|a| { - a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve - }); - if ok { - let mut done = 0; - match g.extents.clone() { - // a sparse archive: walk the concatenation of the extents, never a hole - Some(spans) => { - let total = crate::lock::spans_bytes(&spans); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let want = (256 * MIB).min(budget - done); - let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { - break; - }; - // whole pages; the last page of the last extent may be partial and is rounded up by the kernel - let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; - if g.mapping.populate(offset, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - None => { - let total = g.mapping.len(); - while done < budget && done < total { - if g.cursor >= total { - g.cursor = 0; - } - let n = (256 * MIB).min(total - g.cursor).min(budget - done) / 4096 * 4096; - if n == 0 { - break; - } - if g.mapping.populate(g.cursor, n).is_err() { - break; - } - g.cursor += n; - done += n; - } - } - } - self.inner.counters.heal_bytes.fetch_add(done, Ordering::Relaxed); - self.inner.counters.heal_runs.fetch_add(1, Ordering::Relaxed); - } + self.heal(g, &r, &policy); } r.swapped_bytes } diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs index aa43f458..6bcc050c 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs @@ -11,72 +11,76 @@ impl Governor { let monitor = lock(&self.inner.monitor); let policy = self.policy(); let level = self.level(); - let c = &self.inner.counters; - let planned = self.inner.prefix_planned.load(Ordering::Acquire); - let target = self.inner.prefix_target.load(Ordering::Acquire); - #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - let archive = lock(&self.inner.guarded) - .as_ref() - .map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); - #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] - let archive: Option = None; json!({ "version": 1, "uptime_ms": self.now_ms(), - "gate": { - "level": level.as_str(), - "since_ms": self.inner.since_ms.load(Ordering::Acquire), - "reason": &*lock(&self.inner.reason), - "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, - "available_bytes": self.available_cached(), - "soft_floor_bytes": policy.soft_floor, - "hard_floor_bytes": policy.hard_floor, - }, + "gate": self.gate_json(level, &monitor, &policy), "policy": policy, - "config": {"sample_interval_ms": self.inner.cfg.sample_interval_ms, "lock_mode": self.inner.cfg.lock_mode, "heal": self.inner.cfg.heal}, + "config": self.config_json(), "plan": self.plan(), - "host": { - "mem_total": facts.meminfo.mem_total, - "mem_available": facts.meminfo.mem_available, - "effective_available": facts.effective_available(), - "swap_total": facts.meminfo.swap_total, - "swap_free": facts.meminfo.swap_free, - "shmem": facts.meminfo.shmem, - "mlocked": facts.meminfo.mlocked, - "cgroup": facts.cgroup, - "psi": facts.psi, - "memlock": facts.memlock, - "wsl": facts.wsl, - "kernel": facts.kernel, - }, - "process": { - "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, "locked": facts.status.vm_lck, - "threads": facts.status.threads, "fds": facts.open_fds, - }, + "host": host_json(&facts), + "process": process_json(&facts), "observed": monitor.observed, - "caches": { - "prefix": {"planned_bytes": planned, "shed_target_bytes": if target == NONE { serde_json::Value::Null } else { json!(target) }, "used_bytes": self.inner.prefix_used.load(Ordering::Acquire)}, - }, - "counters": { - "admitted": c.admitted.load(Ordering::Relaxed), - "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), - "rejected_context": c.rejected_context.load(Ordering::Relaxed), - "shed_steps": c.shed_steps.load(Ordering::Relaxed), - "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), - "samples": c.samples.load(Ordering::Relaxed), - "level_changes": c.level_changes.load(Ordering::Relaxed), - "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), - "heal_runs": c.heal_runs.load(Ordering::Relaxed), - }, - "archive": archive, + "caches": self.caches_json(), + "counters": counters_json(&self.inner.counters), + "archive": self.archive_json(), "inventory": self.inventory().to_json(), "ledger": self.inner.ledger.to_json(), "vram": &*lock(&self.inner.vram), - "plan_check": lock(&self.inner.post_load).map(|(p, a)| json!({"predicted_available_after_fixed": p, "actual_available_after_open": a, "error_bytes": i128::from(a) - i128::from(p)})), + "plan_check": self.plan_check_json(), "transitions": &*lock(&self.inner.transitions), }) } + /// The level, why, since when, and the floors it is judged against. + fn gate_json(&self, level: Level, monitor: &Monitor, policy: &Policy) -> serde_json::Value { + json!({ + "level": level.as_str(), + "since_ms": self.inner.since_ms.load(Ordering::Acquire), + "reason": &*lock(&self.inner.reason), + "retry_after_secs": if level == Level::Normal { 0 } else { monitor.retry_after_secs() }, + "available_bytes": self.available_cached(), + "soft_floor_bytes": policy.soft_floor, + "hard_floor_bytes": policy.hard_floor, + }) + } + + fn config_json(&self) -> serde_json::Value { + let cfg = &self.inner.cfg; + json!({"sample_interval_ms": cfg.sample_interval_ms, "lock_mode": cfg.lock_mode, "heal": cfg.heal}) + } + + fn caches_json(&self) -> serde_json::Value { + let planned = self.inner.prefix_planned.load(Ordering::Acquire); + let target = self.inner.prefix_target.load(Ordering::Acquire); + let shed_target = if target == NONE { serde_json::Value::Null } else { json!(target) }; + let used = self.inner.prefix_used.load(Ordering::Acquire); + json!({"prefix": {"planned_bytes": planned, "shed_target_bytes": shed_target, "used_bytes": used}}) + } + + #[cfg(all(target_os = "linux", target_pointer_width = "64"))] + fn archive_json(&self) -> Option { + lock(&self.inner.guarded) + .as_ref() + .map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})) + } + + #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] + fn archive_json(&self) -> Option { + None + } + + /// The error of the startup plan's prediction against what the host really had after the stack opened. + fn plan_check_json(&self) -> Option { + lock(&self.inner.post_load).map(|(p, a)| { + json!({ + "predicted_available_after_fixed": p, + "actual_available_after_open": a, + "error_bytes": i128::from(a) - i128::from(p), + }) + }) + } + /// Render the report into the cell [`published_report`] reads. pub fn publish(&self) { if let Ok(text) = serde_json::to_string(&self.report()) { @@ -86,51 +90,98 @@ impl Governor { // ---- sampler ----------------------------------------------------------------------------------------------- - /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps read of - /// the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop when the guard is - /// dropped. - pub fn spawn_sampler(&self) -> SamplerGuard { - fn nap(inner: &Inner, total: Duration) { - let mut slept = Duration::ZERO; - while slept < total && !inner.stop.load(Ordering::Acquire) { - let step = Duration::from_millis(50).min(total - slept); - std::thread::sleep(step); - slept += step; - } - } - self.inner.stop.store(false, Ordering::Release); + /// Run `round` every `every` on a named thread until the governor is told to stop. A panic in one round (a + /// malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level: it is logged. + fn spawn_rounds( + &self, + name: &str, + every: Duration, + panicked: &'static str, + round: fn(&Governor), + ) -> Option> { let me = self.clone(); - let sampler = std::thread::Builder::new() - .name("leleka-memory".into()) + std::thread::Builder::new() + .name(name.into()) .spawn(move || { - let interval = Duration::from_millis(me.inner.cfg.sample_interval_ms); while !me.inner.stop.load(Ordering::Acquire) { - // a panic in one round (a malformed /proc read, a poisoned state) must not end the thread that lifts a pressure level - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - me.sample_now(); - me.publish(); - })); - if round.is_err() { - me.log("WARNING: the memory sampler round panicked; continuing"); - } - nap(&me.inner, interval); - } - }) - .ok(); - let me = self.clone(); - let guard = std::thread::Builder::new() - .name("leleka-memory-guard".into()) - .spawn(move || { - let every = Duration::from_millis(me.inner.cfg.residency_every_ms); - while !me.inner.stop.load(Ordering::Acquire) { - let round = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| me.residency_tick())); - if round.is_err() { - me.log("WARNING: the memfd residency round panicked; continuing"); + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| round(&me))); + if outcome.is_err() { + me.log(panicked); } nap(&me.inner, every); } }) - .ok(); + .ok() + } + + /// Start the sampler thread (pressure level and report, every interval) and the residency-guard thread (the smaps + /// read of the memfd mapping costs up to a second for 55 GB, which must not delay a pressure sample). Both stop + /// when the guard is dropped. + pub fn spawn_sampler(&self) -> SamplerGuard { + self.inner.stop.store(false, Ordering::Release); + let interval = Duration::from_millis(self.inner.cfg.sample_interval_ms); + let sampler = self.spawn_rounds( + "leleka-memory", + interval, + "WARNING: the memory sampler round panicked; continuing", + |g| { + g.sample_now(); + g.publish(); + }, + ); + let every = Duration::from_millis(self.inner.cfg.residency_every_ms); + let panicked = "WARNING: the memfd residency round panicked; continuing"; + let guard = self.spawn_rounds("leleka-memory-guard", every, panicked, |g| { + g.residency_tick(); + }); SamplerGuard { inner: self.inner.clone(), handles: sampler.into_iter().chain(guard).collect() } } } + +/// Sleep up to `total` in steps of 50 ms, returning early once the governor is told to stop. +fn nap(inner: &Inner, total: Duration) { + let mut slept = Duration::ZERO; + while slept < total && !inner.stop.load(Ordering::Acquire) { + let step = Duration::from_millis(50).min(total - slept); + std::thread::sleep(step); + slept += step; + } +} + +fn host_json(facts: &HostFacts) -> serde_json::Value { + json!({ + "mem_total": facts.meminfo.mem_total, + "mem_available": facts.meminfo.mem_available, + "effective_available": facts.effective_available(), + "swap_total": facts.meminfo.swap_total, + "swap_free": facts.meminfo.swap_free, + "shmem": facts.meminfo.shmem, + "mlocked": facts.meminfo.mlocked, + "cgroup": facts.cgroup, + "psi": facts.psi, + "memlock": facts.memlock, + "wsl": facts.wsl, + "kernel": facts.kernel, + }) +} + +fn process_json(facts: &HostFacts) -> serde_json::Value { + json!({ + "rss": facts.status.vm_rss, "swap": facts.status.vm_swap, "pinned": facts.status.vm_pin, + "locked": facts.status.vm_lck, "threads": facts.status.threads, "fds": facts.open_fds, + }) +} + +fn counters_json(c: &Counters) -> serde_json::Value { + json!({ + "admitted": c.admitted.load(Ordering::Relaxed), + "rejected_memory_pressure": c.rejected_pressure.load(Ordering::Relaxed), + "rejected_context": c.rejected_context.load(Ordering::Relaxed), + "shed_steps": c.shed_steps.load(Ordering::Relaxed), + "evicted_bytes": c.evicted_bytes.load(Ordering::Relaxed), + "samples": c.samples.load(Ordering::Relaxed), + "level_changes": c.level_changes.load(Ordering::Relaxed), + "heal_bytes": c.heal_bytes.load(Ordering::Relaxed), + "heal_runs": c.heal_runs.load(Ordering::Relaxed), + }) +} diff --git a/crates/leleka-memory/src/governor/impl_governorconfig.rs b/crates/leleka-memory/src/governor/impl_governorconfig.rs index 724d0c60..806bd9a9 100644 --- a/crates/leleka-memory/src/governor/impl_governorconfig.rs +++ b/crates/leleka-memory/src/governor/impl_governorconfig.rs @@ -3,6 +3,96 @@ #[allow(unused_imports)] use super::*; +/// The `LELEKA_MEMORY_*` overrides over any lookup `Fn(&str) -> Option`. +trait EnvLookup { + fn var(&self, name: &str) -> Option; + + /// An unsigned override; `None` when unset, an error naming the variable when it is not a number. + fn number(&self, name: &str) -> Result, String> { + match self.var(name) { + None => Ok(None), + Some(v) => v.trim().parse::().map(Some).map_err(|_| format!("{name}={v:?} is not a number")), + } + } + + /// A non-negative finite override; `None` when unset. + fn float(&self, name: &str) -> Result, String> { + match self.var(name) { + None => Ok(None), + Some(v) => v + .trim() + .parse::() + .ok() + .filter(|f| f.is_finite() && *f >= 0.0) + .map(Some) + .ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), + } + } + + /// Override `field` with a number of MiB, in bytes. + fn set_mib(&self, name: &str, field: &mut u64) -> Result<(), String> { + if let Some(v) = self.number(name)? { + *field = v.saturating_mul(MIB); + } + Ok(()) + } + + /// Override `field` with a number. + fn set_number(&self, name: &str, field: &mut u64) -> Result<(), String> { + if let Some(v) = self.number(name)? { + *field = v; + } + Ok(()) + } + + /// Override `field` with a flag (any number but 0 is on). + fn set_flag(&self, name: &str, field: &mut bool) -> Result<(), String> { + if let Some(v) = self.number(name)? { + *field = v != 0; + } + Ok(()) + } + + /// Override `field` with a non-negative number. + fn set_float(&self, name: &str, field: &mut f64) -> Result<(), String> { + if let Some(v) = self.float(name)? { + *field = v; + } + Ok(()) + } +} + +impl Option + ?Sized> EnvLookup for F { + fn var(&self, name: &str) -> Option { + self(name) + } +} + +impl Policy { + /// The floors, the reserve, the cache share and the swap-out limit. + fn apply_env_floors(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> { + env.set_mib("LELEKA_MEMORY_SOFT_FLOOR_MIB", &mut self.soft_floor)?; + env.set_mib("LELEKA_MEMORY_HARD_FLOOR_MIB", &mut self.hard_floor)?; + env.set_mib("LELEKA_MEMORY_RESERVE_MIB", &mut self.reserve)?; + env.set_mib("LELEKA_MEMORY_HYSTERESIS_MIB", &mut self.hysteresis)?; + if let Some(v) = env.number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? { + if v == 0 || v > 100 { + return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100")); + } + self.cache_share_percent = v; + } + env.set_number("LELEKA_MEMORY_SWAPOUT_PAGES_PER_S", &mut self.swapout_pages_per_s_shed) + } + + /// The PSI guard and its two limits, and whether the plan is enforced. + fn apply_env_psi(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> { + env.set_mib("LELEKA_MEMORY_PSI_GUARD_MIB", &mut self.psi_guard_available)?; + env.set_float("LELEKA_MEMORY_PSI_SOME_SHED", &mut self.psi_some_shed)?; + env.set_float("LELEKA_MEMORY_PSI_FULL_REJECT", &mut self.psi_full_reject)?; + env.set_flag("LELEKA_MEMORY_ENFORCE", &mut self.enforce) + } +} + impl GovernorConfig { pub fn new(policy: Policy) -> Self { Self { @@ -16,77 +106,33 @@ impl GovernorConfig { } } - /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the variable - /// (a typo must not silently keep the default of a safety setting). - pub fn from_env(mem_total: u64, laptop: bool, env: &dyn Fn(&str) -> Option) -> Result { - let mut cfg = Self::new(Policy::for_host(mem_total, laptop)); - let number = |name: &str| -> Result, String> { - match env(name) { - None => Ok(None), - Some(v) => v.trim().parse::().map(Some).map_err(|_| format!("{name}={v:?} is not a number")), - } - }; - if let Some(v) = number("LELEKA_MEMORY_SOFT_FLOOR_MIB")? { - cfg.policy.soft_floor = v.saturating_mul(MIB); + /// The sampler, the heal and the lock overrides. + fn apply_env_runtime(&mut self, env: &(impl EnvLookup + ?Sized)) -> Result<(), String> { + if let Some(v) = env.number("LELEKA_MEMORY_SAMPLE_MS")? { + self.sample_interval_ms = v.clamp(50, 60_000); } - if let Some(v) = number("LELEKA_MEMORY_HARD_FLOOR_MIB")? { - cfg.policy.hard_floor = v.saturating_mul(MIB); + env.set_flag("LELEKA_MEMORY_HEAL", &mut self.heal)?; + if let Some(v) = env.number("LELEKA_MEMORY_RESIDENCY_S")? { + self.residency_every_ms = v.saturating_mul(1000).max(1000); } - if let Some(v) = number("LELEKA_MEMORY_RESERVE_MIB")? { - cfg.policy.reserve = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_HYSTERESIS_MIB")? { - cfg.policy.hysteresis = v.saturating_mul(MIB); - } - if let Some(v) = number("LELEKA_MEMORY_CACHE_SHARE_PERCENT")? { - if v == 0 || v > 100 { - return Err(format!("LELEKA_MEMORY_CACHE_SHARE_PERCENT={v} must be 1..=100")); - } - cfg.policy.cache_share_percent = v; - } - if let Some(v) = number("LELEKA_MEMORY_SWAPOUT_PAGES_PER_S")? { - cfg.policy.swapout_pages_per_s_shed = v; - } - let float = |name: &str| -> Result, String> { - match env(name) { - None => Ok(None), - Some(v) => v - .trim() - .parse::() - .ok() - .filter(|f| f.is_finite() && *f >= 0.0) - .map(Some) - .ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), - } - }; - if let Some(v) = number("LELEKA_MEMORY_PSI_GUARD_MIB")? { - cfg.policy.psi_guard_available = v.saturating_mul(MIB); - } - if let Some(v) = float("LELEKA_MEMORY_PSI_SOME_SHED")? { - cfg.policy.psi_some_shed = v; - } - if let Some(v) = float("LELEKA_MEMORY_PSI_FULL_REJECT")? { - cfg.policy.psi_full_reject = v; - } - if let Some(v) = number("LELEKA_MEMORY_ENFORCE")? { - cfg.policy.enforce = v != 0; - } - if let Some(v) = number("LELEKA_MEMORY_SAMPLE_MS")? { - cfg.sample_interval_ms = v.clamp(50, 60_000); - } - if let Some(v) = number("LELEKA_MEMORY_HEAL")? { - cfg.heal = v != 0; - } - if let Some(v) = number("LELEKA_MEMORY_RESIDENCY_S")? { - cfg.residency_every_ms = v.saturating_mul(1000).max(1000); - } - if let Some(v) = env("LELEKA_MEMORY_LOCK") { - cfg.lock_mode = LockMode::parse(v.trim()) + if let Some(v) = env.var("LELEKA_MEMORY_LOCK") { + self.lock_mode = LockMode::parse(v.trim()) .ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; } + Ok(()) + } + + /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the + /// variable (a typo must not silently keep the default of a safety setting). + pub fn from_env(mem_total: u64, laptop: bool, env: &dyn Fn(&str) -> Option) -> Result { + let mut cfg = Self::new(Policy::for_host(mem_total, laptop)); + cfg.policy.apply_env_floors(env)?; + cfg.policy.apply_env_psi(env)?; + cfg.apply_env_runtime(env)?; if cfg.policy.hard_floor >= cfg.policy.soft_floor { return Err(format!( - "hard floor {} MiB must be below the soft floor {} MiB (LELEKA_MEMORY_HARD_FLOOR_MIB / SOFT_FLOOR_MIB)", + "hard floor {} MiB must be below the soft floor {} MiB (LELEKA_MEMORY_HARD_FLOOR_MIB / \ + SOFT_FLOOR_MIB)", cfg.policy.hard_floor >> 20, cfg.policy.soft_floor >> 20 )); diff --git a/crates/leleka-memory/src/heap.rs b/crates/leleka-memory/src/heap.rs index 658ce64a..1996545a 100644 --- a/crates/leleka-memory/src/heap.rs +++ b/crates/leleka-memory/src/heap.rs @@ -1,9 +1,9 @@ //! Giving freed heap memory back to the kernel. //! -//! glibc serves allocations below its (dynamic, up to 32 MiB) mmap threshold from the heap arenas and keeps freed pages there: evicting 4 GiB -//! of 29 MB prefix-cache blocks would leave the process RSS, and so `MemAvailable`, unchanged, and the shed would not help the -//! host at all. `trim` hands the free pages of every arena back (`malloc_trim(0)`), and is called after an eviction. On other -//! allocators or platforms it does nothing. +//! glibc serves allocations below its (dynamic, up to 32 MiB) mmap threshold from the heap arenas and keeps freed pages +//! there: evicting 4 GiB of 29 MB prefix-cache blocks would leave the process RSS, and so `MemAvailable`, unchanged, +//! and the shed would not help the host at all. `trim` hands the free pages of every arena back (`malloc_trim(0)`), and +//! is called after an eviction. On other allocators or platforms it does nothing. /// `LELEKA_MEMORY_NO_TRIM=1` turns `trim` into a no-op (for the A/B of what the trim buys). fn trim_disabled() -> bool { @@ -30,7 +30,8 @@ pub struct HeapStats { #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64"))] #[allow(unsafe_code)] pub fn stats() -> Option { - // SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters under its locks. + // SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters + // under its locks. let m = unsafe { libc::mallinfo2() }; Some(HeapStats { arena: m.arena as u64, @@ -53,8 +54,8 @@ pub fn trim() -> bool { if trim_disabled() { return false; } - // SAFETY: `malloc_trim` takes no pointers; it walks the allocator's own free lists under the allocator's locks and releases whole - // free pages with madvise. It is safe to call from any thread at any time. + // SAFETY: `malloc_trim` takes no pointers; it walks the allocator's own free lists under the allocator's locks and + // releases whole free pages with madvise. It is safe to call from any thread at any time. unsafe { libc::malloc_trim(0); } diff --git a/crates/leleka-memory/src/host.rs b/crates/leleka-memory/src/host.rs index 3d419a1e..0b780617 100644 --- a/crates/leleka-memory/src/host.rs +++ b/crates/leleka-memory/src/host.rs @@ -169,8 +169,8 @@ impl HostFacts { /// `/proc/self/cgroup` is not the unified hierarchy. fn probe_cgroup(src: &dyn ProcSource) -> Option { let text = src.read("/proc/self/cgroup").ok()?; - // the unified hierarchy first; on a hybrid host (WSL2, older container hosts) the memory controller may still be a v1 - // hierarchy, which is where the limit lives + // the unified hierarchy first; on a hybrid host (WSL2, older container hosts) the memory controller may still be a + // v1 hierarchy, which is where the limit lives let v2 = procfs::parse_cgroup_path(&text).and_then(|rel| probe_cgroup_v2(src, rel)); if v2.as_ref().is_some_and(|c| !c.levels.is_empty()) { return v2; @@ -178,90 +178,127 @@ fn probe_cgroup(src: &dyn ProcSource) -> Option { probe_cgroup_v1(src, &text).or(v2) } -/// cgroup v1 `memory` controller: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes`, `memory.stat` and the -/// `oom_kill` counter of `memory.oom_control`. -fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option { - const ROOT: &str = "/sys/fs/cgroup/memory"; - const UNLIMITED: u64 = 1 << 62; - let rel = procfs::parse_cgroup_v1_memory_path(proc_cgroup)?; - if rel.split('/').any(|c| c == ".." || c == ".") { +/// Anything that could leave the cgroup root is refused. +fn escapes_root(rel: &str) -> bool { + rel.split('/').any(|c| c == ".." || c == ".") +} + +/// The directory of a cgroup path relative to the hierarchy `root`. +fn cgroup_dir(root: &str, rel: &str) -> String { + format!("{root}{}", if rel == "/" { String::new() } else { rel.to_owned() }) +} + +/// The directory above `dir`, down to and including `root`; `None` at the root. +fn parent_dir(dir: &str, root: &str) -> Option { + if dir == root { return None; } - let own = format!("{ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); - let mut dir = own.clone(); - let mut levels = Vec::new(); - loop { - let limit = src.read(&format!("{dir}/memory.limit_in_bytes")).ok().and_then(|t| t.trim().parse::().ok()); - let current = src.read(&format!("{dir}/memory.usage_in_bytes")).ok().and_then(|t| t.trim().parse::().ok()); - let stat = src.read(&format!("{dir}/memory.stat")).ok(); - let reclaimable = stat - .as_deref() - .and_then(|t| { - procfs::flat_keyed(t, "total_inactive_file").or_else(|| procfs::flat_keyed(t, "inactive_file")) - }) - .unwrap_or(0); - if limit.is_some() || current.is_some() { - let limit = limit.filter(|l| *l < UNLIMITED); - let headroom = match (limit, current) { - (Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))), - _ => None, - }; - levels.push(CgroupLevel { path: dir.clone(), limit, current, reclaimable, headroom }); - } - if dir == ROOT { - break; - } - match dir.rfind('/') { - Some(i) if i >= ROOT.len() => dir.truncate(i), - _ => break, - } + match dir.rfind('/') { + Some(i) if i >= root.len() => Some(dir[..i].to_owned()), + _ => None, } +} + +/// The levels from `own` up to `root`, innermost first; `level` reads one directory (`None` = nothing there). +fn walk_levels(own: &str, root: &str, mut level: impl FnMut(&str) -> Option) -> Vec { + let mut levels = Vec::new(); + let mut dir = Some(own.to_owned()); + while let Some(d) = dir { + levels.extend(level(&d)); + dir = parent_dir(&d, root); + } + levels +} + +/// The tightest limit among the levels (and where it is), and the smallest headroom. +fn tightest_and_headroom(levels: &[CgroupLevel]) -> (Option<(u64, String)>, Option) { let tightest = levels.iter().filter_map(|l| l.limit.map(|v| (v, l.path.clone()))).min_by_key(|(v, _)| *v); - let headroom = levels.iter().filter_map(|l| l.headroom).min(); + (tightest, levels.iter().filter_map(|l| l.headroom).min()) +} + +/// `limit - current + reclaimable` (the reclaimable part counted only up to what is in use). +fn headroom_of(limit: Option, current: Option, reclaimable: u64) -> Option { + match (limit, current) { + (Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))), + _ => None, + } +} + +/// A number in a one-line cgroup file. +fn read_number(src: &(impl ProcSource + ?Sized), path: &str) -> Option { + src.read(path).ok().and_then(|t| t.trim().parse::().ok()) +} + +/// One v1 level: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes` and `memory.stat`. +fn level_v1(src: &(impl ProcSource + ?Sized), dir: &str) -> Option { + const UNLIMITED: u64 = 1 << 62; + let limit = read_number(src, &format!("{dir}/memory.limit_in_bytes")); + let current = read_number(src, &format!("{dir}/memory.usage_in_bytes")); + let stat = src.read(&format!("{dir}/memory.stat")).ok(); + let reclaimable = stat + .as_deref() + .and_then(|t| procfs::flat_keyed(t, "total_inactive_file").or_else(|| procfs::flat_keyed(t, "inactive_file"))) + .unwrap_or(0); + if limit.is_none() && current.is_none() { + return None; + } + let limit = limit.filter(|l| *l < UNLIMITED); + Some(CgroupLevel { + path: dir.to_owned(), + limit, + current, + reclaimable, + headroom: headroom_of(limit, current, reclaimable), + }) +} + +/// cgroup v1 `memory` controller: `limit_in_bytes` (a value near 2^63 means unlimited), `usage_in_bytes`, `memory.stat` +/// and the `oom_kill` counter of `memory.oom_control`. +fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option { + const ROOT: &str = "/sys/fs/cgroup/memory"; + let rel = procfs::parse_cgroup_v1_memory_path(proc_cgroup)?; + if escapes_root(&rel) { + return None; + } + let own = cgroup_dir(ROOT, &rel); + let levels = walk_levels(&own, ROOT, |dir| level_v1(src, dir)); + let (limit, headroom) = tightest_and_headroom(&levels); let oom_kill = src.read(&format!("{own}/memory.oom_control")).ok().and_then(|t| procfs::flat_keyed(&t, "oom_kill")); let events = oom_kill.map(|k| CgroupEvents { low: 0, high: 0, max: 0, oom: k, oom_kill: k }); - Some(CgroupFacts { path: rel, levels, limit: tightest, headroom, swap_max: None, events }) + Some(CgroupFacts { path: rel, levels, limit, headroom, swap_max: None, events }) +} + +/// One v2 level: `memory.max`, `memory.current` and `memory.stat`. +fn level_v2(src: &(impl ProcSource + ?Sized), dir: &str) -> Option { + // limit: Some(Some(n)) = a limit, Some(None) = "max", None = unreadable (a level without the controller) + let limit = src.read(&format!("{dir}/memory.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)); + let current = read_number(src, &format!("{dir}/memory.current")); + let stat = src.read(&format!("{dir}/memory.stat")).ok(); + let reclaimable = stat.as_deref().and_then(|t| procfs::flat_keyed(t, "inactive_file")).unwrap_or(0); + if limit.is_none() && current.is_none() { + return None; + } + let limit = limit.flatten(); + Some(CgroupLevel { + path: dir.to_owned(), + limit, + current, + reclaimable, + headroom: headroom_of(limit, current, reclaimable), + }) } fn probe_cgroup_v2(src: &dyn ProcSource, rel: String) -> Option { - // Refuse anything that could leave the cgroup root. - if rel.split('/').any(|c| c == ".." || c == ".") { + if escapes_root(&rel) { return None; } - let mut dir = format!("{CGROUP_ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); - let mut levels = Vec::new(); - loop { - let limit = src.read(&format!("{dir}/memory.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)); - let current = src.read(&format!("{dir}/memory.current")).ok().and_then(|t| t.trim().parse::().ok()); - let stat = src.read(&format!("{dir}/memory.stat")).ok(); - let reclaimable = stat.as_deref().and_then(|t| procfs::flat_keyed(t, "inactive_file")).unwrap_or(0); - // limit: Some(Some(n)) = a limit, Some(None) = "max", None = unreadable (a level without the controller) - let (limit_bytes, readable) = match limit { - Some(l) => (l, true), - None => (None, false), - }; - if readable || current.is_some() { - let headroom = match (limit_bytes, current) { - (Some(l), Some(c)) => Some(l.saturating_sub(c).saturating_add(reclaimable.min(c))), - _ => None, - }; - levels.push(CgroupLevel { path: dir.clone(), limit: limit_bytes, current, reclaimable, headroom }); - } - if dir == CGROUP_ROOT { - break; - } - match dir.rfind('/') { - Some(i) if i >= CGROUP_ROOT.len() => dir.truncate(i), - _ => break, - } - } - let tightest = levels.iter().filter_map(|l| l.limit.map(|v| (v, l.path.clone()))).min_by_key(|(v, _)| *v); - let headroom = levels.iter().filter_map(|l| l.headroom).min(); - let own = format!("{CGROUP_ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); + let own = cgroup_dir(CGROUP_ROOT, &rel); + let levels = walk_levels(&own, CGROUP_ROOT, |dir| level_v2(src, dir)); + let (limit, headroom) = tightest_and_headroom(&levels); let swap_max = src.read(&format!("{own}/memory.swap.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)).flatten(); let events = src.read(&format!("{own}/memory.events")).ok().and_then(|t| procfs::parse_cgroup_events(&t)); - Some(CgroupFacts { path: rel, levels, limit: tightest, headroom, swap_max, events }) + Some(CgroupFacts { path: rel, levels, limit, headroom, swap_max, events }) } /// Advice text for the WSL2 case, appended to refusals. @@ -271,94 +308,4 @@ pub fn wsl_advice() -> &'static str { } #[cfg(test)] -mod tests { - 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/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/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") - .with("/proc/self/cgroup", "0::/user.slice/user-1000.slice/session-578.scope\n") - } - - #[test] - fn a_host_without_a_cgroup_limit_reports_meminfo() { - let f = HostFacts::probe(&server()); - assert_eq!(f.effective_available(), Some(20_699_384 * 1024)); - assert_eq!(f.effective_total(), Some(127_091_644 * 1024)); - assert_eq!(f.memlock, Some((8 << 20, 8 << 20))); - assert!(!f.wsl); - assert_eq!((f.pswpin, f.pswpout), (Some(10), Some(20))); - assert_eq!(f.status.vm_pin, Some(52_428_800 * 1024)); - assert!(f.cgroup.is_none() || f.cgroup.as_ref().unwrap().limit.is_none()); - } - - #[test] - fn the_tightest_cgroup_ancestor_bounds_what_is_available() { - let mut p = server(); - let base = "/sys/fs/cgroup/user.slice/user-1000.slice/session-578.scope"; - p.set(&format!("{base}/memory.max"), "max\n"); - p.set(&format!("{base}/memory.current"), "1000000\n"); - // the parent slice is limited to 30 GiB with 28 GiB used and 1 GiB of inactive file pages - let parent = "/sys/fs/cgroup/user.slice/user-1000.slice"; - p.set(&format!("{parent}/memory.max"), &format!("{}\n", 30u64 << 30)); - p.set(&format!("{parent}/memory.current"), &format!("{}\n", 28u64 << 30)); - p.set(&format!("{parent}/memory.stat"), &format!("inactive_file {}\nanon 1\n", 1u64 << 30)); - p.set("/sys/fs/cgroup/memory.max", "max\n"); - p.set("/sys/fs/cgroup/memory.current", "5\n"); - p.set(&format!("{base}/memory.events"), "low 0\nhigh 0\nmax 2\noom 0\noom_kill 0\n"); - let f = HostFacts::probe(&p); - let cg = f.cgroup.as_ref().unwrap(); - assert_eq!(cg.limit, Some((30 << 30, parent.to_owned()))); - assert_eq!(cg.headroom, Some(3 << 30)); - assert_eq!(f.effective_available(), Some(3 << 30), "cgroup headroom is below MemAvailable"); - assert_eq!(f.effective_total(), Some(30 << 30)); - assert_eq!(cg.events.unwrap().max, 2); - assert_eq!(cg.levels.len(), 3); - } - - #[test] - fn a_v1_memory_controller_limit_is_honoured_on_a_hybrid_host() { - let mut p = server(); - p.set("/proc/self/cgroup", "5:memory:/docker/abc\n0::/docker/abc\n"); - let base = "/sys/fs/cgroup/memory/docker/abc"; - p.set(&format!("{base}/memory.limit_in_bytes"), &format!("{}\n", 12u64 << 30)); - p.set(&format!("{base}/memory.usage_in_bytes"), &format!("{}\n", 11u64 << 30)); - p.set(&format!("{base}/memory.stat"), &format!("cache 1\ntotal_inactive_file {}\n", 512u64 << 20)); - p.set(&format!("{base}/memory.oom_control"), "oom_kill_disable 0\nunder_oom 0\noom_kill 2\n"); - p.set("/sys/fs/cgroup/memory/memory.limit_in_bytes", "9223372036854771712\n"); - p.set("/sys/fs/cgroup/memory/memory.usage_in_bytes", "123\n"); - let f = HostFacts::probe(&p); - let cg = f.cgroup.as_ref().unwrap(); - assert_eq!(cg.limit, Some((12 << 30, base.to_owned()))); - assert_eq!(cg.headroom, Some((1u64 << 30) + (512 << 20))); - assert_eq!(f.effective_available(), Some((1u64 << 30) + (512 << 20))); - assert_eq!(cg.events.unwrap().oom_kill, 2); - } - - #[test] - fn a_path_that_climbs_out_of_the_cgroup_root_is_not_followed() { - let mut p = server(); - p.set("/proc/self/cgroup", "0::/../../etc\n"); - assert!(HostFacts::probe(&p).cgroup.is_none()); - } - - #[test] - fn wsl_is_recognised_from_the_kernel_release() { - let mut p = server(); - p.set("/proc/sys/kernel/osrelease", "6.6.87.2-microsoft-standard-WSL2\n"); - assert!(HostFacts::probe(&p).wsl); - } - - #[test] - fn unknown_telemetry_stays_unknown() { - let f = HostFacts::probe(&FakeProc::default()); - assert_eq!(f.effective_available(), None); - assert_eq!(f.effective_total(), None); - assert_eq!(f.swap_free(), 0); - } -} +mod tests; diff --git a/crates/leleka-memory/src/host/tests.rs b/crates/leleka-memory/src/host/tests.rs new file mode 100644 index 00000000..7bacb754 --- /dev/null +++ b/crates/leleka-memory/src/host/tests.rs @@ -0,0 +1,89 @@ +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/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/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") + .with("/proc/self/cgroup", "0::/user.slice/user-1000.slice/session-578.scope\n") +} + +#[test] +fn a_host_without_a_cgroup_limit_reports_meminfo() { + let f = HostFacts::probe(&server()); + assert_eq!(f.effective_available(), Some(20_699_384 * 1024)); + assert_eq!(f.effective_total(), Some(127_091_644 * 1024)); + assert_eq!(f.memlock, Some((8 << 20, 8 << 20))); + assert!(!f.wsl); + assert_eq!((f.pswpin, f.pswpout), (Some(10), Some(20))); + assert_eq!(f.status.vm_pin, Some(52_428_800 * 1024)); + assert!(f.cgroup.is_none() || f.cgroup.as_ref().unwrap().limit.is_none()); +} + +#[test] +fn the_tightest_cgroup_ancestor_bounds_what_is_available() { + let mut p = server(); + let base = "/sys/fs/cgroup/user.slice/user-1000.slice/session-578.scope"; + p.set(&format!("{base}/memory.max"), "max\n"); + p.set(&format!("{base}/memory.current"), "1000000\n"); + // the parent slice is limited to 30 GiB with 28 GiB used and 1 GiB of inactive file pages + let parent = "/sys/fs/cgroup/user.slice/user-1000.slice"; + p.set(&format!("{parent}/memory.max"), &format!("{}\n", 30u64 << 30)); + p.set(&format!("{parent}/memory.current"), &format!("{}\n", 28u64 << 30)); + p.set(&format!("{parent}/memory.stat"), &format!("inactive_file {}\nanon 1\n", 1u64 << 30)); + p.set("/sys/fs/cgroup/memory.max", "max\n"); + p.set("/sys/fs/cgroup/memory.current", "5\n"); + p.set(&format!("{base}/memory.events"), "low 0\nhigh 0\nmax 2\noom 0\noom_kill 0\n"); + let f = HostFacts::probe(&p); + let cg = f.cgroup.as_ref().unwrap(); + assert_eq!(cg.limit, Some((30 << 30, parent.to_owned()))); + assert_eq!(cg.headroom, Some(3 << 30)); + assert_eq!(f.effective_available(), Some(3 << 30), "cgroup headroom is below MemAvailable"); + assert_eq!(f.effective_total(), Some(30 << 30)); + assert_eq!(cg.events.unwrap().max, 2); + assert_eq!(cg.levels.len(), 3); +} + +#[test] +fn a_v1_memory_controller_limit_is_honoured_on_a_hybrid_host() { + let mut p = server(); + p.set("/proc/self/cgroup", "5:memory:/docker/abc\n0::/docker/abc\n"); + let base = "/sys/fs/cgroup/memory/docker/abc"; + p.set(&format!("{base}/memory.limit_in_bytes"), &format!("{}\n", 12u64 << 30)); + p.set(&format!("{base}/memory.usage_in_bytes"), &format!("{}\n", 11u64 << 30)); + p.set(&format!("{base}/memory.stat"), &format!("cache 1\ntotal_inactive_file {}\n", 512u64 << 20)); + p.set(&format!("{base}/memory.oom_control"), "oom_kill_disable 0\nunder_oom 0\noom_kill 2\n"); + p.set("/sys/fs/cgroup/memory/memory.limit_in_bytes", "9223372036854771712\n"); + p.set("/sys/fs/cgroup/memory/memory.usage_in_bytes", "123\n"); + let f = HostFacts::probe(&p); + let cg = f.cgroup.as_ref().unwrap(); + assert_eq!(cg.limit, Some((12 << 30, base.to_owned()))); + assert_eq!(cg.headroom, Some((1u64 << 30) + (512 << 20))); + assert_eq!(f.effective_available(), Some((1u64 << 30) + (512 << 20))); + assert_eq!(cg.events.unwrap().oom_kill, 2); +} + +#[test] +fn a_path_that_climbs_out_of_the_cgroup_root_is_not_followed() { + let mut p = server(); + p.set("/proc/self/cgroup", "0::/../../etc\n"); + assert!(HostFacts::probe(&p).cgroup.is_none()); +} + +#[test] +fn wsl_is_recognised_from_the_kernel_release() { + let mut p = server(); + p.set("/proc/sys/kernel/osrelease", "6.6.87.2-microsoft-standard-WSL2\n"); + assert!(HostFacts::probe(&p).wsl); +} + +#[test] +fn unknown_telemetry_stays_unknown() { + let f = HostFacts::probe(&FakeProc::default()); + assert_eq!(f.effective_available(), None); + assert_eq!(f.effective_total(), None); + assert_eq!(f.swap_free(), 0); +} diff --git a/crates/leleka-memory/src/inventory.rs b/crates/leleka-memory/src/inventory.rs index 892cba08..ba256f74 100644 --- a/crates/leleka-memory/src/inventory.rs +++ b/crates/leleka-memory/src/inventory.rs @@ -190,7 +190,8 @@ impl Inventory { } totals } - /// Host RAM the classes account for: everything except file-backed mappings (the OS file cache holds those and gives them back). + /// Host RAM the classes account for: everything except file-backed mappings (the OS file cache holds those and + /// gives them back). pub fn total_host(&self) -> u64 { self.lock().values().filter(|e| e.space.is_host() && e.space != Space::HostMapped).map(|e| e.bytes).sum() } @@ -215,50 +216,49 @@ impl Inventory { /// The startup table: one row per class, grouped by space, fixed-width. pub fn table(&self) -> String { let mut rows = self.entries(); - rows.sort_by(|a, b| { - (a.space, a.when, a.component.as_str(), a.class.as_str()).cmp(&( - b.space, - b.when, - b.component.as_str(), - b.class.as_str(), - )) - }); - let mut out = String::new(); - out.push_str(&format!( + rows.sort_by(|a, b| row_key(a).cmp(&row_key(b))); + let mut out = format!( "{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n", "space", "when", "component.class", "MiB", "peak MiB", "planned", "swap", "size formula" - )); - let mib = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0); + ); for e in &rows { - out.push_str(&format!( - "{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n", - e.space.label(), - e.when.label(), - e.id(), - mib(e.bytes), - mib(e.peak), - e.expected.map_or("-".to_owned(), mib), - if e.swappable { "yes" } else { "no" }, - e.formula - )); + out.push_str(&table_row(e)); } - out.push_str(&format!( - "{:<15} {:<11} {:<34} {:>11}\n{:<15} {:<11} {:<34} {:>11}\n{:<15} {:<11} {:<34} {:>11}\n", - "total", - "", - "host RAM (accounted)", - mib(self.total_host()), - "total", - "", - "file-mapped (page cache)", - mib(self.total_mapped()), - "total", - "", - "device (accounted)", - mib(self.total_device()) - )); + out.push_str(&self.total_rows()); out } + + /// The three total lines closing the table: host RAM, file-mapped memory, device memory. + fn total_rows(&self) -> String { + let total = + |label: &str, bytes: u64| format!("{:<15} {:<11} {:<34} {:>11}\n", "total", "", label, mib_text(bytes)); + total("host RAM (accounted)", self.total_host()) + + &total("file-mapped (page cache)", self.total_mapped()) + + &total("device (accounted)", self.total_device()) + } +} + +/// The order of the table: by space, when, component and class. +fn row_key(e: &Entry) -> (Space, When, &str, &str) { + (e.space, e.when, e.component.as_str(), e.class.as_str()) +} + +fn mib_text(bytes: u64) -> String { + format!("{:.1}", bytes as f64 / 1_048_576.0) +} + +fn table_row(e: &Entry) -> String { + format!( + "{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n", + e.space.label(), + e.when.label(), + e.id(), + mib_text(e.bytes), + mib_text(e.peak), + e.expected.map_or("-".to_owned(), mib_text), + if e.swappable { "yes" } else { "no" }, + e.formula + ) } #[cfg(test)] diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index 94d92b1f..39909b73 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -1,9 +1,10 @@ //! Memory safety for the Leleka runtime: an allocation inventory, a startup budget that refuses what cannot fit and -//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting the -//! OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak tests. +//! sizes the caches from what is left, a runtime pressure monitor that sheds load in a fixed order instead of letting +//! the OOM killer or a swap storm decide, a residency guard for the sealed KAR memfd, and the census used by the soak +//! tests. //! -//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) and -//! acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`. +//! Model-free and CUDA-free by design: the runtime feeds it numbers (what it will allocate, what the device reports) +//! and acts on its decisions (evict, refuse, lock). See `docs/memory-safety.md`. pub mod census; pub mod governor; diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index 79f4cafc..34962cd1 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -5,8 +5,9 @@ //! them to swap, which turns every PLE row read into a major fault. Three layers defend against it: //! //! 1. **Lock** the pages: `mmap` the descriptor read-only and `mlock` it in chunks. Needs `RLIMIT_MEMLOCK` >= the -//! archive or `CAP_IPC_LOCK`; the plan is decided from the limits first (`plan_lock`) so a host that cannot lock does not -//! fault 55 GB in for nothing, and the refusal carries the fix (`LimitMEMLOCK=infinity`, `ulimit -l`, `setcap`). +//! archive or `CAP_IPC_LOCK`; the plan is decided from the limits first (`plan_lock`) so a host that cannot lock +//! does not fault 55 GB in for nothing, and the refusal carries the fix (`LimitMEMLOCK=infinity`, `ulimit -l`, +//! `setcap`). //! 2. **Detect** swapped pages: the swap of the mapping from `/proc/self/smaps` (exact) and `mincore` (which pages). //! 3. **Heal**: when pages are found swapped out and the host has the memory, `MADV_POPULATE_READ` brings them back, //! rate limited and guarded by the same floors as everything else. diff --git a/crates/leleka-memory/src/lock/impl_lockmode.rs b/crates/leleka-memory/src/lock/impl_lockmode.rs index f49b5f6c..1a18bb62 100644 --- a/crates/leleka-memory/src/lock/impl_lockmode.rs +++ b/crates/leleka-memory/src/lock/impl_lockmode.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl LockMode, fn plan_lock, impl LockOutcome, fn residency_from_smaps, fn spans_bytes, fn check_spans .... +//! Moved out of the parent module by STRA-338: impl LockMode, fn plan_lock, impl LockOutcome, fn residency_from_smaps, +//! fn spans_bytes, fn check_spans .... #[allow(unused_imports)] use super::*; @@ -14,7 +15,27 @@ impl LockMode { } } -/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the capabilities? +/// What the operator can change when `RLIMIT_MEMLOCK` cannot cover `need` bytes. +fn memlock_advice(need: u64) -> Vec { + vec![ + format!( + "raise RLIMIT_MEMLOCK to at least {} MiB: systemd `LimitMEMLOCK=infinity` in the service unit (the \ + leleka unit sets it), or `ulimit -l unlimited` / /etc/security/limits.conf `memlock` for the user", + need >> 20 + ), + "or grant the binary CAP_IPC_LOCK (`setcap cap_ipc_lock+ep` / systemd `AmbientCapabilities=CAP_IPC_LOCK`)" + .into(), + concat!( + "without the lock the guard still detects swapped pages and pulls them back ", + "(MADV_POPULATE_READ); lower vm.swappiness and `MemoryLow=` on the service cgroup also keep the ", + "memfd out of swap" + ) + .into(), + ] +} + +/// Pure: can `len` bytes be locked given `RLIMIT_MEMLOCK` (`soft`, `hard`), what is already locked and the +/// capabilities? pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status: &ProcStatus) -> LockDecision { if mode == LockMode::Off { return LockDecision::Off; @@ -27,16 +48,7 @@ pub fn plan_lock(mode: LockMode, len: u64, memlock: Option<(u64, u64)>, status: match memlock { Some((soft, _)) if soft >= need => LockDecision::Attempt { raise_soft_to: None }, Some((_, hard)) if hard >= need => LockDecision::Attempt { raise_soft_to: Some(need) }, - Some((soft, hard)) => LockDecision::Insufficient { - need, - soft, - hard, - advice: vec![ - format!("raise RLIMIT_MEMLOCK to at least {} MiB: systemd `LimitMEMLOCK=infinity` in the service unit (the leleka unit sets it), or `ulimit -l unlimited` / /etc/security/limits.conf `memlock` for the user", need >> 20), - "or grant the binary CAP_IPC_LOCK (`setcap cap_ipc_lock+ep` / systemd `AmbientCapabilities=CAP_IPC_LOCK`)".into(), - "without the lock the guard still detects swapped pages and pulls them back (MADV_POPULATE_READ); lower vm.swappiness and `MemoryLow=` on the service cgroup also keep the memfd out of swap".into(), - ], - }, + Some((soft, hard)) => LockDecision::Insufficient { need, soft, hard, advice: memlock_advice(need) }, None => LockDecision::Attempt { raise_soft_to: None }, } } @@ -66,7 +78,8 @@ pub fn spans_bytes(spans: &[Span]) -> u64 { spans.iter().map(|s| s.1).sum() } -/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, disjoint, inside? +/// Are the spans usable for `mlock` / `madvise` on a mapping of `len` bytes: page-aligned starts, non-empty, sorted, +/// disjoint, inside? pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { let mut previous_end = 0u64; for (i, (offset, n)) in spans.iter().enumerate() { @@ -81,9 +94,9 @@ pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { Ok(()) } -/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, at most -/// `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A sparse archive -/// is walked with this so that nothing is ever asked of a hole. +/// The piece of the spans at position `pos` of their concatenation ("compact space"): `(offset in the mapping, bytes)`, +/// at most `max` bytes and never across the end of a span. `None` when `pos` is past the last byte (or `max` is 0). A +/// sparse archive is walked with this so that nothing is ever asked of a hole. pub fn compact_piece(spans: &[Span], pos: u64, max: u64) -> Option<(u64, u64)> { let mut start = 0u64; for (offset, n) in spans { diff --git a/crates/leleka-memory/src/lock/sys.rs b/crates/leleka-memory/src/lock/sys.rs index c4274096..eb11b13f 100644 --- a/crates/leleka-memory/src/lock/sys.rs +++ b/crates/leleka-memory/src/lock/sys.rs @@ -98,7 +98,8 @@ impl FdMapping { Ok(r) => r, Err(e) => return LockOutcome::Partial { locked: self.locked, wanted: total, why: e.to_string() }, }; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins + // pages. if unsafe { libc::mlock(ptr, n_usize) } != 0 { let e = io::Error::last_os_error(); return LockOutcome::Partial { locked: self.locked, wanted: total, why: format!("mlock: {e}") }; @@ -108,10 +109,29 @@ impl FdMapping { } LockOutcome::Locked { bytes: self.locked } } - /// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling `allow(bytes_that_may_fault_in)` before - /// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file - /// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the - /// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans. + /// `mlock` the `n` bytes at `offset` of the mapping; the reason when that fails. + fn mlock_range(&self, offset: u64, n: u64) -> Result<(), String> { + let (ptr, n_usize) = self.range(offset, n).map_err(|e| e.to_string())?; + // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. + if unsafe { libc::mlock(ptr, n_usize) } != 0 { + return Err(format!("mlock: {}", io::Error::last_os_error())); + } + Ok(()) + } + /// Ask `allow`, then `mlock` and record the `n` bytes at `offset`; the reason when either refuses. + fn lock_chunk(&mut self, offset: u64, n: u64, allow: &mut impl FnMut(u64) -> bool) -> Result<(), String> { + if !allow(n) { + return Err("host memory guard refused the next chunk".to_owned()); + } + self.mlock_range(offset, n)?; + self.locked_spans.push((offset, n)); + Ok(()) + } + /// Lock only `spans` (the extents a sparse archive holds), `chunk` bytes at a time, calling + /// `allow(bytes_that_may_fault_in)` before each; stop at the first refusal. The holes between the spans are never + /// touched: `mlock` of a hole in a shmem file allocates zero pages for it (the sparse copy would silently become + /// the full 55 GB again), so a range outside the spans is not representable here. `check_spans` runs first. The + /// counter `locked_bytes` is the sum of the locked spans. pub fn lock_ranges( &mut self, spans: &[super::Span], @@ -128,23 +148,9 @@ impl FdMapping { let mut done = 0u64; while done < span_len { let n = chunk.min(span_len - done); - if !allow(n) { - return LockOutcome::Partial { - locked, - wanted, - why: "host memory guard refused the next chunk".into(), - }; + if let Err(why) = self.lock_chunk(span_offset + done, n, &mut allow) { + return LockOutcome::Partial { locked, wanted, why }; } - let (ptr, n_usize) = match self.range(span_offset + done, n) { - Ok(r) => r, - Err(e) => return LockOutcome::Partial { locked, wanted, why: e.to_string() }, - }; - // SAFETY: `ptr..ptr+n_usize` lies inside our live mapping (checked by `range`); mlock only faults/pins pages. - if unsafe { libc::mlock(ptr, n_usize) } != 0 { - let e = io::Error::last_os_error(); - return LockOutcome::Partial { locked, wanted, why: format!("mlock: {e}") }; - } - self.locked_spans.push((span_offset + done, n)); done += n; locked += n; self.locked = locked; @@ -166,8 +172,8 @@ impl FdMapping { } self.locked = 0; } - /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the caller - /// may not write, newer kernels report every page resident: use the smaps number for totals. + /// Which 4 KiB pages of `offset..offset+n` are in memory (`mincore`), one flag per page. For a descriptor the + /// caller may not write, newer kernels report every page resident: use the smaps number for totals. pub fn incore(&self, offset: u64, n: u64) -> io::Result> { let (ptr, n_usize) = self.range(offset, n)?; let pages = n_usize.div_ceil(PAGE as usize); @@ -323,7 +329,8 @@ mod tests { #[test] fn locking_the_whole_mapping_of_a_sparse_memfd_does_allocate_the_holes_which_is_why_ranges_exist() { - // the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be needed + // the negative control of the test above: if this stopped allocating, the extents-only lock would no longer be + // needed let f = sparse_memfd(256, &[(10, 4), (100, 6)]); let mut m = FdMapping::map_readonly(f.as_fd(), (256 * PAGE) as usize).unwrap(); let outcome = m.lock(64 * PAGE, |_| true); diff --git a/crates/leleka-memory/src/plan.rs b/crates/leleka-memory/src/plan.rs index 1cb81ccb..ff527e1d 100644 --- a/crates/leleka-memory/src/plan.rs +++ b/crates/leleka-memory/src/plan.rs @@ -28,8 +28,8 @@ pub struct Policy { pub soft_floor: u64, /// Below this new requests are refused with 503 `memory_pressure`. pub hard_floor: u64, - /// Slack kept on top of `soft_floor` after the fixed footprint for the transients of one request - /// (a conversation checkpoint is ~118 MB, a prefix node state ~127 MB, import staging) and for lazy growth the plan does not model. + /// Slack kept on top of `soft_floor` after the fixed footprint for the transients of one request (a conversation + /// checkpoint is ~118 MB, a prefix node state ~127 MB, import staging) and for lazy growth the plan does not model. /// It is also the margin above the soft floor at which the caches stop admitting (see `Policy::admit_floor`). pub reserve: u64, /// Leaving a level needs this much margin above its threshold. @@ -40,8 +40,9 @@ pub struct Policy { pub prefix_cap: u64, /// An `auto` cache smaller than this is off. pub min_useful_cache: u64, - /// PSI is system wide and is raised by any reader streaming a file through the page cache (job 910: a `dd` of the KAR file drove `full` to - /// 5.2% with 68 GiB available), so it only counts while available memory is below this; above it the stalls are not about us. + /// PSI is system wide and is raised by any reader streaming a file through the page cache (job 910: a `dd` of the + /// KAR file drove `full` to 5.2% with 68 GiB available), so it only counts while available memory is below this; + /// above it the stalls are not about us. pub psi_guard_available: u64, /// PSI `some avg10` (percent of time stalled) that starts shedding. pub psi_some_shed: f64, diff --git a/crates/leleka-memory/src/plan/auto_prefix_budget.rs b/crates/leleka-memory/src/plan/auto_prefix_budget.rs index f3c8fcde..bfdafcc7 100644 --- a/crates/leleka-memory/src/plan/auto_prefix_budget.rs +++ b/crates/leleka-memory/src/plan/auto_prefix_budget.rs @@ -14,10 +14,10 @@ pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pi if bytes < policy.min_useful_cache { 0 } else { bytes } } -/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the wish**. -/// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM -/// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number. -/// Returns the granted bytes and the elastic memory it was clamped against. +/// An explicit `--prefix-cache-mib N` at stack open: the wish, clamped to what the host has now, **never above the +/// wish**. Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing +/// RAM elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's +/// number. Returns the granted bytes and the elastic memory it was clamped against. pub fn explicit_prefix_budget( wish: u64, available: Option, diff --git a/crates/leleka-memory/src/plan/impl_policy.rs b/crates/leleka-memory/src/plan/impl_policy.rs index b892cb71..b924df23 100644 --- a/crates/leleka-memory/src/plan/impl_policy.rs +++ b/crates/leleka-memory/src/plan/impl_policy.rs @@ -1,10 +1,12 @@ -//! Moved out of the parent module by STRA-338: impl Policy, impl FixedItem, impl std_fmt_Display, impl std_error_Error, fn gib, fn check_vram .... +//! Moved out of the parent module by STRA-338: impl Policy, impl FixedItem, impl std_fmt_Display, impl std_error_Error, +//! fn gib, fn check_vram .... #[allow(unused_imports)] use super::*; impl Policy { - /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`. + /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): + /// `soft_floor + reserve`. pub fn admit_floor(&self) -> u64 { self.soft_floor.saturating_add(self.reserve) } @@ -13,7 +15,8 @@ impl Policy { Self { soft_floor: (4 * GIB).max(mem_total / 32 / MIB * MIB), hard_floor: (2 * GIB).max(mem_total / 64 / MIB * MIB), - // 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in the real Codex CRM session (job 945) + // 2 GiB: the first long request and the cache's own overhead grew the process by ~1 GiB beyond the plan in + // the real Codex CRM session (job 945) reserve: 2 * GIB, hysteresis: GIB, cache_share_percent: 75, @@ -54,8 +57,25 @@ pub fn gib(bytes: u64) -> String { format!("{:.2} GiB", bytes as f64 / GIB as f64) } -/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the free -/// VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned. +/// The device does not have room for the measured fixed footprint. +fn vram_refusal(plan: &VramPlan, estimate: u64) -> Refusal { + Refusal { + code: "vram", + message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), + numbers: vec![ + ("vram free".into(), plan.free), + ("vram fixed footprint".into(), estimate), + ("vram headroom".into(), plan.headroom), + ], + advice: vec![ + "stop the other GPU processes (nvidia-smi)".into(), + "lower --gpu-budget / the expert slots / --kv-resident".into(), + ], + } +} + +/// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the +/// free VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned. pub fn check_vram( policy: &Policy, vram: VramFacts, @@ -67,19 +87,7 @@ pub fn check_vram( && plan.free < estimate.saturating_add(plan.headroom) && policy.enforce { - return Err(Refusal { - code: "vram", - message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), - numbers: vec![ - ("vram free".into(), plan.free), - ("vram fixed footprint".into(), estimate), - ("vram headroom".into(), plan.headroom), - ], - advice: vec![ - "stop the other GPU processes (nvidia-smi)".into(), - "lower --gpu-budget / the expert slots / --kv-resident".into(), - ], - }); + return Err(vram_refusal(&plan, estimate)); } let note = (plan.free < plan.budget).then(|| { format!( @@ -91,159 +99,240 @@ pub fn check_vram( Ok((plan, note)) } -/// The budget. Pure: no file system, no clock. -pub fn plan(input: &PlanInput) -> Result { - let policy = input.policy; - let mut notes: Vec = Vec::new(); - let fixed_bytes: u64 = input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum(); - let kar_to_create = match input.kar { - KarForm::MemfdToCreate { bytes } => bytes, - KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0, - }; - let vram = match input.vram { - Some(v) => { - let (plan, note) = check_vram(&policy, v, input.vram_budget, input.vram_fixed_estimate)?; - notes.extend(note); - Some(plan) - } - None => None, - }; - let Some(available) = input.host.effective_available() else { - notes.push( - "host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)" - .into(), - ); - return Ok(Plan { - available_before: None, - kar_to_create, - fixed_bytes, - fixed: input.fixed.clone(), - available_after_fixed: None, - elastic: 0, - resident_complement_bytes: 0, - prefix_bytes: 0, - conversation_checkpoints: 0, - conversation_bytes: 0, - soft_floor: policy.soft_floor, - hard_floor: policy.hard_floor, - policy, - blind: true, - vram, - notes, - }); - }; - let needs = fixed_bytes.saturating_add(kar_to_create); - let required_after = policy.soft_floor.saturating_add(policy.reserve); - let after = available.checked_sub(needs); - if after.is_none_or(|r| r < required_after) { - let mut advice = vec![ - "free host memory (stop other processes; `free -g` and the MemAvailable line of /proc/meminfo)".into(), - "use `--expert-source mapped` (read-only mappings of shard 0) instead of the ~50 GB resident copy".into(), - "use `--kar-archive-file` (read-only file) instead of a sealed memfd on small hosts".into(), - "lower --context-tokens (the pinned K/V image is sized by the serving context)".into(), - ]; - if input.host.wsl { - advice.push(wsl_advice().into()); - } - if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { - advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); - } - let mut numbers = vec![("available".to_owned(), available), ("fixed host footprint".to_owned(), fixed_bytes)]; - if kar_to_create > 0 { - numbers.push(("sealed KAR memfd to create".to_owned(), kar_to_create)); - } - numbers.push(("soft floor + reserve".to_owned(), required_after)); - numbers.push(("short by".to_owned(), required_after.saturating_add(needs).saturating_sub(available))); - let refusal = Refusal { - code: "host_ram", - message: format!( - "the fixed host footprint ({}) leaves {} of {} available, below the {} the runtime needs to stay out of swap and the OOM killer", - gib(needs), - after.map_or("nothing".to_owned(), gib), - gib(available), - gib(required_after) - ), - numbers, - advice, - }; - if policy.enforce { - return Err(refusal); - } - notes.push(format!("ENFORCEMENT OFF: {refusal}")); - } - let after = after.unwrap_or(0); - let mut elastic = after.saturating_sub(required_after); +/// What the host has and what the fixed items still take from it. +struct HostBudget { + available: u64, + fixed_bytes: u64, + kar_to_create: u64, + /// `soft_floor + reserve`: what must be left after the fixed footprint. + required_after: u64, +} - // 1. the resident complement (explicit, pinned at open) - let mut complement = 0; - if let Some(wish) = input.resident_complement { - complement = wish.min(elastic); - if complement < wish { - notes.push(format!( - "resident complement clamped from {} to {} (elastic memory)", - gib(wish), - gib(complement) - )); - } - elastic -= complement; +impl HostBudget { + fn needs(&self) -> u64 { + self.fixed_bytes.saturating_add(self.kar_to_create) } - // 2. the prefix cache, or the conversation checkpoints it replaces - let (mut prefix_bytes, mut checkpoints, mut conversation_bytes) = (0, 0, 0); - match input.prefix { - CacheWish::Off => { - let each = input.checkpoint_bytes.max(1); - checkpoints = input.conversation_checkpoints.min(elastic / each); - if checkpoints < input.conversation_checkpoints { - notes.push(format!( - "conversation checkpoints reduced from {} to {checkpoints} ({} each, elastic memory {})", - input.conversation_checkpoints, - gib(input.checkpoint_bytes), - gib(elastic) - )); - } - conversation_bytes = checkpoints * input.checkpoint_bytes; - } - CacheWish::Auto => { - let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; - let bytes = share.min(policy.prefix_cap) / MIB * MIB; - if bytes < policy.min_useful_cache { - notes.push(format!( - "prefix cache off: auto budget {} is below the useful minimum {}", - gib(bytes), - gib(policy.min_useful_cache) - )); - } else { - prefix_bytes = bytes; - } - } - CacheWish::Bytes(wish) => { - prefix_bytes = wish.min(elastic) / MIB * MIB; - if prefix_bytes < wish { - notes.push(format!( - "prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory", - gib(wish), - gib(prefix_bytes), - gib(elastic) - )); - } - } + /// Available memory after the fixed footprint; `None` when it does not even fit. + fn after(&self) -> Option { + self.available.checked_sub(self.needs()) } - Ok(Plan { - available_before: Some(available), +} + +/// The plan of a host without memory telemetry: caches off, the monitor sheds (fail closed). +fn blind_plan( + input: &PlanInput, + kar_to_create: u64, + fixed_bytes: u64, + vram: Option, + notes: Vec, +) -> Plan { + let policy = input.policy; + Plan { + available_before: None, kar_to_create, fixed_bytes, fixed: input.fixed.clone(), - available_after_fixed: Some(after), - elastic: elastic + complement, - resident_complement_bytes: complement, - prefix_bytes, - conversation_checkpoints: checkpoints, - conversation_bytes, + available_after_fixed: None, + elastic: 0, + resident_complement_bytes: 0, + prefix_bytes: 0, + conversation_checkpoints: 0, + conversation_bytes: 0, soft_floor: policy.soft_floor, hard_floor: policy.hard_floor, policy, - blind: false, + blind: true, vram, notes, + } +} + +/// What the operator can change when the fixed footprint does not leave room. +fn host_ram_advice(input: &PlanInput) -> Vec { + let mut advice = vec![ + "free host memory (stop other processes; `free -g` and the MemAvailable line of /proc/meminfo)".into(), + "use `--expert-source mapped` (read-only mappings of shard 0) instead of the ~50 GB resident copy".into(), + "use `--kar-archive-file` (read-only file) instead of a sealed memfd on small hosts".into(), + "lower --context-tokens (the pinned K/V image is sized by the serving context)".into(), + ]; + if input.host.wsl { + advice.push(wsl_advice().into()); + } + if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { + advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); + } + advice +} + +/// The fixed host footprint leaves less than `soft_floor + reserve`. +fn host_ram_refusal(input: &PlanInput, hb: &HostBudget) -> Refusal { + let (needs, available) = (hb.needs(), hb.available); + let mut numbers = vec![("available".to_owned(), available), ("fixed host footprint".to_owned(), hb.fixed_bytes)]; + if hb.kar_to_create > 0 { + numbers.push(("sealed KAR memfd to create".to_owned(), hb.kar_to_create)); + } + numbers.push(("soft floor + reserve".to_owned(), hb.required_after)); + numbers.push(("short by".to_owned(), hb.required_after.saturating_add(needs).saturating_sub(available))); + Refusal { + code: "host_ram", + message: format!( + "the fixed host footprint ({}) leaves {} of {} available, below the {} the runtime needs to stay out of \ + swap and the OOM killer", + gib(needs), + hb.after().map_or("nothing".to_owned(), gib), + gib(available), + gib(hb.required_after) + ), + numbers, + advice: host_ram_advice(input), + } +} + +/// The explicit resident complement (pinned at open), clamped to the elastic memory. +fn size_complement(input: &PlanInput, elastic: u64, notes: &mut Vec) -> u64 { + let Some(wish) = input.resident_complement else { + return 0; + }; + let complement = wish.min(elastic); + if complement < wish { + notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement))); + } + complement +} + +/// Conversation checkpoints, the replacement of a prefix cache that is off: how many fit. +fn size_checkpoints(input: &PlanInput, elastic: u64, notes: &mut Vec) -> u64 { + let each = input.checkpoint_bytes.max(1); + let checkpoints = input.conversation_checkpoints.min(elastic / each); + if checkpoints < input.conversation_checkpoints { + notes.push(format!( + "conversation checkpoints reduced from {} to {checkpoints} ({} each, elastic memory {})", + input.conversation_checkpoints, + gib(input.checkpoint_bytes), + gib(elastic) + )); + } + checkpoints +} + +/// An `auto` prefix cache: a share of the elastic memory, capped, or off when below the useful minimum. +fn size_auto_prefix(policy: &Policy, elastic: u64, notes: &mut Vec) -> u64 { + let share = (u128::from(elastic) * u128::from(policy.cache_share_percent.min(100)) / 100) as u64; + let bytes = share.min(policy.prefix_cap) / MIB * MIB; + if bytes < policy.min_useful_cache { + notes.push(format!( + "prefix cache off: auto budget {} is below the useful minimum {}", + gib(bytes), + gib(policy.min_useful_cache) + )); + return 0; + } + bytes +} + +/// An explicit prefix cache budget, clamped to the elastic memory. +fn size_wished_prefix(wish: u64, elastic: u64, notes: &mut Vec) -> u64 { + let bytes = wish.min(elastic) / MIB * MIB; + if bytes < wish { + notes.push(format!( + "prefix cache clamped from {} to {} (elastic memory {}); lower --prefix-cache-mib or free memory", + gib(wish), + gib(bytes), + gib(elastic) + )); + } + bytes +} + +/// The device plan of a host that reports free VRAM (refuses when the fixed footprint cannot fit). +fn plan_vram(input: &PlanInput, notes: &mut Vec) -> Result, Refusal> { + let Some(v) = input.vram else { + return Ok(None); + }; + let (plan, note) = check_vram(&input.policy, v, input.vram_budget, input.vram_fixed_estimate)?; + notes.extend(note); + Ok(Some(plan)) +} + +const BLIND_NOTE: &str = + "host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)"; + +/// Refuse when the fixed footprint leaves too little, unless enforcement is off (then say so in the notes). +fn check_enforced(input: &PlanInput, hb: &HostBudget, notes: &mut Vec) -> Result<(), Refusal> { + let refusal = host_ram_refusal(input, hb); + if input.policy.enforce { + return Err(refusal); + } + notes.push(format!("ENFORCEMENT OFF: {refusal}")); + Ok(()) +} + +/// How the elastic memory was divided between the caches. +struct Caches { + complement: u64, + /// What is left of the elastic memory after the complement. + elastic: u64, + prefix_bytes: u64, + checkpoints: u64, + conversation_bytes: u64, +} + +fn size_caches(input: &PlanInput, elastic: u64, notes: &mut Vec) -> Caches { + // 1. the resident complement (explicit, pinned at open) + let complement = size_complement(input, elastic, notes); + let elastic = elastic - complement; + let mut caches = Caches { complement, elastic, prefix_bytes: 0, checkpoints: 0, conversation_bytes: 0 }; + // 2. the prefix cache, or the conversation checkpoints it replaces + match input.prefix { + CacheWish::Off => { + caches.checkpoints = size_checkpoints(input, elastic, notes); + caches.conversation_bytes = caches.checkpoints * input.checkpoint_bytes; + } + CacheWish::Auto => caches.prefix_bytes = size_auto_prefix(&input.policy, elastic, notes), + CacheWish::Bytes(wish) => caches.prefix_bytes = size_wished_prefix(wish, elastic, notes), + } + caches +} + +/// Host bytes of the fixed items the runtime has yet to allocate. +fn fixed_host_bytes(input: &PlanInput) -> u64 { + input.fixed.iter().filter(|i| i.space.is_host()).map(|i| i.bytes).sum() +} + +/// The sealed memfd this process still has to create (an inherited one is already out of `MemAvailable`). +fn kar_bytes_to_create(input: &PlanInput) -> u64 { + match input.kar { + KarForm::MemfdToCreate { bytes } => bytes, + KarForm::MemfdInherited { .. } | KarForm::File { .. } => 0, + } +} + +/// The budget. Pure: no file system, no clock. +pub fn plan(input: &PlanInput) -> Result { + let mut notes: Vec = Vec::new(); + let (fixed_bytes, kar_to_create) = (fixed_host_bytes(input), kar_bytes_to_create(input)); + let vram = plan_vram(input, &mut notes)?; + let Some(available) = input.host.effective_available() else { + notes.push(BLIND_NOTE.into()); + return Ok(blind_plan(input, kar_to_create, fixed_bytes, vram, notes)); + }; + let required_after = input.policy.soft_floor.saturating_add(input.policy.reserve); + let hb = HostBudget { available, fixed_bytes, kar_to_create, required_after }; + let after = hb.after(); + if after.is_none_or(|r| r < required_after) { + check_enforced(input, &hb, &mut notes)?; + } + let after = after.unwrap_or(0); + let c = size_caches(input, after.saturating_sub(required_after), &mut notes); + Ok(Plan { + available_before: Some(available), + available_after_fixed: Some(after), + elastic: c.elastic + c.complement, + resident_complement_bytes: c.complement, + prefix_bytes: c.prefix_bytes, + conversation_checkpoints: c.checkpoints, + conversation_bytes: c.conversation_bytes, + blind: false, + ..blind_plan(input, kar_to_create, fixed_bytes, vram, notes) }) } diff --git a/crates/leleka-memory/src/plan/tests.rs b/crates/leleka-memory/src/plan/tests.rs index ee81d149..7a985921 100644 --- a/crates/leleka-memory/src/plan/tests.rs +++ b/crates/leleka-memory/src/plan/tests.rs @@ -170,8 +170,9 @@ fn auto_budget_at_open_follows_the_same_rule_and_fails_closed() { let b = auto_prefix_budget(Some(g(22)), &p, 0); assert!(b >= g(12) && b < g(13), "{b}"); // (22 - 4 - 2) x 75% assert!(auto_prefix_budget(Some(g(22)), &p, g(8)) < b); - // the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the host sat at 7.4 GiB - // available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and takes 75% of the rest + // the real Codex CRM session (e2e job 945): 14,064 MiB available at open. The old rule granted 7,476 MiB and the + // host sat at 7.4 GiB available once the cache was full; the governor keeps soft floor + reserve (6 GiB) out and + // takes 75% of the rest let crm = auto_prefix_budget(Some(14_064 * MIB), &p, 0); assert!(crm > 5 * GIB + 800 * MIB && crm < 6 * GIB + 100 * MIB, "{crm}"); assert!(14_064 * MIB - crm > 7 * GIB + 900 * MIB, "at least ~8 GiB stays available with the cache full"); @@ -191,7 +192,8 @@ fn floors_scale_with_very_large_hosts_only() { fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() { let p = Policy::for_host(g(121), false); let cap = 6144 * MIB; - // the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure ~14 GiB) + // the 5090 at turn 5 today (MemAvailable 8.6 GiB after the stack opened is the PLAN's view of the open-time figure + // ~14 GiB) let before = 14_064 * MIB; // the sparse memfd frees ~36.6 GiB of shmem: MemAvailable at open rises by that much let after = before + 36_600 * MIB; diff --git a/crates/leleka-memory/src/pressure.rs b/crates/leleka-memory/src/pressure.rs index ceedcf87..0ccbaf66 100644 --- a/crates/leleka-memory/src/pressure.rs +++ b/crates/leleka-memory/src/pressure.rs @@ -4,7 +4,8 @@ //! * [`Level::Normal`]: caches grow under their budgets. //! * [`Level::Shed`]: the caches stop admitting and give memory back (prefix cache evicted, conversation checkpoints //! dropped); requests are still served. -//! * [`Level::Reject`]: new requests are refused with 503 `memory_pressure` and `Retry-After`; everything sheddable is shed. +//! * [`Level::Reject`]: new requests are refused with 503 `memory_pressure` and `Retry-After`; everything sheddable is +//! shed. //! //! Unknown telemetry never reads as "plenty": a missing `MemAvailable` holds the level at `Shed`. @@ -108,162 +109,6 @@ impl Monitor { self.policy = policy; } - /// The level the sample asks for, with the margin added to every threshold when `relaxed` (stepping down). - fn target(&mut self, s: &Sample) -> (Level, String, Level) { - let p = &self.policy; - let mut level = Level::Normal; - let mut why = String::from("within budget"); - // the level the sample asks for if the hysteresis margin is applied (to decide a step down) - let mut relaxed_level = Level::Normal; - let raise = |l: Level, relaxed: Level, reason: String, level: &mut Level, why: &mut String, rl: &mut Level| { - if l > *level { - *level = l; - *why = reason; - } - if relaxed > *rl { - *rl = relaxed; - } - }; - match s.available { - None => raise( - Level::Shed, - Level::Shed, - "available memory unknown (fail closed)".into(), - &mut level, - &mut why, - &mut relaxed_level, - ), - Some(a) => { - let (hard, soft, h) = (p.hard_floor, p.soft_floor, p.hysteresis); - let at = |floor: u64| a < floor; - let at_relaxed = |floor: u64| a < floor.saturating_add(h); - if at(hard) { - raise( - Level::Reject, - Level::Reject, - format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20), - &mut level, - &mut why, - &mut relaxed_level, - ); - } else if at(soft) { - raise( - Level::Shed, - Level::Shed, - format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20), - &mut level, - &mut why, - &mut relaxed_level, - ); - } - // what the relaxed (stepping-down) view still holds - let r = if at_relaxed(hard) { - Level::Reject - } else if at_relaxed(soft) { - Level::Shed - } else { - Level::Normal - }; - if r > relaxed_level { - relaxed_level = r; - } - } - } - // stalls count only while memory is not plentiful (see `Policy::psi_guard_available`); unknown available memory counts - let psi_counts = s.available.is_none_or(|a| a < p.psi_guard_available); - if let Some(psi) = s.psi.filter(|_| psi_counts) { - self.observed.psi_some_avg10 = Some(psi.some.avg10); - self.observed.psi_full_avg10 = Some(psi.full.avg10); - if psi.full.avg10 >= p.psi_full_reject { - raise( - Level::Reject, - Level::Reject, - format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject), - &mut level, - &mut why, - &mut relaxed_level, - ); - } else if psi.some.avg10 >= p.psi_some_shed { - raise( - Level::Shed, - Level::Shed, - format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed), - &mut level, - &mut why, - &mut relaxed_level, - ); - } - // PSI avg10 decays smoothly; stepping down needs it clearly below the limit - if psi.full.avg10 >= p.psi_full_reject / 2.0 { - relaxed_level = relaxed_level.max(Level::Shed); - } - if psi.some.avg10 >= p.psi_some_shed / 2.0 { - relaxed_level = relaxed_level.max(Level::Shed); - } - } else { - self.observed.psi_some_avg10 = s.psi.map(|p| p.some.avg10); - self.observed.psi_full_avg10 = s.psi.map(|p| p.full.avg10); - } - if let (Some(now), Some(before)) = (s.events, self.prev_events) { - let d = |a: u64, b: u64| a.saturating_sub(b); - self.observed.cgroup_high_delta = d(now.high, before.high); - self.observed.cgroup_max_delta = d(now.max, before.max); - self.observed.cgroup_oom_delta = d(now.oom, before.oom).max(d(now.oom_kill, before.oom_kill)); - if self.observed.cgroup_oom_delta > 0 { - raise( - Level::Reject, - Level::Reject, - format!("cgroup oom events +{}", self.observed.cgroup_oom_delta), - &mut level, - &mut why, - &mut relaxed_level, - ); - } else if self.observed.cgroup_max_delta > 0 || self.observed.cgroup_high_delta > 0 { - raise( - Level::Shed, - Level::Shed, - format!( - "cgroup memory.high +{} / memory.max +{} events", - self.observed.cgroup_high_delta, self.observed.cgroup_max_delta - ), - &mut level, - &mut why, - &mut relaxed_level, - ); - } - } - if s.events.is_some() { - self.prev_events = s.events; - } - if let Some(out) = s.pswpout { - if let Some((t0, o0)) = self.prev_swap { - let dt = s.at_ms.saturating_sub(t0); - if dt >= 500 { - let rate = out.saturating_sub(o0) * 1000 / dt; - self.observed.swapout_pages_per_s = Some(rate); - if rate >= p.swapout_pages_per_s_shed { - raise( - Level::Shed, - Level::Shed, - format!("swap-out {rate} pages/s (limit {})", p.swapout_pages_per_s_shed), - &mut level, - &mut why, - &mut relaxed_level, - ); - } - if rate >= p.swapout_pages_per_s_shed / 2 { - relaxed_level = relaxed_level.max(Level::Shed); - } - self.prev_swap = Some((s.at_ms, out)); - } - } else { - self.prev_swap = Some((s.at_ms, out)); - } - } - self.observed.available = s.available; - (level, why, relaxed_level) - } - /// Feed one sample. Escalation is immediate; stepping down one level needs [`CALM_SAMPLES`] calm samples. pub fn update(&mut self, s: &Sample) -> Option { let (wanted, why, relaxed) = self.target(s); @@ -303,5 +148,7 @@ impl Monitor { } } +mod ask; + #[cfg(test)] mod tests; diff --git a/crates/leleka-memory/src/pressure/ask.rs b/crates/leleka-memory/src/pressure/ask.rs new file mode 100644 index 00000000..78ec7e94 --- /dev/null +++ b/crates/leleka-memory/src/pressure/ask.rs @@ -0,0 +1,134 @@ +//! The level a sample asks for: one step per signal (available memory, PSI, cgroup events, swap-out rate), each +//! raising the asked level and the level that still holds once the hysteresis margin is added. + +use super::*; + +/// The level a sample asks for, why, and the level that still holds with the hysteresis margin added to every +/// threshold (to decide a step down). +struct Ask { + level: Level, + why: String, + relaxed: Level, +} + +impl Ask { + fn new() -> Self { + Self { level: Level::Normal, why: String::from("within budget"), relaxed: Level::Normal } + } + + /// A signal asks for `level` (and still holds it relaxed). + fn raise(&mut self, level: Level, reason: String) { + if level > self.level { + self.level = level; + self.why = reason; + } + self.hold(level); + } + + /// The relaxed view still holds at least `level`. + fn hold(&mut self, level: Level) { + self.relaxed = self.relaxed.max(level); + } +} + +/// Available memory against the floors, and against the floors plus the margin. +fn ask_available_known(a: u64, p: &Policy, ask: &mut Ask) { + let (hard, soft, h) = (p.hard_floor, p.soft_floor, p.hysteresis); + if a < hard { + ask.raise(Level::Reject, format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20)); + } else if a < soft { + ask.raise(Level::Shed, format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20)); + } + // what the relaxed (stepping-down) view still holds + let relaxed = if a < hard.saturating_add(h) { + Level::Reject + } else if a < soft.saturating_add(h) { + Level::Shed + } else { + Level::Normal + }; + ask.hold(relaxed); +} + +/// Stalls: `full` refuses, `some` sheds; stepping down needs them clearly below the limit. +fn ask_psi_levels(psi: Psi, p: &Policy, ask: &mut Ask) { + if psi.full.avg10 >= p.psi_full_reject { + ask.raise(Level::Reject, format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject)); + } else if psi.some.avg10 >= p.psi_some_shed { + ask.raise(Level::Shed, format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed)); + } + // PSI avg10 decays smoothly; stepping down needs it clearly below the limit + if psi.full.avg10 >= p.psi_full_reject / 2.0 || psi.some.avg10 >= p.psi_some_shed / 2.0 { + ask.hold(Level::Shed); + } +} + +impl Monitor { + /// The level the sample asks for, why, and the level that holds with the margin added to every threshold. + pub(super) fn target(&mut self, s: &Sample) -> (Level, String, Level) { + let mut ask = Ask::new(); + match s.available { + None => ask.raise(Level::Shed, "available memory unknown (fail closed)".into()), + Some(a) => ask_available_known(a, &self.policy, &mut ask), + } + self.ask_psi(s, &mut ask); + self.ask_cgroup(s, &mut ask); + self.ask_swapout(s, &mut ask); + self.observed.available = s.available; + (ask.level, ask.why, ask.relaxed) + } + + fn ask_psi(&mut self, s: &Sample, ask: &mut Ask) { + self.observed.psi_some_avg10 = s.psi.map(|p| p.some.avg10); + self.observed.psi_full_avg10 = s.psi.map(|p| p.full.avg10); + // stalls count only while memory is not plentiful (see `Policy::psi_guard_available`); unknown available memory + // counts + let psi_counts = s.available.is_none_or(|a| a < self.policy.psi_guard_available); + if let Some(psi) = s.psi.filter(|_| psi_counts) { + ask_psi_levels(psi, &self.policy, ask); + } + } + + fn ask_cgroup(&mut self, s: &Sample, ask: &mut Ask) { + if let (Some(now), Some(before)) = (s.events, self.prev_events) { + let d = |a: u64, b: u64| a.saturating_sub(b); + let o = &mut self.observed; + o.cgroup_high_delta = d(now.high, before.high); + o.cgroup_max_delta = d(now.max, before.max); + o.cgroup_oom_delta = d(now.oom, before.oom).max(d(now.oom_kill, before.oom_kill)); + if o.cgroup_oom_delta > 0 { + ask.raise(Level::Reject, format!("cgroup oom events +{}", o.cgroup_oom_delta)); + } else if o.cgroup_max_delta > 0 || o.cgroup_high_delta > 0 { + let reason = + format!("cgroup memory.high +{} / memory.max +{} events", o.cgroup_high_delta, o.cgroup_max_delta); + ask.raise(Level::Shed, reason); + } + } + if s.events.is_some() { + self.prev_events = s.events; + } + } + + /// The system-wide swap-out rate between two samples at least 500 ms apart. + fn ask_swapout(&mut self, s: &Sample, ask: &mut Ask) { + let Some(out) = s.pswpout else { return }; + let Some((t0, o0)) = self.prev_swap else { + self.prev_swap = Some((s.at_ms, out)); + return; + }; + let dt = s.at_ms.saturating_sub(t0); + if dt < 500 { + return; + } + let limit = self.policy.swapout_pages_per_s_shed; + let rate = out.saturating_sub(o0) * 1000 / dt; + self.observed.swapout_pages_per_s = Some(rate); + if rate >= limit { + ask.raise(Level::Shed, format!("swap-out {rate} pages/s (limit {limit})")); + } + if rate >= limit / 2 { + ask.hold(Level::Shed); + } + self.prev_swap = Some((s.at_ms, out)); + } +} diff --git a/crates/leleka-memory/src/pressure/tests.rs b/crates/leleka-memory/src/pressure/tests.rs index 57c6973d..c5198977 100644 --- a/crates/leleka-memory/src/pressure/tests.rs +++ b/crates/leleka-memory/src/pressure/tests.rs @@ -86,7 +86,8 @@ fn psi_stalls_shed_and_reject_independent_of_available_memory() { full: PsiLine { avg10: full, ..Default::default() }, }) }; - // above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free changes nothing + // above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free + // changes nothing assert!( m.update(&Sample { at_ms: 0, available: Some(30 * GIB), psi: psi(60.0, 20.0), ..Sample::default() }).is_none() ); diff --git a/crates/leleka-memory/src/procfs.rs b/crates/leleka-memory/src/procfs.rs index f9b69823..8e907e7e 100644 --- a/crates/leleka-memory/src/procfs.rs +++ b/crates/leleka-memory/src/procfs.rs @@ -38,6 +38,35 @@ pub struct MemInfo { pub hugepage_size: Option, } +/// The `/proc/meminfo` keys of [`MemInfo`] and where each one lives. +type MemInfoSlot = fn(&mut MemInfo) -> &mut Option; +const MEMINFO_FIELDS: [(&str, MemInfoSlot); 17] = [ + ("MemTotal", |i| &mut i.mem_total), + ("MemFree", |i| &mut i.mem_free), + ("MemAvailable", |i| &mut i.mem_available), + ("Buffers", |i| &mut i.buffers), + ("Cached", |i| &mut i.cached), + ("SwapCached", |i| &mut i.swap_cached), + ("SwapTotal", |i| &mut i.swap_total), + ("SwapFree", |i| &mut i.swap_free), + ("Shmem", |i| &mut i.shmem), + ("Mlocked", |i| &mut i.mlocked), + ("Unevictable", |i| &mut i.unevictable), + ("AnonPages", |i| &mut i.anon_pages), + ("Active(file)", |i| &mut i.active_file), + ("Inactive(file)", |i| &mut i.inactive_file), + ("Hugetlb", |i| &mut i.hugetlb), + ("HugePages_Total", |i| &mut i.hugepages_total), + ("Hugepagesize", |i| &mut i.hugepage_size), +]; + +/// The keys the governor decides on: a duplicated or malformed one makes the field unknown. +const POISONABLE: [&str; 6] = ["MemTotal", "MemFree", "MemAvailable", "SwapTotal", "SwapFree", "Shmem"]; + +fn meminfo_slot<'a>(info: &'a mut MemInfo, key: &str) -> Option<&'a mut Option> { + MEMINFO_FIELDS.iter().find(|(name, _)| *name == key).map(|(_, slot)| slot(info)) +} + /// Parse `/proc/meminfo` text. A duplicated key makes that field unknown (never "the last one wins"). pub fn parse_meminfo(text: &str) -> MemInfo { let mut info = MemInfo::default(); @@ -47,47 +76,17 @@ pub fn parse_meminfo(text: &str) -> MemInfo { let Some((key, rest)) = line.split_once(':') else { continue }; let mut fields = rest.split_ascii_whitespace(); let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; - if fields.next().is_some() { - poisoned.push(key); - continue; - } - if seen.contains(&key) { + if fields.next().is_some() || seen.contains(&key) { poisoned.push(key); continue; } seen.push(key); - let parsed = if key == "HugePages_Total" { value.parse().ok() } else { kib(value, unit) }; - let slot = match key { - "MemTotal" => &mut info.mem_total, - "MemFree" => &mut info.mem_free, - "MemAvailable" => &mut info.mem_available, - "Buffers" => &mut info.buffers, - "Cached" => &mut info.cached, - "SwapCached" => &mut info.swap_cached, - "SwapTotal" => &mut info.swap_total, - "SwapFree" => &mut info.swap_free, - "Shmem" => &mut info.shmem, - "Mlocked" => &mut info.mlocked, - "Unevictable" => &mut info.unevictable, - "AnonPages" => &mut info.anon_pages, - "Active(file)" => &mut info.active_file, - "Inactive(file)" => &mut info.inactive_file, - "Hugetlb" => &mut info.hugetlb, - "HugePages_Total" => &mut info.hugepages_total, - "Hugepagesize" => &mut info.hugepage_size, - _ => continue, - }; - *slot = parsed; + let Some(slot) = meminfo_slot(&mut info, key) else { continue }; + *slot = if key == "HugePages_Total" { value.parse().ok() } else { kib(value, unit) }; } - for key in poisoned { - match key { - "MemTotal" => info.mem_total = None, - "MemFree" => info.mem_free = None, - "MemAvailable" => info.mem_available = None, - "SwapTotal" => info.swap_total = None, - "SwapFree" => info.swap_free = None, - "Shmem" => info.shmem = None, - _ => {} + for key in poisoned.into_iter().filter(|key| POISONABLE.contains(key)) { + if let Some(slot) = meminfo_slot(&mut info, key) { + *slot = None; } } info @@ -111,32 +110,35 @@ pub struct ProcStatus { pub cap_eff: Option, } +fn status_slot<'a>(status: &'a mut ProcStatus, key: &str) -> Option<&'a mut Option> { + match key { + "VmRSS" => Some(&mut status.vm_rss), + "VmHWM" => Some(&mut status.vm_hwm), + "VmSwap" => Some(&mut status.vm_swap), + "VmLck" => Some(&mut status.vm_lck), + "VmPin" => Some(&mut status.vm_pin), + "RssAnon" => Some(&mut status.rss_anon), + "RssFile" => Some(&mut status.rss_file), + "RssShmem" => Some(&mut status.rss_shmem), + _ => None, + } +} + pub fn parse_status(text: &str) -> ProcStatus { let mut status = ProcStatus::default(); for line in text.lines() { let Some((key, rest)) = line.split_once(':') else { continue }; let mut fields = rest.split_ascii_whitespace(); let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; - let slot = match key { - "VmRSS" => &mut status.vm_rss, - "VmHWM" => &mut status.vm_hwm, - "VmSwap" => &mut status.vm_swap, - "VmLck" => &mut status.vm_lck, - "VmPin" => &mut status.vm_pin, - "RssAnon" => &mut status.rss_anon, - "RssFile" => &mut status.rss_file, - "RssShmem" => &mut status.rss_shmem, - "Threads" => { - status.threads = value.parse().ok(); - continue; + match key { + "Threads" => status.threads = value.parse().ok(), + "CapEff" => status.cap_eff = u64::from_str_radix(value, 16).ok(), + _ => { + if let Some(slot) = status_slot(&mut status, key) { + *slot = kib(value, unit); + } } - "CapEff" => { - status.cap_eff = u64::from_str_radix(value, 16).ok(); - continue; - } - _ => continue, - }; - *slot = kib(value, unit); + } } status } @@ -166,27 +168,37 @@ pub struct Psi { pub full: PsiLine, } +/// One `key=value` field of a PSI line: `Some(false)` for a key that is not read, `None` for a malformed number. +fn psi_field(line: &mut PsiLine, key: &str, value: &str) -> Option { + match key { + "avg10" => line.avg10 = value.parse().ok()?, + "avg60" => line.avg60 = value.parse().ok()?, + "avg300" => line.avg300 = value.parse().ok()?, + "total" => line.total_us = value.parse().ok()?, + _ => return Some(false), + } + Some(true) +} + +/// The fields after `some` / `full`: all four of avg10, avg60, avg300 and total, with finite averages. +fn parse_psi_line<'a>(fields: impl Iterator) -> Option { + let mut parsed = PsiLine::default(); + let mut complete = 0; + for field in fields { + let (key, value) = field.split_once('=')?; + complete += usize::from(psi_field(&mut parsed, key, value)?); + } + let finite = parsed.avg10.is_finite() && parsed.avg60.is_finite() && parsed.avg300.is_finite(); + (complete == 4 && finite).then_some(parsed) +} + pub fn parse_psi(text: &str) -> Option { let mut psi = Psi::default(); let (mut some, mut full) = (false, false); for line in text.lines() { let mut fields = line.split_ascii_whitespace(); let kind = fields.next()?; - let mut parsed = PsiLine::default(); - let mut complete = 0; - for field in fields { - let (key, value) = field.split_once('=')?; - match key { - "avg10" => (parsed.avg10, complete) = (value.parse().ok()?, complete + 1), - "avg60" => (parsed.avg60, complete) = (value.parse().ok()?, complete + 1), - "avg300" => (parsed.avg300, complete) = (value.parse().ok()?, complete + 1), - "total" => (parsed.total_us, complete) = (value.parse().ok()?, complete + 1), - _ => {} - } - } - if complete != 4 || !parsed.avg10.is_finite() || !parsed.avg60.is_finite() || !parsed.avg300.is_finite() { - return None; - } + let parsed = parse_psi_line(fields)?; match kind { "some" => (psi.some, some) = (parsed, true), "full" => (psi.full, full) = (parsed, true), @@ -272,38 +284,51 @@ pub struct SmapsEntry { pub shmem_pmd_mapped: u64, } +/// A mapping header line: `start-end perms offset dev inode [path...]`. +fn is_smaps_header(line: &str) -> bool { + let first = line.split_ascii_whitespace().next().unwrap_or(""); + first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':') +} + +/// The entry a header line opens; `None` for a malformed range. +fn parse_smaps_header(line: &str) -> Option { + let mut fields = line.split_ascii_whitespace(); + let range = fields.next().unwrap_or(""); + let perms = fields.next().unwrap_or("").to_owned(); + // offset dev inode [path...] + let _offset = fields.next(); + let _dev = fields.next(); + let _inode = fields.next(); + let path = fields.collect::>().join(" "); + let (a, b) = range.split_once('-')?; + let (Ok(start), Ok(end)) = (u64::from_str_radix(a, 16), u64::from_str_radix(b, 16)) else { return None }; + Some(SmapsEntry { start, end, perms, path, ..SmapsEntry::default() }) +} + +/// A `Key: value kB` counter line of the current entry; anything else is skipped. +fn apply_smaps_counter(entry: &mut SmapsEntry, line: &str) { + let Some((key, rest)) = line.split_once(':') else { return }; + let mut fields = rest.split_ascii_whitespace(); + let (Some(value), unit) = (fields.next(), fields.next()) else { return }; + let Some(bytes) = kib(value, unit) else { return }; + match key { + "Size" => entry.size = bytes, + "Rss" => entry.rss = bytes, + "Swap" => entry.swap = bytes, + "Locked" => entry.locked = bytes, + "ShmemPmdMapped" => entry.shmem_pmd_mapped = bytes, + _ => {} + } +} + /// Parse `/proc/self/smaps`. A malformed header or counter line stops the entry (never fabricates numbers). pub fn parse_smaps(text: &str) -> Vec { let mut entries: Vec = Vec::new(); for line in text.lines() { - let first = line.split_ascii_whitespace().next().unwrap_or(""); - let is_header = - first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':'); - if is_header { - let mut fields = line.split_ascii_whitespace(); - let range = fields.next().unwrap_or(""); - let perms = fields.next().unwrap_or("").to_owned(); - // offset dev inode [path...] - let _offset = fields.next(); - let _dev = fields.next(); - let _inode = fields.next(); - let path = fields.collect::>().join(" "); - let Some((a, b)) = range.split_once('-') else { continue }; - let (Ok(start), Ok(end)) = (u64::from_str_radix(a, 16), u64::from_str_radix(b, 16)) else { continue }; - entries.push(SmapsEntry { start, end, perms, path, ..SmapsEntry::default() }); + if is_smaps_header(line) { + entries.extend(parse_smaps_header(line)); } else if let Some(entry) = entries.last_mut() { - let Some((key, rest)) = line.split_once(':') else { continue }; - let mut fields = rest.split_ascii_whitespace(); - let (Some(value), unit) = (fields.next(), fields.next()) else { continue }; - let Some(bytes) = kib(value, unit) else { continue }; - match key { - "Size" => entry.size = bytes, - "Rss" => entry.rss = bytes, - "Swap" => entry.swap = bytes, - "Locked" => entry.locked = bytes, - "ShmemPmdMapped" => entry.shmem_pmd_mapped = bytes, - _ => {} - } + apply_smaps_counter(entry, line); } } entries diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index 801bee55..d9792193 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -27,7 +27,8 @@ pub const RUN_LIMIT: Duration = Duration::from_secs(5); const EXTRA_LOCATIONS: [&str; 3] = ["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"]; -/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and anything else. +/// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and +/// anything else. fn number(field: &str) -> Option { let field = field.trim(); if field.is_empty() || field.starts_with('[') || field.eq_ignore_ascii_case("n/a") { @@ -77,10 +78,9 @@ pub fn find_binary() -> Option { from_path.or_else(|| EXTRA_LOCATIONS.iter().map(std::path::PathBuf::from).find(|candidate| candidate.is_file())) } -/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed out or -/// printed something unusable. -pub fn query(binary: &std::path::Path, index: u32) -> Option { - let mut child = Command::new(binary) +/// Start `nvidia-smi` for [`QUERY`] on device `index`, its standard output piped. +fn spawn_query(binary: &std::path::Path, index: u32) -> Option { + Command::new(binary) .arg(format!("--query-gpu={QUERY}")) .arg("--format=csv,noheader,nounits") .arg("-i") @@ -89,7 +89,13 @@ pub fn query(binary: &std::path::Path, index: u32) -> Option { .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() - .ok()?; + .ok() +} + +/// Run `nvidia-smi` for [`QUERY`] on device `index` and parse the answer. `None`: the binary is missing, failed, timed +/// out or printed something unusable. +pub fn query(binary: &std::path::Path, index: u32) -> Option { + let mut child = spawn_query(binary, index)?; let mut stdout = child.stdout.take()?; let started = Instant::now(); loop { @@ -159,7 +165,8 @@ mod tests { #[test] fn output_captured_from_real_drivers_parses() { - // `nvidia-smi --query-gpu= --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02, Linux) + // `nvidia-smi --query-gpu= --format=csv,noheader,nounits` on the RTX 5090 server (driver 595.99.02, + // Linux) let server = parse_csv("0, 94, 21, 31606, 32607, 271.40, 2887, 58, NVIDIA GeForce RTX 5090\n", 0).unwrap(); assert_eq!((server.util_pct, server.vram_used_mib, server.vram_total_mib), (94, 31606, 32607)); assert_eq!((server.power_w, server.sm_clock_mhz, server.temp_c), (Some(271.4), Some(2887), Some(58))); diff --git a/crates/leleka-memory/src/telemetry.rs b/crates/leleka-memory/src/telemetry.rs index 36057696..339f1770 100644 --- a/crates/leleka-memory/src/telemetry.rs +++ b/crates/leleka-memory/src/telemetry.rs @@ -89,7 +89,8 @@ struct State { decode_ema: Option, context_live: u64, context_max: u64, - /// Non-finite verify windows (upstream's NaN guard): retried from the round's checkpoint and then fine, or given up on. + /// Non-finite verify windows (upstream's NaN guard): retried from the round's checkpoint and then fine, or given up + /// on. nan_healed: u64, nan_unhealed: u64, nan_last: Option, @@ -97,7 +98,8 @@ struct State { spec_rounds: u64, spec_tokens: u64, last_request: Option, - /// The expert tier's counters as of the last finished request (lifetime of the stack, so a delta is a request's share). + /// The expert tier's counters as of the last finished request (lifetime of the stack, so a delta is a request's + /// share). expert_tier: Option, } @@ -215,7 +217,8 @@ struct LiveRequest { elapsed_s: f64, } -/// Speculative decode as the operator reads it: committed tokens per verified round (1.0 would be no gain from drafting). +/// Speculative decode as the operator reads it: committed tokens per verified round (1.0 would be no gain from +/// drafting). #[derive(Debug, Serialize)] struct Spec { rounds: u64, diff --git a/crates/leleka-memory/src/telemetry/lock.rs b/crates/leleka-memory/src/telemetry/lock.rs index a3303467..fb092c81 100644 --- a/crates/leleka-memory/src/telemetry/lock.rs +++ b/crates/leleka-memory/src/telemetry/lock.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn lock, fn with_state, fn published_telemetry, fn set_settings, fn set_context_max, fn request_started .... +//! Moved out of the parent module by STRA-338: fn lock, fn with_state, fn published_telemetry, fn set_settings, fn +//! set_context_max, fn request_started .... #[allow(unused_imports)] use super::*; @@ -16,7 +17,8 @@ pub fn published_telemetry() -> Option { lock(&PUBLISHED).clone() } -/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the document. +/// The settings the engine runs with now (context, prefill chunk, caches, workers...): rendered as `settings` in the +/// document. pub fn set_settings(settings: serde_json::Value) { *lock(&SETTINGS) = Some(settings); } @@ -26,7 +28,8 @@ pub fn set_context_max(tokens: u64) { with_state(|s| s.context_max = tokens); } -/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the figures of the last finished request stay until then). +/// A request entered the engine with `prompt_tokens` in its prompt (the cache hit is known when it finishes; the +/// figures of the last finished request stay until then). pub fn request_started(prompt_tokens: u64) { request_started_at(prompt_tokens, SystemClock.now()); } @@ -60,8 +63,9 @@ pub fn tokens_delivered_at(count: u64, at: Instant) { }); } -/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the retry was good. -/// `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in the document. +/// The NaN guard retried a window whose logits or stage outputs were not finite from the round's checkpoint, and the +/// retry was good. `what` names it for the operator (position, rows, attempt, the error class); the last one is kept in +/// the document. pub fn nan_guard_healed(what: &str) { with_state(|s| { s.nan_healed += 1; @@ -69,7 +73,8 @@ pub fn nan_guard_healed(what: &str) { }); } -/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request fails as before. +/// The NaN guard gave up on a non-finite window (no retry left, or the checkpoint could not be restored): the request +/// fails as before. pub fn nan_guard_unhealed(what: &str) { with_state(|s| { s.nan_unhealed += 1; @@ -86,6 +91,30 @@ pub fn request_aborted() { }); } +impl State { + /// Fold the prompt tokens this request really prefilled (not the reused ones) into the prefill rates. + fn fold_prefill(&mut self, prefilled: u64, prompt_ms: f64) { + if prefilled > 0 && prompt_ms > 0.0 { + let rate = prefilled as f64 * 1e3 / prompt_ms; + self.prefill_tokens += prefilled; + self.prefill_ms += prompt_ms; + self.last_prefill_tok_s = Some(rate); + self.prefill_ema = Some(ema(self.prefill_ema, rate)); + } + } + + /// Fold the tokens this request decoded into the decode rates. + fn fold_decode(&mut self, produced: u64, decode_ms: f64) { + if produced > 0 && decode_ms > 0.0 { + let rate = produced as f64 * 1e3 / decode_ms; + self.decode_tokens += produced; + self.decode_ms += decode_ms; + self.last_decode_tok_s = Some(rate); + self.decode_ema = Some(ema(self.decode_ema, rate)); + } + } +} + /// A request finished (any outcome that produced numbers): fold it into the lifetime figures. pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, prompt_ms: f64, decode_ms: f64) { with_state(|s| { @@ -105,21 +134,8 @@ pub fn request_finished(prompt_tokens: u64, reused_tokens: u64, produced: u64, p s.last_prefill_ms = prompt_ms; s.last_decode_ms = decode_ms; s.context_live = prompt_tokens + produced; - let prefilled = prompt_tokens.saturating_sub(reused_tokens); - if prefilled > 0 && prompt_ms > 0.0 { - let rate = prefilled as f64 * 1e3 / prompt_ms; - s.prefill_tokens += prefilled; - s.prefill_ms += prompt_ms; - s.last_prefill_tok_s = Some(rate); - s.prefill_ema = Some(ema(s.prefill_ema, rate)); - } - if produced > 0 && decode_ms > 0.0 { - let rate = produced as f64 * 1e3 / decode_ms; - s.decode_tokens += produced; - s.decode_ms += decode_ms; - s.last_decode_tok_s = Some(rate); - s.decode_ema = Some(ema(s.decode_ema, rate)); - } + s.fold_prefill(prompt_tokens.saturating_sub(reused_tokens), prompt_ms); + s.fold_decode(produced, decode_ms); }); } @@ -146,8 +162,9 @@ pub fn request_detail(request_id: &str, rounds: u64, tier: Option) }); } -/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the counters are -/// the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, when they went back). +/// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the +/// counters are the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, +/// when they went back). pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, f64, f64) { let base = previous.filter(|p| { now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries @@ -163,8 +180,8 @@ pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, (pct(v), pct(p), pct(c)) } -/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request so that -/// `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable. +/// The fields of the engine's one structured line per request (`engine.log`), keyed by the id the API gave the request +/// so that `leleka logs --request ID` joins it with the API's record. Pure, so its content and size are testable. pub fn request_line_fields<'a>(r: &RequestLine<'a>) -> Vec> { use leleka_obs::V; let fresh = r.input_tokens.saturating_sub(r.reused_tokens); diff --git a/crates/leleka-memory/src/telemetry/render.rs b/crates/leleka-memory/src/telemetry/render.rs index 828aa84a..68963a6a 100644 --- a/crates/leleka-memory/src/telemetry/render.rs +++ b/crates/leleka-memory/src/telemetry/render.rs @@ -3,82 +3,114 @@ #[allow(unused_imports)] use super::*; -pub(super) fn render(state: &State, measured: &Measured) -> String { +fn ram_of(measured: &Measured) -> Option { let mib = |bytes: Option| bytes.map_or(0, |b| b >> 20); - let ram = measured.meminfo.mem_total.map(|total| Ram { + measured.meminfo.mem_total.map(|total| Ram { total_mib: total >> 20, available_mib: mib(measured.meminfo.mem_available), process_rss_mib: mib(measured.status.vm_rss), process_pinned_mib: mib(measured.status.vm_pin), swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20, - }); - let live_rate = match (state.phase, state.first_token) { + }) +} + +/// The decode rate of the request in flight, once it has produced more than a token over more than 50 ms. +fn live_rate_of(state: &State, measured: &Measured) -> Option { + match (state.phase, state.first_token) { (Phase::Decode, Some(first)) if state.produced_now > 1 => { let secs = measured.at.saturating_duration_since(first).as_secs_f64(); (secs > 0.05).then(|| round1(state.produced_now as f64 / secs)) } _ => None, - }; + } +} + +fn live_request_of(state: &State, measured: &Measured) -> Option { + state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { + prompt_tokens: state.prompt_now, + generated_tokens: state.produced_now, + elapsed_s: (measured.at.saturating_duration_since(started).as_secs_f64() * 10.0).round() / 10.0, + }) +} + +fn rates_of(state: &State, live_rate: Option) -> Rates { + Rates { + prefill_tok_s_last: state.last_prefill_tok_s.map(round1), + prefill_tok_s_avg: state.prefill_ema.map(round1), + prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms), + decode_tok_s_last: state.last_decode_tok_s.map(round1), + decode_tok_s_avg: state.decode_ema.map(round1), + decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms), + decode_tok_s_live: live_rate, + } +} + +fn cache_of(state: &State) -> Cache { + Cache { + requests: state.requests, + hit_requests: state.cache_hit_requests, + hit_ratio: ratio(state.cache_hit_requests, state.requests), + prompt_tokens: state.prompt_tokens, + reused_tokens: state.reused_tokens, + token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens), + last_prompt_tokens: state.last_prompt_tokens, + last_reused_tokens: state.last_reused_tokens, + } +} + +fn spec_of(state: &State) -> Spec { + Spec { + rounds: state.spec_rounds, + tokens: state.spec_tokens, + tokens_per_round: (state.spec_rounds > 0) + .then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), + } +} + +fn tier_of(state: &State) -> Option { + state.expert_tier.map(|counters| Tier { + counters, + vram_ratio: ratio(counters.vram_entries, counters.vram_entries + counters.pcie_entries + counters.cpu_entries), + }) +} + +fn cpu_of(measured: &Measured) -> Option { + measured.cpu.map(|(process, system)| Cpu { + cores: measured.cores, + process_busy_cores: round1(process), + system_busy_pct: round1(system), + }) +} + +fn context_of(state: &State) -> Context { + Context { + live_tokens: state.context_live, + max_tokens: state.context_max, + used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), + } +} + +fn nan_guard_of(state: &State) -> NanGuard { + NanGuard { healed_windows: state.nan_healed, unhealed_windows: state.nan_unhealed, last: state.nan_last.clone() } +} + +pub(super) fn render(state: &State, measured: &Measured) -> String { let document = Document { version: 1, ts_ms: measured.now_ms, uptime_s: measured.uptime_s, phase: state.phase, - request: state.started.filter(|_| state.phase != Phase::Idle).map(|started| LiveRequest { - prompt_tokens: state.prompt_now, - generated_tokens: state.produced_now, - elapsed_s: (measured.at.saturating_duration_since(started).as_secs_f64() * 10.0).round() / 10.0, - }), + request: live_request_of(state, measured), gpu: measured.gpu.clone(), - ram, - cpu: measured.cpu.map(|(process, system)| Cpu { - cores: measured.cores, - process_busy_cores: round1(process), - system_busy_pct: round1(system), - }), - throughput: Rates { - prefill_tok_s_last: state.last_prefill_tok_s.map(round1), - prefill_tok_s_avg: state.prefill_ema.map(round1), - prefill_tok_s_lifetime: lifetime_rate(state.prefill_tokens, state.prefill_ms), - decode_tok_s_last: state.last_decode_tok_s.map(round1), - decode_tok_s_avg: state.decode_ema.map(round1), - decode_tok_s_lifetime: lifetime_rate(state.decode_tokens, state.decode_ms), - decode_tok_s_live: live_rate, - }, - cache: Cache { - requests: state.requests, - hit_requests: state.cache_hit_requests, - hit_ratio: ratio(state.cache_hit_requests, state.requests), - prompt_tokens: state.prompt_tokens, - reused_tokens: state.reused_tokens, - token_hit_ratio: ratio(state.reused_tokens, state.prompt_tokens), - last_prompt_tokens: state.last_prompt_tokens, - last_reused_tokens: state.last_reused_tokens, - }, - context: Context { - live_tokens: state.context_live, - max_tokens: state.context_max, - used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), - }, - nan_guard: NanGuard { - healed_windows: state.nan_healed, - unhealed_windows: state.nan_unhealed, - last: state.nan_last.clone(), - }, - spec: Spec { - rounds: state.spec_rounds, - tokens: state.spec_tokens, - tokens_per_round: (state.spec_rounds > 0) - .then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), - }, - expert_tier: state.expert_tier.map(|counters| Tier { - counters, - vram_ratio: ratio( - counters.vram_entries, - counters.vram_entries + counters.pcie_entries + counters.cpu_entries, - ), - }), + ram: ram_of(measured), + cpu: cpu_of(measured), + throughput: rates_of(state, live_rate_of(state, measured)), + cache: cache_of(state), + context: context_of(state), + nan_guard: nan_guard_of(state), + spec: spec_of(state), + expert_tier: tier_of(state), last_request: state.last_request.clone(), settings: lock(&SETTINGS).clone(), }; @@ -106,7 +138,8 @@ impl Drop for Sampler { } } -/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU block. +/// Start the once-a-second sampler over the real `/proc`. `gpu_probe` reads the device (NVML); `None` reports no GPU +/// block. pub fn start(gpu_probe: Option, period: Duration) -> Sampler { start_with_clock(gpu_probe, period, SystemClock) } diff --git a/crates/leleka-memory/src/winproc.rs b/crates/leleka-memory/src/winproc.rs index 3c4de477..c43e93c5 100644 --- a/crates/leleka-memory/src/winproc.rs +++ b/crates/leleka-memory/src/winproc.rs @@ -42,7 +42,11 @@ pub fn meminfo_text(m: &SystemMemory) -> String { m.total_commit.saturating_sub(m.avail_commit).saturating_sub(m.total_phys.saturating_sub(m.avail_phys)); let swap_free = swap_total.saturating_sub(swap_used); format!( - "MemTotal: {} kB\nMemFree: {} kB\nMemAvailable: {} kB\nSwapTotal: {} kB\nSwapFree: {} kB\n", + "MemTotal: {} kB\n\ + MemFree: {} kB\n\ + MemAvailable: {} kB\n\ + SwapTotal: {} kB\n\ + SwapFree: {} kB\n", kb(m.total_phys), kb(m.avail_phys), kb(m.avail_phys), @@ -67,10 +71,15 @@ pub fn status_text(p: &ProcessMemory) -> String { /// `/proc/self/limits`: Windows has no `RLIMIT_MEMLOCK`; `VirtualLock` is bounded by the working-set quota and reports /// its own failure, so the limit is reported unlimited (the lock plan then attempts and the attempt decides). pub fn limits_text() -> String { - "Limit Soft Limit Hard Limit Units\nMax locked memory unlimited unlimited bytes\n".to_owned() + concat!( + "Limit Soft Limit Hard Limit Units\n", + "Max locked memory unlimited unlimited bytes\n" + ) + .to_owned() } -/// `/proc/self/stat` with only the fields the CPU telemetry reads: `utime` and `stime` (fields 14 and 15) in 10 ms ticks. +/// `/proc/self/stat` with only the fields the CPU telemetry reads: `utime` and `stime` (fields 14 and 15) in 10 ms +/// ticks. pub fn self_stat_text(user_ticks: u64, kernel_ticks: u64) -> String { format!("1 (leleka) R 0 0 0 0 0 0 0 0 0 0 {user_ticks} {kernel_ticks} 0 0 20 0 1 0 0\n") } @@ -99,8 +108,9 @@ pub fn read(path: &str) -> Option { } } -/// Trim this process's working set (Windows only; `false` elsewhere or on failure). Windows counts the mapped pages a process still has in its -/// working set as in use, so a file-mapped expert bank that was touched looks like pressure to the governor although the OS could reclaim it. +/// Trim this process's working set (Windows only; `false` elsewhere or on failure). Windows counts the mapped pages a +/// process still has in its working set as in use, so a file-mapped expert bank that was touched looks like pressure to +/// the governor although the OS could reclaim it. pub fn trim_working_set() -> bool { #[cfg(windows)] { @@ -168,8 +178,8 @@ mod win32 { }) } - /// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its working set to the - /// standby list: they stay cached, count as available again and come back with a soft fault. + /// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its + /// working set to the standby list: they stay cached, count as available again and come back with a soft fault. pub fn trim_working_set() -> bool { // SAFETY: the pseudo handle of the current process is always valid. unsafe { EmptyWorkingSet(GetCurrentProcess()) != 0 } diff --git a/crates/obs/src/impl_level.rs b/crates/obs/src/impl_level.rs index ab3a962f..1cd54693 100644 --- a/crates/obs/src/impl_level.rs +++ b/crates/obs/src/impl_level.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Level, impl From_for_V, impl From_for_V, impl From_for_V, impl From_for_V, impl From_for_V .... +//! Moved out of the parent module by STRA-338: impl Level, impl From_for_V, impl From_for_V, impl From_for_V, impl +//! From_for_V, impl From_for_V .... #[allow(unused_imports)] use super::*; @@ -83,8 +84,9 @@ impl Settings { } else { get("LELEKA_LOG_LEVEL").and_then(|v| Level::parse(&v)).unwrap_or(Level::Info) }; - // `leleka run` sets LELEKA_LOG_FORMAT=json for its children. A process started by hand keeps the plain lines the lab - // scripts parse (legacy) when its standard error is a file, and writes key=value text on a terminal. + // `leleka run` sets LELEKA_LOG_FORMAT=json for its children. A process started by hand keeps the plain + // lines the lab scripts parse (legacy) when its standard error is a file, and writes key=value text on a + // terminal. let (format, legacy) = match get("LELEKA_LOG_FORMAT").as_deref().map(str::trim) { Some("json") => (Format::Json, false), Some("text") => (Format::Text, false), @@ -130,27 +132,7 @@ pub(super) fn render_fields(settings: &Settings, fields: &[Field<'_>]) -> Vec<(S for (key, value) in fields { let key = clean_key(key); match *value { - V::Str(text) => { - let limit = if key == "msg" { MAX_MSG } else { MAX_VALUE }; - match classify_key(&key) { - KeyClass::Secret => out.push((key, Rendered::Str(redact::MARK.to_owned()))), - KeyClass::Text => { - if settings.debug { - out.push((format!("{key}_len"), Rendered::Raw(text.len().to_string()))); - } - out.push((key, Rendered::Str(redact::MARK.to_owned()))); - } - KeyClass::Plain => { - let scrubbed = redact::scrub(text); - let clipped = redact::clip(&scrubbed, limit); - let mut shown = clipped.to_owned(); - if clipped.len() < scrubbed.len() { - shown.push('~'); - } - out.push((key, Rendered::Str(shown))); - } - } - } + V::Str(text) => render_str(settings, key, text, &mut out), V::Int(n) => out.push((key, Rendered::Raw(n.to_string()))), V::UInt(n) => out.push((key, Rendered::Raw(n.to_string()))), V::Float(f) if f.is_finite() => out.push((key, Rendered::Raw(format!("{f}")))), @@ -161,6 +143,29 @@ pub(super) fn render_fields(settings: &Settings, fields: &[Field<'_>]) -> Vec<(S out } +/// A string field: redacted by its key class, else scrubbed and capped (a `~` marks the cut). +fn render_str(settings: &Settings, key: String, text: &str, out: &mut Vec<(String, Rendered)>) { + match classify_key(&key) { + KeyClass::Secret => out.push((key, Rendered::Str(redact::MARK.to_owned()))), + KeyClass::Text => { + if settings.debug { + out.push((format!("{key}_len"), Rendered::Raw(text.len().to_string()))); + } + out.push((key, Rendered::Str(redact::MARK.to_owned()))); + } + KeyClass::Plain => { + let limit = if key == "msg" { MAX_MSG } else { MAX_VALUE }; + let scrubbed = redact::scrub(text); + let clipped = redact::clip(&scrubbed, limit); + let mut shown = clipped.to_owned(); + if clipped.len() < scrubbed.len() { + shown.push('~'); + } + out.push((key, Rendered::Str(shown))); + } + } +} + /// The line for one event (no trailing newline). Pure: the clock and the settings are arguments. pub fn format_line( settings: &Settings, @@ -183,24 +188,28 @@ pub fn format_line( Format::Json => json_line(ts_ms, level, &comp, &ev, &rendered), Format::Text => text_line(ts_ms, level, &comp, &ev, &rendered), }; - if line.len() <= MAX_LINE || rendered.is_empty() { + if line.len() <= MAX_LINE || rendered.is_empty() || !shrink(&mut rendered, &mut truncated) { return line; } - // Too long: drop fields from the end, behind a `trunc` marker that stays last. - if truncated { - if rendered.len() < 2 { - return line; - } - let index = rendered.len() - 2; - rendered.remove(index); - } else { - truncated = true; - rendered.pop(); - rendered.push(("trunc".to_owned(), Rendered::Raw("true".to_owned()))); - } } } +/// Too long: drop fields from the end, behind a `trunc` marker that stays last. False when nothing more can go. +fn shrink(rendered: &mut Vec<(String, Rendered)>, truncated: &mut bool) -> bool { + if *truncated { + if rendered.len() < 2 { + return false; + } + let index = rendered.len() - 2; + rendered.remove(index); + } else { + *truncated = true; + rendered.pop(); + rendered.push(("trunc".to_owned(), Rendered::Raw("true".to_owned()))); + } + true +} + pub(super) fn clean_key_dash(text: &str) -> String { text.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' }).collect() } diff --git a/crates/obs/src/lib.rs b/crates/obs/src/lib.rs index b80ce86c..3698962a 100644 --- a/crates/obs/src/lib.rs +++ b/crates/obs/src/lib.rs @@ -63,8 +63,8 @@ pub struct Settings { pub format: Format, /// `LELEKA_LOG_DEBUG`: debug level on, and the *length* of redacted text values is logged. pub debug: bool, - /// `LELEKA_LOG_LEGACY=1`: the lab's unstructured lines exactly as before (no JSON, no sampling) for the scripts that - /// parse them; the secret scrub still applies. + /// `LELEKA_LOG_LEGACY=1`: the lab's unstructured lines exactly as before (no JSON, no sampling) for the scripts + /// that parse them; the secret scrub still applies. pub legacy: bool, } @@ -83,7 +83,8 @@ pub struct FileSink { file: Mutex>, } -/// `warn!`-style free text through the legacy path, keyed by the call site: `obs_msg!(Level::Info, "api", "fmt {}", x)`. +/// `warn!`-style free text through the legacy path, keyed by the call site: `obs_msg!(Level::Info, "api", "fmt {}", +/// x)`. #[macro_export] macro_rules! obs_msg { ($level:expr, $comp:expr, $($arg:tt)*) => {{ diff --git a/crates/obs/src/rate.rs b/crates/obs/src/rate.rs index e7c21143..df250063 100644 --- a/crates/obs/src/rate.rs +++ b/crates/obs/src/rate.rs @@ -1,8 +1,8 @@ //! Per-event token buckets: a burst is logged, a flood is sampled, and the line after a gap says how many were dropped. //! -//! The root disk of the 5090 server stalls under sustained small writes, so a loop that fails every few milliseconds must -//! cost a bounded number of bytes per hour, not per second. The limiter keeps one bucket per key (an event name or a call -//! site), at most [`MAX_KEYS`] of them; a key beyond that shares one overflow bucket. +//! The root disk of the 5090 server stalls under sustained small writes, so a loop that fails every few milliseconds +//! must cost a bounded number of bytes per hour, not per second. The limiter keeps one bucket per key (an event name +//! or a call site), at most [`MAX_KEYS`] of them; a key beyond that shares one overflow bucket. use std::collections::HashMap; use std::sync::Mutex; diff --git a/crates/obs/src/redact.rs b/crates/obs/src/redact.rs index aa5c0775..a87fb127 100644 --- a/crates/obs/src/redact.rs +++ b/crates/obs/src/redact.rs @@ -120,60 +120,54 @@ const TOKEN_PREFIXES: &[(&str, usize)] = &[ ("eyJ", 20), ]; +/// Names that mark `name=value` / `name":"value` text as a credential; the value runs to the next separator. +const NAMES: &[&str] = + &["token", "secret", "password", "passwd", "api_key", "apikey", "api-key", "access_key", "authorization", "key"]; + +/// Bytes after a credential name that open its value: `=`, `":"` or `": "` (JSON); 0 when none does. +fn separator_len(rest: &[u8]) -> usize { + if rest.starts_with(b"=") { + 1 + } else if rest.starts_with(b"\":\"") { + 3 + } else if rest.starts_with(b"\": \"") { + 4 + } else { + 0 + } +} + +/// Where the value of a credential-looking `name=` starting at `i` begins, if one does. +fn named_value_start(lower: &str, bytes: &[u8], i: usize) -> Option { + if i != 0 && word_char(bytes[i - 1]) { + return None; + } + NAMES.iter().find_map(|name| { + let after = i + name.len(); + let skip = if lower[i..].starts_with(name) { separator_len(&bytes[after..]) } else { 0 }; + (skip > 0).then_some(after + skip) + }) +} + +/// Where the value that starts at `start` ends: the next separator, or the end of the text. +fn named_value_end(bytes: &[u8], start: usize) -> usize { + bytes[start..] + .iter() + .position(|&b| matches!(b, b'&' | b' ' | b'"' | b'\'' | b',' | b';' | b'\n' | b'\r' | b'}' | b')')) + .map_or(bytes.len(), |n| start + n) +} + fn scrub_named_values(text: &str, out: &mut String) -> bool { - // `name=value` / `name":"value` for credential-looking names; the value runs to the next separator. - const NAMES: &[&str] = &[ - "token", - "secret", - "password", - "passwd", - "api_key", - "apikey", - "api-key", - "access_key", - "authorization", - "key", - ]; let lower = text.to_ascii_lowercase(); let bytes = text.as_bytes(); - let mut changed = false; - let mut i = 0; - let mut last = 0; + let (mut changed, mut i, mut last) = (false, 0, 0); while i < bytes.len() { - let mut matched = None; - if i == 0 || !word_char(bytes[i - 1]) { - for name in NAMES { - if lower[i..].starts_with(name) { - let after = i + name.len(); - let rest = &bytes[after..]; - // =, :, "=" or "\":\"" (JSON) after the name - let skip = if rest.starts_with(b"=") { - 1 - } else if rest.starts_with(b"\":\"") { - 3 - } else if rest.starts_with(b"\": \"") { - 4 - } else { - 0 - }; - if skip > 0 { - matched = Some(after + skip); - break; - } - } - } - } - if let Some(value_start) = matched { - let value_end = bytes[value_start..] - .iter() - .position(|&b| matches!(b, b'&' | b' ' | b'"' | b'\'' | b',' | b';' | b'\n' | b'\r' | b'}' | b')')) - .map_or(bytes.len(), |n| value_start + n); + if let Some(value_start) = named_value_start(&lower, bytes, i) { + let value_end = named_value_end(bytes, value_start); if value_end > value_start { out.push_str(&text[last..value_start]); out.push_str(MARK); - last = value_end; - i = value_end; - changed = true; + (last, i, changed) = (value_end, value_end, true); continue; } } @@ -183,42 +177,72 @@ fn scrub_named_values(text: &str, out: &mut String) -> bool { changed } +/// Copies a text while swapping spans for the marker; hands the original back when no span was cut. +struct Cutter<'a> { + text: &'a str, + out: String, + last: usize, + changed: bool, +} + +impl<'a> Cutter<'a> { + fn new(text: &'a str) -> Self { + Self { text, out: String::new(), last: 0, changed: false } + } + + /// Keep the text up to `start`, then `sep` and the marker; resume at `end`. + fn cut(&mut self, start: usize, sep: &str, end: usize) { + self.out.push_str(&self.text[self.last..start]); + self.out.push_str(sep); + self.out.push_str(MARK); + self.last = end; + self.changed = true; + } + + fn finish(mut self) -> Cow<'a, str> { + if !self.changed { + return Cow::Borrowed(self.text); + } + self.out.push_str(&self.text[self.last..]); + Cow::Owned(self.out) + } +} + +/// `Bearer ` at `i`: (where the token starts, "", where it ends). +fn bearer_hit(text: &str, lower: &str, i: usize) -> Option<(usize, &'static str, usize)> { + if !lower[i..].starts_with("bearer ") || (i != 0 && word_char(text.as_bytes()[i - 1])) { + return None; + } + let start = i + 7; + let stops = |&b: &u8| matches!(b, b' ' | b'"' | b'\'' | b',' | b';' | b'\n' | b'\r'); + let end = text.as_bytes()[start..].iter().position(stops).map_or(text.len(), |n| start + n); + Some((start, "", end)) +} + +/// `Authorization: ` at `i`: (where the value starts, " ", end of the line). +fn header_hit(text: &str, lower: &str, i: usize) -> Option<(usize, &'static str, usize)> { + if !lower[i..].starts_with("authorization:") { + return None; + } + let start = i + "authorization:".len(); + let end = text[start..].find(['\n', '\r']).map_or(text.len(), |n| start + n); + Some((start, " ", end)) +} + fn scrub_authorization(text: &str) -> Cow<'_, str> { let lower = text.to_ascii_lowercase(); - let mut out = String::new(); - let mut last = 0; + let mut cutter = Cutter::new(text); let mut i = 0; - let mut changed = false; while i < text.len() { - if lower[i..].starts_with("bearer ") && (i == 0 || !word_char(text.as_bytes()[i - 1])) { - let start = i + 7; - let end = text.as_bytes()[start..] - .iter() - .position(|&b| matches!(b, b' ' | b'"' | b'\'' | b',' | b';' | b'\n' | b'\r')) - .map_or(text.len(), |n| start + n); - out.push_str(&text[last..start]); - out.push_str(MARK); - last = end; - i = end; - changed = true; - } else if lower[i..].starts_with("authorization:") { - let start = i + "authorization:".len(); - let end = text[start..].find(['\n', '\r']).map_or(text.len(), |n| start + n); - out.push_str(&text[last..start]); - out.push(' '); - out.push_str(MARK); - last = end; - i = end; - changed = true; - } else { - i += text[i..].chars().next().map_or(1, char::len_utf8); - } + i = match bearer_hit(text, &lower, i).or_else(|| header_hit(text, &lower, i)) { + Some((start, sep, end)) => { + cutter.cut(start, sep, end); + end + } + None => i + text[i..].chars().next().map_or(1, char::len_utf8), + }; } - if !changed { - return Cow::Borrowed(text); - } - out.push_str(&text[last..]); - Cow::Owned(out) + cutter.finish() } fn scrub_url_credentials(text: &str) -> Cow<'_, str> { @@ -247,55 +271,52 @@ fn scrub_url_credentials(text: &str) -> Cow<'_, str> { Cow::Owned(out) } +/// End of the alphanumeric run that starts at `start`. +fn alnum_end(bytes: &[u8], start: usize) -> usize { + bytes[start..].iter().position(|&b| !word_char(b)).map_or(bytes.len(), |n| start + n) +} + +/// End of the run at `from` once `_` and `-` count too (for the prefix rules only). +fn prefix_run_end(bytes: &[u8], from: usize) -> usize { + let part = |&b: &u8| word_char(b) || b == b'_' || b == b'-'; + bytes[from..].iter().position(|b| !part(b)).map_or(bytes.len(), |n| from + n) +} + +/// A long run that starts with a known credential prefix and does not continue a longer word. +fn token_by_prefix(long_run: &str, starts_word: bool) -> bool { + let known = |(prefix, min): &(&str, usize)| long_run.starts_with(prefix) && long_run.len() >= prefix.len() + min; + starts_word && TOKEN_PREFIXES.iter().any(known) +} + +/// A long mixed letters-and-digits run that is not the shape of a 40 or 64 digit hex digest. +fn random_run(alnum: &str) -> bool { + let digest_shape = is_hex(alnum) && matches!(alnum.len(), 40 | 64); + alnum.len() >= 32 + && !digest_shape + && alnum.bytes().any(|b| b.is_ascii_digit()) + && alnum.bytes().any(|b| b.is_ascii_alphabetic()) +} + fn scrub_runs(text: &str) -> Cow<'_, str> { let bytes = text.as_bytes(); - let mut out = String::new(); - let mut last = 0; + let mut cutter = Cutter::new(text); let mut i = 0; - let mut changed = false; while i < bytes.len() { if !word_char(bytes[i]) { i += 1; continue; } let start = i; - while i < bytes.len() && (word_char(bytes[i])) { - i += 1; - } - // extend over `_` and `-` for the prefix rules only - let mut end = i; - while end < bytes.len() && (word_char(bytes[end]) || bytes[end] == b'_' || bytes[end] == b'-') { - end += 1; - } - let long_run = &text[start..end]; - let alnum = &text[start..i]; - let token_by_prefix = TOKEN_PREFIXES - .iter() - .any(|(prefix, min)| long_run.starts_with(prefix) && long_run.len() >= prefix.len() + min) - && (start == 0 || !word_char(bytes[start - 1])); - let digest_shape = is_hex(alnum) && matches!(alnum.len(), 40 | 64); - let random_run = alnum.len() >= 32 - && !digest_shape - && alnum.bytes().any(|b| b.is_ascii_digit()) - && alnum.bytes().any(|b| b.is_ascii_alphabetic()); - if token_by_prefix { - out.push_str(&text[last..start]); - out.push_str(MARK); - last = end; + i = alnum_end(bytes, start); + let end = prefix_run_end(bytes, i); + if token_by_prefix(&text[start..end], start == 0 || !word_char(bytes[start - 1])) { + cutter.cut(start, "", end); i = end; - changed = true; - } else if random_run { - out.push_str(&text[last..start]); - out.push_str(MARK); - last = i; - changed = true; + } else if random_run(&text[start..i]) { + cutter.cut(start, "", i); } } - if !changed { - return Cow::Borrowed(text); - } - out.push_str(&text[last..]); - Cow::Owned(out) + cutter.finish() } /// The value-based net applied to every string a log line carries. diff --git a/crates/obs/src/time.rs b/crates/obs/src/time.rs index e5d8d3e6..cec871f6 100644 --- a/crates/obs/src/time.rs +++ b/crates/obs/src/time.rs @@ -40,28 +40,48 @@ pub fn format_utc_ms(ms: u64) -> String { format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, ms % 1000) } +/// The `-`, `T` and `:` of `2026-11-02T10:11:12` sit where they should. +fn has_separators(b: &[u8]) -> bool { + [(4, b'-'), (7, b'-'), (10, b'T'), (13, b':'), (16, b':')].iter().all(|&(at, c)| b[at] == c) +} + +/// Month, day, hour, minute and second are in their calendar ranges (a leap second is accepted). +fn in_calendar_range(mo: u64, d: u64, h: u64, mi: u64, s: u64) -> bool { + (1..=12).contains(&mo) && (1..=31).contains(&d) && h <= 23 && mi <= 59 && s <= 60 +} + +/// The milliseconds of an optional `.fff` fraction, and the text that follows it. +fn fraction_ms(rest: &str) -> Option<(u64, &str)> { + let Some(fraction) = rest.strip_prefix('.') else { + return Some((0, rest)); + }; + let digits: String = fraction.chars().take_while(char::is_ascii_digit).take(3).collect(); + if digits.is_empty() { + return None; + } + let ms = digits.parse::().ok()? * 10u64.pow(3 - digits.len() as u32); + Some((ms, fraction.trim_start_matches(|c: char| c.is_ascii_digit()))) +} + +/// The numbers of `YYYY-MM-DDThh:mm:ss`: ([year, month, day], [hour, minute, second]). +fn date_time_fields(text: &str) -> Option<([u64; 3], [u64; 3])> { + let num = |from: usize, to: usize| -> Option { text.get(from..to)?.parse::().ok() }; + let date = [num(0, 4)?, num(5, 7)?, num(8, 10)?]; + let time = [num(11, 13)?, num(14, 16)?, num(17, 19)?]; + Some((date, time)) +} + /// The inverse of [`format_utc_ms`]; also accepts the form without milliseconds (`...:12Z`). pub fn parse_utc_ms(text: &str) -> Option { let b = text.as_bytes(); - if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' { + if b.len() < 20 || !has_separators(b) { return None; } - let num = |from: usize, to: usize| -> Option { text.get(from..to)?.parse::().ok() }; - let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); - let (h, mi, s) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); - if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || s > 60 { + let ([y, mo, d], [h, mi, s]) = date_time_fields(text)?; + if !in_calendar_range(mo, d, h, mi, s) { return None; } - let mut ms = 0; - let mut rest = &text[19..]; - if let Some(fraction) = rest.strip_prefix('.') { - let digits: String = fraction.chars().take_while(char::is_ascii_digit).take(3).collect(); - if digits.is_empty() { - return None; - } - ms = digits.parse::().ok()? * 10u64.pow(3 - digits.len() as u32); - rest = fraction.trim_start_matches(|c: char| c.is_ascii_digit()); - } + let (ms, rest) = fraction_ms(&text[19..])?; if rest != "Z" { return None; } diff --git a/crates/obs/src/write_stderr_fn.rs b/crates/obs/src/write_stderr_fn.rs index 9a7423c6..2d23867d 100644 --- a/crates/obs/src/write_stderr_fn.rs +++ b/crates/obs/src/write_stderr_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn write_stderr, impl FileSink, fn request_sink, fn emit, fn emit_keyed, fn emit_always .... +//! Moved out of the parent module by STRA-338: fn write_stderr, impl FileSink, fn request_sink, fn emit, fn emit_keyed, +//! fn emit_always .... #[allow(unused_imports)] use super::*; diff --git a/limits-baseline.json b/limits-baseline.json index 0987e7b0..f6dee780 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -13,11 +13,6 @@ "complexity": 2, "fn_lines": 3 }, - "leleka-context": { - "fn_lines": 6, - "complexity": 6, - "width": 9 - }, "leleka-cpu-kernels": { "fn_lines": 1 }, @@ -45,12 +40,8 @@ "nesting": 7 }, "leleka-engine-core": { - "fn_lines": 44, - "complexity": 38, - "width": 56 - }, - "leleka-engine-fake": { - "width": 1 + "fn_lines": 11, + "complexity": 8 }, "leleka-engine-qwen35-cuda": { "fn_lines": 625, @@ -128,12 +119,6 @@ "fn_lines": 2, "complexity": 2 }, - "leleka-memory": { - "fn_lines": 24, - "width": 97, - "complexity": 11, - "nesting": 1 - }, "leleka-model-format": { "fn_lines": 69, "complexity": 63, @@ -159,12 +144,6 @@ "complexity": 1, "width": 2 }, - "leleka-obs": { - "fn_lines": 5, - "complexity": 4, - "width": 7, - "nesting": 1 - }, "leleka-offline-tools": { "fn_lines": 8, "complexity": 5, @@ -230,8 +209,7 @@ }, "leleka-context": { "fn_lines": 5, - "complexity": 1, - "width": 2 + "complexity": 1 }, "leleka-cpu-kernels": { "fn_lines": 8, @@ -261,7 +239,7 @@ }, "leleka-engine-core": { "fn_lines": 11, - "width": 15, + "width": 2, "complexity": 3, "nesting": 1 }, @@ -323,7 +301,7 @@ "fn_lines": 5, "complexity": 1, "nesting": 1, - "width": 21 + "width": 13 }, "leleka-model-format": { "fn_lines": 71,