From 05c612afce37a5002da7d6438bb9416cadbacb7a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 20 Oct 2026 03:09:35 -0500 Subject: [PATCH 1/2] Measure engine KV against physical token capacity --- .../src/cognition/serving_plan/footprint.rs | 4 +- .../src/inference/engine_residency.rs | 4 +- .../src/inference/lane_footprint.rs | 65 ++-- .../src/inference/weight_residency.rs | 41 ++- .../src/modules/serving_daemon.rs | 283 +----------------- .../src/modules/serving_daemon/footprint.rs | 272 +++++++++++++++++ core/source-hygiene/src/file_size.rs | 2 +- core/vendor/LLAMA_CPP_PIN | 2 +- core/vendor/llama.cpp | 2 +- 9 files changed, 355 insertions(+), 320 deletions(-) create mode 100644 core/continuum-core/src/modules/serving_daemon/footprint.rs diff --git a/core/continuum-core/src/cognition/serving_plan/footprint.rs b/core/continuum-core/src/cognition/serving_plan/footprint.rs index 56f4839f3d..c593e82420 100644 --- a/core/continuum-core/src/cognition/serving_plan/footprint.rs +++ b/core/continuum-core/src/cognition/serving_plan/footprint.rs @@ -284,7 +284,7 @@ mod tests { for _ in 0..4 { let per_token = crate::inference::lane_footprint::per_token_from(anon, lanes, window, fp.base_compute_buffer_per_lane(), 0) .expect("test: a reading"); - let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: per_token, lanes, window, anon_bytes: anon, last_ms: 0 }; + let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: per_token, lanes, window, allocated_tokens: None, anon_bytes: anon, last_ms: 0 }; fp.fixed_per_lane_bytes = fixed_per_lane_from(header_rate, &record); seen.push(fp.fixed_per_lane_bytes); } @@ -310,7 +310,7 @@ mod tests { // sample of 55,925 at 67,340) yields ≈1.56 GB of fixed residency per lane, and // across budgets the plan with it fits no more lanes than the header-only plan // and no fewer than the raised-rate plan — strictly between them somewhere. - let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: 55_925, lanes: 1, window: 67_340, anon_bytes: 0, last_ms: 0 }; + let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: 55_925, lanes: 1, window: 67_340, allocated_tokens: None, anon_bytes: 0, last_ms: 0 }; let fixed = fixed_per_lane_from(32_768, &record); assert!((1_500_000_000..1_620_000_000).contains(&fixed), "{fixed} B per lane"); assert_eq!(fixed_per_lane_from(65_536, &record), 0, "a sample under the rate carries nothing"); diff --git a/core/continuum-core/src/inference/engine_residency.rs b/core/continuum-core/src/inference/engine_residency.rs index 78350b00d7..4884144336 100644 --- a/core/continuum-core/src/inference/engine_residency.rs +++ b/core/continuum-core/src/inference/engine_residency.rs @@ -547,7 +547,7 @@ mod tests { fn a_release_retires_only_the_footprint_sampled_during_the_work() { use super::super::lane_footprint::{retire_sampled_since, MeasuredCost}; let bound_at = 1_000; - let reading = |last_ms| MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, anon_bytes: 20 << 30, last_ms }; + let reading = |last_ms| MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, allocated_tokens: None, anon_bytes: 20 << 30, last_ms }; let mut costs = std::collections::BTreeMap::new(); costs.insert("during".to_string(), reading(bound_at + 60_000)); costs.insert("before".to_string(), reading(bound_at - 1)); @@ -571,7 +571,7 @@ mod tests { #[test] fn a_sample_that_straddles_a_residency_change_is_never_published() { use super::super::lane_footprint::{begin_sample, publish_sample, MeasuredCost}; - let reading = MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, anon_bytes: 20 << 30, last_ms: 5 }; + let reading = MeasuredCost { per_token_bytes: 36_000, lanes: 1, window: 32_768, allocated_tokens: None, anon_bytes: 20 << 30, last_ms: 5 }; let dir = tempfile::tempdir().expect("tempdir"); let path = store_path(dir.path()); let w = work(10, 25281, 1_000, 58058); diff --git a/core/continuum-core/src/inference/lane_footprint.rs b/core/continuum-core/src/inference/lane_footprint.rs index 1e385821ac..46db98644f 100644 --- a/core/continuum-core/src/inference/lane_footprint.rs +++ b/core/continuum-core/src/inference/lane_footprint.rs @@ -44,6 +44,9 @@ pub struct MeasuredCost { pub per_token_bytes: u64, pub lanes: u32, pub window: u32, + /// Physical token capacity. Absent only in records written by older cores. + #[serde(default)] + pub allocated_tokens: Option, pub anon_bytes: u64, pub last_ms: u64, } @@ -83,20 +86,19 @@ pub fn window_measurable(window: u32) -> bool { window >= MEASURABLE_WINDOW_MIN } -pub fn per_token_from( - anon_bytes: u64, - lanes: u32, - window: u32, - compute_floor_per_lane: u64, - host_cache_bytes: u64, -) -> Option { - if lanes == 0 || window == 0 { +pub fn per_token_from(anon_bytes: u64, lanes: u32, window: u32, compute_floor_per_lane: u64, host_cache_bytes: u64) -> Option { + per_token_for_allocation(anon_bytes, lanes, u64::from(lanes) * u64::from(window), compute_floor_per_lane, host_cache_bytes) +} + +/// Attribute bytes to physical token storage, independently of sequence limits. +fn per_token_for_allocation(anon_bytes: u64, lanes: u32, allocated_tokens: u64, compute_floor_per_lane: u64, host_cache_bytes: u64) -> Option { + if lanes == 0 || allocated_tokens == 0 { return None; } let beyond_cache = anon_bytes.checked_sub(host_cache_bytes)?; - let per_lane = beyond_cache / lanes as u64; - let beyond_floor = per_lane.checked_sub(compute_floor_per_lane)?; - let per_token = beyond_floor / window as u64; + let floors = compute_floor_per_lane.checked_mul(u64::from(lanes))?; + let beyond_floor = beyond_cache.checked_sub(floors)?; + let per_token = beyond_floor / allocated_tokens; (per_token > 0).then_some(per_token) } @@ -182,14 +184,21 @@ pub fn observe( model: &str, lanes: u32, window: u32, + allocated_tokens: u64, anon_bytes: u64, compute_floor_per_lane: u64, host_cache_bytes: u64, ) -> Result, ResidencyChanged> { // A pre-1970 clock reads 0 here: every record is stale, so the estimate rules. let now = EpochMs::now().millis(); - let sample = per_token_from(anon_bytes, lanes, window, compute_floor_per_lane, host_cache_bytes) - .map(|per_token| MeasuredCost { per_token_bytes: per_token, lanes, window, anon_bytes, last_ms: now }); + let sample = per_token_for_allocation(anon_bytes, lanes, allocated_tokens, compute_floor_per_lane, host_cache_bytes).map(|per_token| MeasuredCost { + per_token_bytes: per_token, + lanes, + window, + allocated_tokens: Some(allocated_tokens), + anon_bytes, + last_ms: now, + }); use std::sync::atomic::Ordering; let mut costs = COSTS.lock(); let moved = publish_sample(&mut costs, RESIDENCY_EPOCH.load(Ordering::SeqCst), token, model, sample.as_ref())?; @@ -263,7 +272,6 @@ pub fn measured_record(model: &str) -> Option { COSTS.lock().get(model).filter(|c| c.fresh_at(now)).cloned() } - /// The ANONYMOUS memory a process holds — dirty + compressed/swapped, mapped files /// excluded. On macOS `proc_pid_rusage` (libproc, no entitlement for our own user's /// processes); on Linux `/proc//status` `RssAnon + VmSwap`. `None` = could not @@ -444,12 +452,7 @@ fn parse_procargs2(buf: &[u8]) -> Option> { #[cfg(target_os = "linux")] fn process_args(pid: u32) -> Option> { let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?; - Some( - raw.split(|b| *b == 0) - .filter(|a| !a.is_empty()) - .map(|a| String::from_utf8_lossy(a).into_owned()) - .collect(), - ) + Some(raw.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).into_owned()).collect()) } #[cfg(not(any(target_os = "macos", target_os = "linux")))] @@ -536,7 +539,14 @@ mod tests { let model = "trapped-fixture"; COSTS.lock().insert( model.to_string(), - MeasuredCost { per_token_bytes: per_token, lanes: 1, window: 2_048, anon_bytes: 500_000_000, last_ms: EpochMs::now().millis() }, + MeasuredCost { + per_token_bytes: per_token, + lanes: 1, + window: 2_048, + allocated_tokens: None, + anon_bytes: 500_000_000, + last_ms: EpochMs::now().millis(), + }, ); assert!(measured_record(model).is_some(), "the trap record rules before retirement"); assert!(retire(model), "a record was there to retire"); @@ -561,6 +571,12 @@ mod tests { assert_eq!(per_token_from(gb, 0, 51_712, 0, 0), None); assert_eq!(per_token_from(gb, 2, 0, 0, 0), None); assert_eq!(per_token_from(gb, 2, 4096, gb, 0), None, "under the compute floors: nothing beyond them to attribute"); + // Unified and divided caches may have equal sequence limits but different + // physical capacities. Charge only the capacity in the engine's receipt. + assert_eq!(per_token_for_allocation(4096, 2, 2048, 0, 0), Some(2)); + assert_eq!(per_token_for_allocation(4096, 2, 4096, 0, 0), Some(1)); + assert_eq!(per_token_for_allocation(4096, 2, 0, 0, 0), None); + assert_eq!(per_token_for_allocation(u64::MAX, 2, 2048, u64::MAX, 0), None); } // what this catches (2026-09-19, the M5 starved to one lane while running two): the @@ -581,7 +597,7 @@ mod tests { assert!(beyond < inflated && beyond > 32_768, "{beyond}: less than the inflated read, still a real excess"); let mut costs = BTreeMap::new(); - let stale = MeasuredCost { per_token_bytes: 133_720, lanes, window, anon_bytes: anon, last_ms: 1 }; + let stale = MeasuredCost { per_token_bytes: 133_720, lanes, window, allocated_tokens: None, anon_bytes: anon, last_ms: 1 }; assert!(apply_sample(&mut costs, "m", Some(&stale)), "first record is a move"); assert!(apply_sample(&mut costs, "m", None), "an unattributable sample retires it — a save is due"); assert!(costs.get("m").is_none(), "nothing rules the plan from disk"); @@ -595,7 +611,10 @@ mod tests { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("lane-footprint.json"); let mut costs = BTreeMap::new(); - costs.insert("m".to_string(), MeasuredCost { per_token_bytes: 36_000, lanes: 8, window: 51_712, anon_bytes: 25_700_000_000, last_ms: 5 }); + costs.insert( + "m".to_string(), + MeasuredCost { per_token_bytes: 36_000, lanes: 8, window: 51_712, allocated_tokens: None, anon_bytes: 25_700_000_000, last_ms: 5 }, + ); save_to(&path, &costs); assert_eq!(load_from(&path), costs); std::fs::write(&path, b"{not json").expect("write"); diff --git a/core/continuum-core/src/inference/weight_residency.rs b/core/continuum-core/src/inference/weight_residency.rs index 81bbafcc26..67fece1af7 100644 --- a/core/continuum-core/src/inference/weight_residency.rs +++ b/core/continuum-core/src/inference/weight_residency.rs @@ -106,8 +106,9 @@ pub struct EngineContext { /// KV plus compute buffers on accelerators: everything the engine says it holds beyond weights. pub beyond_weights: u64, pub slots: u32, - /// Each slot's context. The lane passes `--parallel` explicitly, so the cache is never unified - /// and the engine holds `slots × n_ctx_per_slot` tokens. + /// Total physical token capacity; unified caches do not multiply this by slots. + pub allocated_tokens: u64, + /// Maximum context for one sequence, independently of total physical capacity. pub n_ctx_per_slot: u32, } @@ -148,13 +149,22 @@ impl EngineContext { pub fn from_props(props: &serde_json::Value) -> Option { let memory = EngineMemory::from_props(props)?; let (slots, n_ctx_per_slot) = slot_geometry(props)?; + let allocated_tokens = match props.get("context_geometry") { + Some(geometry) => { + let tokens = geometry.get("allocated_tokens")?.as_u64()?; + let capacity = geometry.get("sequence_capacity")?.as_u64()?; + let window = geometry.get("max_tokens_per_sequence")?.as_u64()?; + if tokens == 0 || capacity != u64::from(slots) || window != u64::from(n_ctx_per_slot) || window > tokens { + return None; + } + tokens + } + // Older managed engines used divided caches. Only absence permits their + // legacy geometry; a present malformed receipt must never take this path. + None => u64::from(slots) * u64::from(n_ctx_per_slot), + }; let context_bytes = memory.accelerator_context(); - (context_bytes > 0).then(|| Self { - context_bytes, - beyond_weights: memory.accelerator_beyond_weights(), - slots, - n_ctx_per_slot, - }) + (context_bytes > 0).then(|| Self { context_bytes, beyond_weights: memory.accelerator_beyond_weights(), slots, allocated_tokens, n_ctx_per_slot }) } } @@ -202,7 +212,22 @@ mod tests { let ctx = EngineContext::from_props(&with_slots).expect("reads"); assert_eq!((ctx.context_bytes, ctx.slots, ctx.n_ctx_per_slot), (117440512, 2, 2048)); assert_eq!(ctx.beyond_weights, 117440512 + 66594944); + assert_eq!(ctx.allocated_tokens, 4096); assert_eq!(EngineContextReading::of(&with_slots), EngineContextReading::Read(ctx)); + // A unified cache's per-sequence limit is not independent storage per slot. + let mut unified = with_slots.clone(); + unified["context_geometry"] = serde_json::json!({ + "allocated_tokens": 2048, "max_tokens_per_sequence": 2048, "sequence_capacity": 2 + }); + assert_eq!(EngineContext::from_props(&unified).expect("unified receipt").allocated_tokens, 2048); + for invalid in [ + serde_json::Value::Null, + serde_json::json!({"allocated_tokens": 0, "max_tokens_per_sequence": 2048, "sequence_capacity": 2}), + serde_json::json!({"allocated_tokens": 2048, "max_tokens_per_sequence": 2048, "sequence_capacity": 3}), + ] { + unified["context_geometry"] = invalid; + assert_eq!(EngineContextReading::of(&unified), EngineContextReading::Invalid); + } // present but unusable is no reading, never the legacy fallback (Codex on #4961) assert_eq!(EngineContextReading::of(&props), EngineContextReading::Invalid, "no slot geometry"); let mut zero_slots = with_slots.clone(); diff --git a/core/continuum-core/src/modules/serving_daemon.rs b/core/continuum-core/src/modules/serving_daemon.rs index 570d0ac1aa..8302de52f8 100644 --- a/core/continuum-core/src/modules/serving_daemon.rs +++ b/core/continuum-core/src/modules/serving_daemon.rs @@ -22,6 +22,7 @@ //! its `send` takes `&self`. cbar's pipeline-stage pattern in Rust dress. pub(crate) mod academy_batch; +mod footprint; use crate::time::EpochMs; use super::serving_consumer::{FootprintFn, ServingConsumer, SERVING_CONSUMER_ID}; @@ -2562,288 +2563,6 @@ impl ServingDaemonModule { ); } - async fn sample_lane_footprint(&self) { - // The board's credit first, every tick and unconditionally. The per-token reading - // below is taken once a minute and withheld while other work lives in the engine, - // but the engine's device holding is serving's own the whole time. A once-a-minute - // credit would read a freshly relaunched engine as nobody's for up to a minute, which - // is exactly when a relaunch is sized. `/props` is one local call per tick. - self.refresh_engine_device_credit().await; - let now = EpochMs::now().millis(); - if !crate::inference::lane_footprint::sample_due(now) { - return; - } - // THE FOOTPRINT IS SERVING'S ONLY WHEN NOTHING ELSE LIVES IN THE ENGINE (SHARED-RESIDENT- - // LIFECYCLE.md step 2). On the 5090 (2026-09-28 12:29:07) the lane's reading carried a live - // /train run's graph, optimizer and adapter, ~7.4 GB that the record then treated as fixed - // per-lane serving residency; the 27B stopped fitting and the plan replaced the engine - // the run was in. So while live work is bound to this engine, or its binding cannot be - // read, the reading is WITHHELD; and for one sample interval after work leaves (the - // engine frees asynchronously, the device reports late) it is withheld too, as it is for - // the first interval of a process (a predecessor's release is unknown to it). The release - // retired a record sampled during the work; a reading in flight across a bind or release - // is refused when it publishes. - // The token is taken BEFORE occupancy is read: work that binds or leaves after this - // point refuses the reading at publication (Codex on #4536), however long it awaits. - let token = crate::inference::lane_footprint::begin_sample(); - let occupancy = self.engine_occupancy(); - let settling = crate::inference::engine_residency::released_within(now, crate::inference::lane_footprint::SAMPLE_EVERY_MS); - if occupancy.holds() || settling { - crate::probe!( - class = "serving.footprint.unmeasured", - leg = if occupancy.holds() { "resident_work" } else { "resident_work_settling" }, - occupancy = %format!("{occupancy:?}"), - "the engine hosts (or just released) work that is not serving: its footprint is not \ - serving cost, so the per-token reading is WITHHELD" - ); - return; - } - let live = self.serving_tx.borrow().clone(); - if !live.ready || live.lanes == 0 || live.served_context_window == 0 { - return; - } - let Some(active) = live.active_model.clone() else { - return; - }; - let Some(pid) = crate::inference::lane_pidfile::read() else { - return; - }; - let Some(model) = (self.model_resolver)(&active) else { - return; - }; - let Some(fp) = footprint_for(&model) else { - return; - }; - // THE FOOTPRINT SOURCE IS PER HOST CLASS (Fable, 2026-09-17, converging #4152 and - // #4164): on unified memory the lane's KV lives in system RAM, so its anonymous - // process footprint IS the bytes beyond the weights. On a discrete GPU the KV - // lives in VRAM, a process read misses it entirely, and WDDM attributes VRAM to - // no process at all (`nvidia-smi --query-compute-apps` prints [N/A] for every - // pid on the 5090) — so the discrete arm is the DEVICE delta across the launch: - // used-now minus used-before-spawn, minus the weights (in VRAM on this class). - // Both arms feed the ONE consumer below; the probe names which one spoke. A - // CPU-placed lane (#3729) holds nothing on the device whatever the host class, - // so the device delta would read zero for a lane whose KV fills system RAM — - // the process read is the one that sees it. - // - // ON A DISCRETE GPU THE ENGINE'S OWN KV SPEAKS FIRST (card 03cdeee3; BigMama's 5090 - // receipt and Codex's design, 2026-10-11). The device delta holds every tenant of the - // GPU (the embedding lane's 1.75 GiB lease) and the engine's unreported overhead; divided - // by tokens it read 85.8 KB/token where this engine's own context bytes read 46.4 KB, and - // the plan carried the excess as fixed bytes PER LANE, so every extra lane paid for the - // other tenants again. The reading is now the engine's KV over the tokens it allocated; - // what the delta holds beyond everything the engine claims is probed as UNATTRIBUTED and - // never enters this model's record. The delta still speaks for an engine that predates - // `memory_breakdown`. - // On a HYBRID model the context buffer also holds each slot's fixed recurrent state, so the - // rate is an UPPER bound by that state spread over the slot's tokens, and a plan for more, - // shorter slots is short one recurrent state per extra slot (BigMama on #4961). Splitting - // it out needs the engine to report it per sequence: card c8b2e1df. - let placement = crate::inference::llama_server::main_lane_placement(); - let (source, beyond_weights, allocated) = match (placement, self.system.gpu_memory_mode()) { - ( - crate::inference::llama_server::LanePlacement::Gpu, - Some(crate::gpu::monitor::MemoryMode::Discrete), - ) => { - let baseline = self.spawn_baseline_vram.load(Ordering::Relaxed); - let now = vram_physical_used(&self.resource_daemon); - let delta = device_delta_beyond_weights(baseline, now, fp.weights_bytes); - // An engine that did not ANSWER is an unavailable observation, not an engine - // without the field: falling to the delta there would write the tenant-charged - // rate back under the same record on one 500 ms miss (Codex on #4961). Only an - // engine that answered WITHOUT `memory_breakdown` (one predating it) is measured - // by the delta; a breakdown or geometry that is present but unusable is no reading. - let Some(props) = engine_props().await else { - crate::probe!( - class = "serving.footprint.unmeasured", - leg = "engine_unanswered", - model = %active, - pid = pid as u64, - "the engine's /props did not answer in time: no reading this sample, and the device delta does not stand in for it" - ); - return; - }; - use crate::inference::weight_residency::EngineContextReading; - match (EngineContextReading::of(&props), delta) { - (EngineContextReading::Invalid, _) => { - crate::probe!( - class = "serving.footprint.unmeasured", - leg = "engine_breakdown_invalid", - model = %active, - pid = pid as u64, - "the engine reports a memory breakdown, but it or its slot geometry is unusable: no reading this sample, and the device delta does not stand in for it" - ); - return; - } - (EngineContextReading::Read(ctx), _) => { - crate::probe!( - class = "serving.footprint.device_residual", - model = %active, - engine_context_bytes = ctx.context_bytes, - engine_beyond_weights = ctx.beyond_weights, - device_delta_read = delta.is_some(), - device_delta_beyond_weights = delta.unwrap_or(0), // unwrap_or: probe label; `device_delta_read` says whether it exists - // absent, never 0: an unread delta is not "nothing unattributed" (BigMama on #4961) - unattributed_bytes = %delta.map_or_else(|| "none".to_string(), |d| d.saturating_sub(ctx.beyond_weights).to_string()), - "the device's growth beyond the weights against what the engine says it holds: the excess is other tenants or engine overhead, never this model's per-token cost" - ); - ("engine_context", Some(ctx.context_bytes), Some(ctx)) - } - (EngineContextReading::Absent, Some(delta)) => ("device_delta", Some(delta), None), - (EngineContextReading::Absent, None) => { - crate::probe!( - class = "serving.footprint.device_delta_unread", - baseline_bytes = baseline, - now_bytes = now, - weights_bytes = fp.weights_bytes, - "neither the engine's breakdown nor a device delta beyond the weights (no baseline, no reading, or a baseline that already held the weights)" - ); - ("device_delta", None, None) - } - } - } - _ => ( - "process_anon", - crate::inference::lane_footprint::anon_footprint_of(pid), - None, - ), - }; - let outcome = match beyond_weights { - // An UNKNOWN grant withholds the reading (Cormac's condition, 2026-09-20): with 0 - // subtracted the whole prompt cache would read as per-token bytes and be saved - // as the record — the corrupt 262k reading this measurement produced on the - // re-home path, reproduced on the deploy path. An absence stays an absence: - // no `observe`, no record written, the previous record stands. - Some(_) if live.host_prompt_cache_mib == 0 => { - crate::probe!( - class = "serving.footprint.unmeasured", - leg = "unknown_grant", - model = %active, - pid = pid as u64, - source, - lanes = live.lanes as u64, - window = live.served_context_window as u64, - "the engine's cache grant is unknown (an adopted lane whose argv names no \ - --cache-ram, and no spawn fact) — the per-token reading is WITHHELD rather \ - than taken with the whole prompt cache attributed as per-token bytes" - ); - "unmeasured" - } - // A STARVED window withholds the reading too: at 2,048 tokens the bytes beyond - // weights are the engine's fixed buffers, and dividing them by 2,048 reads as - // hundreds of KB per token — saved, that record fits no window at all and pins - // the next plan at the floor it fell to (the trap a collapsed node cannot climb - // out of). Below one full turn's window the measurement is not a measurement. - // …and RETIRES the model's record (Cormac's condition on #4255): a node already - // in the trap holds a ~244k B/token record that corrects the plan UP to the - // floor; left standing behind a withheld reading it rules forever. Retired, the - // plan falls back to the estimate, plans a real window, and the next honest - // reading replaces the estimate — the node climbs out without a hand on a file. - Some(_) if !crate::inference::lane_footprint::window_measurable(live.served_context_window) => { - let retired = crate::inference::lane_footprint::retire(&active); - crate::probe!( - class = "serving.footprint.unmeasured", - leg = "starved_window", - model = %active, - pid = pid as u64, - source, - lanes = live.lanes as u64, - window = live.served_context_window as u64, - floor = crate::inference::lane_footprint::MEASURABLE_WINDOW_MIN as u64, - record_retired = retired, - "the served window is below one full turn — the per-token reading is WITHHELD \ - (the excess over weights is fixed buffers, not tokens) and the model's record \ - is RETIRED so a trap record cannot keep the plan at the floor" - ); - "unmeasured" - } - Some(anon) => { - // The engine's KV is decomposed over the geometry the ENGINE holds (its slots, a - // scratch slot included, at its per-slot context) with no compute floor: the - // reading holds no compute. Every other source is the plan's own decomposition. - let (lanes, window, compute_floor) = match allocated { - Some(ctx) => (ctx.slots, ctx.n_ctx_per_slot, 0), - // the BASE buffer: the fixed term is derived from this reading - // (`base_compute_buffer_per_lane`, the M5's two-tick flap) - None => (live.lanes, live.served_context_window, fp.base_compute_buffer_per_lane()), - }; - let predicted = match allocated { - Some(_) => fp.kv_at(window).saturating_mul(lanes as u64), - None => fp - .kv_at(window) - .saturating_mul(lanes as u64) - .saturating_add(fp.prefill_compute_reserve(window, lanes)), - }; - // The host prompt cache the ENGINE was launched with (`--cache-ram`, on - // the snapshot as a fact about the process): it fills the same anonymous - // footprint over the serve's life and is not per-token cost — subtracted - // before anything is attributed. It used to be read from a cell the - // target derivation rewrote every tick the plan changed; on 2026-09-20 - // 07:52Z that cell went 14,396 → 256 MiB under a running 2-lane engine - // and the reading here went 33k → 262k B/token, saved to disk. - // `--cache-ram` lives in HOST RAM: only a process reading contains it. The device - // readings (device_delta, engine_context) never saw it, so subtracting it there - // would undercount the per-token cost or retire the record (Cormac on #4459). - let host_cache_bytes = if source == "process_anon" { - (live.host_prompt_cache_mib as u64) * 1024 * 1024 - } else { - 0 - }; - let measured = crate::inference::lane_footprint::observe( - token, - &active, - lanes, - window, - anon, - compute_floor, - host_cache_bytes, - ); - let Ok(measured) = measured else { - crate::probe!( - class = "serving.footprint.unmeasured", - leg = "residency_changed", - model = %active, - pid = pid as u64, - source, - "work bound to or left the engine while this reading was taken: it may \ - straddle that work, so it is DROPPED and the record stands" - ); - return; - }; - crate::probe!( - class = "serving.footprint.measured", - model = %active, - pid = pid as u64, - source, - lanes = lanes as u64, - window = window as u64, - anon_bytes = anon, - host_cache_bytes, - predicted_beyond_weights = predicted, - ratio = anon as f64 / predicted.max(1) as f64, - per_token_estimate = fp.kv_per_token, - // absent, never 0: a reading that yields no per-token rate is not a rate of - // zero (card b5230492: 0 printed every minute read like a measurement) - per_token_measured = %measured.map_or_else(|| "none".to_string(), |rate| rate.to_string()), - "the lane's footprint (its process, or on a discrete GPU the engine's own KV) against the plan's arithmetic" - ); - "read" - } - None => "could_not_look", - }; - if outcome == "could_not_look" { - crate::probe!( - class = "serving.footprint.measured", - model = %active, - pid = pid as u64, - source, - outcome, - "the lane's footprint could not be read: no process reading on this host class, \ - or no spawn baseline (an adopted lane) for the device delta" - ); - } - } - fn publish_moe_host_cache_lease(&self) { let live = self.serving_tx.borrow().clone(); if !live.ready || live.served_context_window == 0 { diff --git a/core/continuum-core/src/modules/serving_daemon/footprint.rs b/core/continuum-core/src/modules/serving_daemon/footprint.rs new file mode 100644 index 0000000000..543d6be988 --- /dev/null +++ b/core/continuum-core/src/modules/serving_daemon/footprint.rs @@ -0,0 +1,272 @@ +//! Sampling the live serving engine's physical footprint. + +use super::*; + +impl ServingDaemonModule { + pub(super) async fn sample_lane_footprint(&self) { + // The board's credit first, every tick and unconditionally. The per-token reading + // below is taken once a minute and withheld while other work lives in the engine, + // but the engine's device holding is serving's own the whole time. A once-a-minute + // credit would read a freshly relaunched engine as nobody's for up to a minute, which + // is exactly when a relaunch is sized. `/props` is one local call per tick. + self.refresh_engine_device_credit().await; + let now = EpochMs::now().millis(); + if !crate::inference::lane_footprint::sample_due(now) { + return; + } + // THE FOOTPRINT IS SERVING'S ONLY WHEN NOTHING ELSE LIVES IN THE ENGINE (SHARED-RESIDENT- + // LIFECYCLE.md step 2). On the 5090 (2026-09-28 12:29:07) the lane's reading carried a live + // /train run's graph, optimizer and adapter, ~7.4 GB that the record then treated as fixed + // per-lane serving residency; the 27B stopped fitting and the plan replaced the engine + // the run was in. So while live work is bound to this engine, or its binding cannot be + // read, the reading is WITHHELD; and for one sample interval after work leaves (the + // engine frees asynchronously, the device reports late) it is withheld too, as it is for + // the first interval of a process (a predecessor's release is unknown to it). The release + // retired a record sampled during the work; a reading in flight across a bind or release + // is refused when it publishes. + // The token is taken BEFORE occupancy is read: work that binds or leaves after this + // point refuses the reading at publication (Codex on #4536), however long it awaits. + let token = crate::inference::lane_footprint::begin_sample(); + let occupancy = self.engine_occupancy(); + let settling = crate::inference::engine_residency::released_within(now, crate::inference::lane_footprint::SAMPLE_EVERY_MS); + if occupancy.holds() || settling { + crate::probe!( + class = "serving.footprint.unmeasured", + leg = if occupancy.holds() { "resident_work" } else { "resident_work_settling" }, + occupancy = %format!("{occupancy:?}"), + "the engine hosts (or just released) work that is not serving: its footprint is not \ + serving cost, so the per-token reading is WITHHELD" + ); + return; + } + let live = self.serving_tx.borrow().clone(); + if !live.ready || live.lanes == 0 || live.served_context_window == 0 { + return; + } + let Some(active) = live.active_model.clone() else { + return; + }; + let Some(pid) = crate::inference::lane_pidfile::read() else { + return; + }; + let Some(model) = (self.model_resolver)(&active) else { + return; + }; + let Some(fp) = footprint_for(&model) else { + return; + }; + // THE FOOTPRINT SOURCE IS PER HOST CLASS (Fable, 2026-09-17, converging #4152 and + // #4164): on unified memory the lane's KV lives in system RAM, so its anonymous + // process footprint IS the bytes beyond the weights. On a discrete GPU the KV + // lives in VRAM, a process read misses it entirely, and WDDM attributes VRAM to + // no process at all (`nvidia-smi --query-compute-apps` prints [N/A] for every + // pid on the 5090) — so the discrete arm is the DEVICE delta across the launch: + // used-now minus used-before-spawn, minus the weights (in VRAM on this class). + // Both arms feed the ONE consumer below; the probe names which one spoke. A + // CPU-placed lane (#3729) holds nothing on the device whatever the host class, + // so the device delta would read zero for a lane whose KV fills system RAM — + // the process read is the one that sees it. + // + // ON A DISCRETE GPU THE ENGINE'S OWN KV SPEAKS FIRST (card 03cdeee3; BigMama's 5090 + // receipt and Codex's design, 2026-10-11). The device delta holds every tenant of the + // GPU (the embedding lane's 1.75 GiB lease) and the engine's unreported overhead; divided + // by tokens it read 85.8 KB/token where this engine's own context bytes read 46.4 KB, and + // the plan carried the excess as fixed bytes PER LANE, so every extra lane paid for the + // other tenants again. The reading is now the engine's KV over the tokens it allocated; + // what the delta holds beyond everything the engine claims is probed as UNATTRIBUTED and + // never enters this model's record. The delta still speaks for an engine that predates + // `memory_breakdown`. + // On a HYBRID model the context buffer also holds each slot's fixed recurrent state, so the + // rate is an UPPER bound by that state spread over the slot's tokens, and a plan for more, + // shorter slots is short one recurrent state per extra slot (BigMama on #4961). Splitting + // it out needs the engine to report it per sequence: card c8b2e1df. + let placement = crate::inference::llama_server::main_lane_placement(); + let (source, beyond_weights, allocated) = match (placement, self.system.gpu_memory_mode()) { + (crate::inference::llama_server::LanePlacement::Gpu, Some(crate::gpu::monitor::MemoryMode::Discrete)) => { + let baseline = self.spawn_baseline_vram.load(Ordering::Relaxed); + let now = vram_physical_used(&self.resource_daemon); + let delta = device_delta_beyond_weights(baseline, now, fp.weights_bytes); + // An engine that did not ANSWER is an unavailable observation, not an engine + // without the field: falling to the delta there would write the tenant-charged + // rate back under the same record on one 500 ms miss (Codex on #4961). Only an + // engine that answered WITHOUT `memory_breakdown` (one predating it) is measured + // by the delta; a breakdown or geometry that is present but unusable is no reading. + let Some(props) = engine_props().await else { + crate::probe!( + class = "serving.footprint.unmeasured", + leg = "engine_unanswered", + model = %active, + pid = pid as u64, + "the engine's /props did not answer in time: no reading this sample, and the device delta does not stand in for it" + ); + return; + }; + use crate::inference::weight_residency::EngineContextReading; + match (EngineContextReading::of(&props), delta) { + (EngineContextReading::Invalid, _) => { + crate::probe!( + class = "serving.footprint.unmeasured", + leg = "engine_breakdown_invalid", + model = %active, + pid = pid as u64, + "the engine reports a memory breakdown, but it or its slot geometry is unusable: no reading this sample, and the device delta does not stand in for it" + ); + return; + } + (EngineContextReading::Read(ctx), _) => { + crate::probe!( + class = "serving.footprint.device_residual", + model = %active, + engine_context_bytes = ctx.context_bytes, + engine_beyond_weights = ctx.beyond_weights, + device_delta_read = delta.is_some(), + device_delta_beyond_weights = delta.unwrap_or(0), // unwrap_or: probe label; `device_delta_read` says whether it exists + // absent, never 0: an unread delta is not "nothing unattributed" (BigMama on #4961) + unattributed_bytes = %delta.map_or_else(|| "none".to_string(), |d| d.saturating_sub(ctx.beyond_weights).to_string()), + "the device's growth beyond the weights against what the engine says it holds: the excess is other tenants or engine overhead, never this model's per-token cost" + ); + ("engine_context", Some(ctx.context_bytes), Some(ctx)) + } + (EngineContextReading::Absent, Some(delta)) => ("device_delta", Some(delta), None), + (EngineContextReading::Absent, None) => { + crate::probe!( + class = "serving.footprint.device_delta_unread", + baseline_bytes = baseline, + now_bytes = now, + weights_bytes = fp.weights_bytes, + "neither the engine's breakdown nor a device delta beyond the weights (no baseline, no reading, or a baseline that already held the weights)" + ); + ("device_delta", None, None) + } + } + } + _ => ("process_anon", crate::inference::lane_footprint::anon_footprint_of(pid), None), + }; + let outcome = match beyond_weights { + // An UNKNOWN grant withholds the reading (Cormac's condition, 2026-09-20): with 0 + // subtracted the whole prompt cache would read as per-token bytes and be saved + // as the record — the corrupt 262k reading this measurement produced on the + // re-home path, reproduced on the deploy path. An absence stays an absence: + // no `observe`, no record written, the previous record stands. + Some(_) if live.host_prompt_cache_mib == 0 => { + crate::probe!( + class = "serving.footprint.unmeasured", + leg = "unknown_grant", + model = %active, + pid = pid as u64, + source, + lanes = live.lanes as u64, + window = live.served_context_window as u64, + "the engine's cache grant is unknown (an adopted lane whose argv names no \ + --cache-ram, and no spawn fact) — the per-token reading is WITHHELD rather \ + than taken with the whole prompt cache attributed as per-token bytes" + ); + "unmeasured" + } + // A STARVED window withholds the reading too: at 2,048 tokens the bytes beyond + // weights are the engine's fixed buffers, and dividing them by 2,048 reads as + // hundreds of KB per token — saved, that record fits no window at all and pins + // the next plan at the floor it fell to (the trap a collapsed node cannot climb + // out of). Below one full turn's window the measurement is not a measurement. + // …and RETIRES the model's record (Cormac's condition on #4255): a node already + // in the trap holds a ~244k B/token record that corrects the plan UP to the + // floor; left standing behind a withheld reading it rules forever. Retired, the + // plan falls back to the estimate, plans a real window, and the next honest + // reading replaces the estimate — the node climbs out without a hand on a file. + Some(_) if !crate::inference::lane_footprint::window_measurable(live.served_context_window) => { + let retired = crate::inference::lane_footprint::retire(&active); + crate::probe!( + class = "serving.footprint.unmeasured", + leg = "starved_window", + model = %active, + pid = pid as u64, + source, + lanes = live.lanes as u64, + window = live.served_context_window as u64, + floor = crate::inference::lane_footprint::MEASURABLE_WINDOW_MIN as u64, + record_retired = retired, + "the served window is below one full turn — the per-token reading is WITHHELD \ + (the excess over weights is fixed buffers, not tokens) and the model's record \ + is RETIRED so a trap record cannot keep the plan at the floor" + ); + "unmeasured" + } + Some(anon) => { + // The engine's KV is decomposed over its physical token capacity, + // independently of its sequence limits, with no compute floor: the + // reading holds no compute. Every other source is the plan's own decomposition. + let (lanes, window, allocated_tokens, compute_floor) = match allocated { + Some(ctx) => (ctx.slots, ctx.n_ctx_per_slot, ctx.allocated_tokens, 0), + // the BASE buffer: the fixed term is derived from this reading + // (`base_compute_buffer_per_lane`, the M5's two-tick flap) + None => ( + live.lanes, + live.served_context_window, + u64::from(live.lanes) * u64::from(live.served_context_window), + fp.base_compute_buffer_per_lane(), + ), + }; + let predicted = match allocated { + Some(_) => fp.kv_per_token.saturating_mul(allocated_tokens), + None => fp.kv_at(window).saturating_mul(lanes as u64).saturating_add(fp.prefill_compute_reserve(window, lanes)), + }; + // The host prompt cache the ENGINE was launched with (`--cache-ram`, on + // the snapshot as a fact about the process): it fills the same anonymous + // footprint over the serve's life and is not per-token cost — subtracted + // before anything is attributed. It used to be read from a cell the + // target derivation rewrote every tick the plan changed; on 2026-09-20 + // 07:52Z that cell went 14,396 → 256 MiB under a running 2-lane engine + // and the reading here went 33k → 262k B/token, saved to disk. + // `--cache-ram` lives in HOST RAM: only a process reading contains it. The device + // readings (device_delta, engine_context) never saw it, so subtracting it there + // would undercount the per-token cost or retire the record (Cormac on #4459). + let host_cache_bytes = if source == "process_anon" { (live.host_prompt_cache_mib as u64) * 1024 * 1024 } else { 0 }; + let measured = + crate::inference::lane_footprint::observe(token, &active, lanes, window, allocated_tokens, anon, compute_floor, host_cache_bytes); + let Ok(measured) = measured else { + crate::probe!( + class = "serving.footprint.unmeasured", + leg = "residency_changed", + model = %active, + pid = pid as u64, + source, + "work bound to or left the engine while this reading was taken: it may \ + straddle that work, so it is DROPPED and the record stands" + ); + return; + }; + crate::probe!( + class = "serving.footprint.measured", + model = %active, + pid = pid as u64, + source, + lanes = lanes as u64, + window = window as u64, + allocated_tokens, + anon_bytes = anon, + host_cache_bytes, + predicted_beyond_weights = predicted, + ratio = anon as f64 / predicted.max(1) as f64, + per_token_estimate = fp.kv_per_token, + // absent, never 0: a reading that yields no per-token rate is not a rate of + // zero (card b5230492: 0 printed every minute read like a measurement) + per_token_measured = %measured.map_or_else(|| "none".to_string(), |rate| rate.to_string()), + "the lane's footprint (its process, or on a discrete GPU the engine's own KV) against the plan's arithmetic" + ); + "read" + } + None => "could_not_look", + }; + if outcome == "could_not_look" { + crate::probe!( + class = "serving.footprint.measured", + model = %active, + pid = pid as u64, + source, + outcome, + "the lane's footprint could not be read: no process reading on this host class, \ + or no spawn baseline (an adopted lane) for the device delta" + ); + } + } +} diff --git a/core/source-hygiene/src/file_size.rs b/core/source-hygiene/src/file_size.rs index 225b7c82ef..8d35467c83 100644 --- a/core/source-hygiene/src/file_size.rs +++ b/core/source-hygiene/src/file_size.rs @@ -44,7 +44,7 @@ pub const READABLE_FILE_LINES: usize = 1_000; // 157,412 after card a00ab1a6 deleted the standing benchmark autopilot (no harness). // 156,830 after card 5e3a3e75 deleted three hand copies of paths::continuum_home. // 156,825 after card 394017ed folded ensure_slot_pool's inline probes into one typed miss. -const BASELINE_LINES_OVER: usize = 156_710; +const BASELINE_LINES_OVER: usize = 156_429; pub struct FileSize; diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index a30f3dc73e..5b5cad25ee 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -50b02b8bb55102665500327b2152fe7e3348e1bc +29eaf83aab1e146910e9ead7ad51507ee8396820 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index 50b02b8bb5..29eaf83aab 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit 50b02b8bb55102665500327b2152fe7e3348e1bc +Subproject commit 29eaf83aab1e146910e9ead7ad51507ee8396820 From 3f0be60b8136a620d23ebe92936a4e105f438dd1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 20 Oct 2026 04:59:13 -0500 Subject: [PATCH 2/2] fix(serving): carry physical allocation through fixed-cost reconstruction --- .../src/cognition/serving_plan/footprint.rs | 38 +++++++++---- .../src/inference/lane_footprint.rs | 4 ++ .../src/inference/weight_residency.rs | 55 +++++++++---------- 3 files changed, 56 insertions(+), 41 deletions(-) diff --git a/core/continuum-core/src/cognition/serving_plan/footprint.rs b/core/continuum-core/src/cognition/serving_plan/footprint.rs index c593e82420..b9ffb12bd9 100644 --- a/core/continuum-core/src/cognition/serving_plan/footprint.rs +++ b/core/continuum-core/src/cognition/serving_plan/footprint.rs @@ -76,7 +76,7 @@ pub fn footprint_for(model: &Model) -> Option { ); if header_rate.is_some() { if let Some(record) = &measured { - fp.fixed_per_lane_bytes = fixed_per_lane_from(fp.kv_per_token, record); + fp.fixed_per_lane_bytes = fixed_per_lane_from(fp.kv_per_token, record)?; // One row when the value CHANGES: this runs on every footprint read (measured // 2026-09-19 23:2xZ on the M5: 840 identical rows in 12 minutes, 70/min — the // ledger-rotation class, the same shape the knee clamp's row had). @@ -100,13 +100,19 @@ pub fn footprint_for(model: &Model) -> Option { } /// The residency a sample measured BEYOND the header's per-token rate, as fixed bytes per -/// lane: `(measured − rate) × the window it was measured at`. Zero when the sample agrees -/// with the header. The rate stays physics; the residency stays counted. -pub fn fixed_per_lane_from(header_rate: u64, record: &crate::inference::lane_footprint::MeasuredCost) -> u64 { - record - .per_token_bytes - .saturating_sub(header_rate) - .saturating_mul(record.window as u64) +/// lane: excess per physical token × allocated tokens / lanes. Historical records without +/// allocation retain their divided-cache window semantics. Invalid geometry is not a footprint. +pub fn fixed_per_lane_from(header_rate: u64, record: &crate::inference::lane_footprint::MeasuredCost) -> Option { + if record.lanes == 0 || record.window == 0 { + return None; + } + let tokens = match record.allocated_tokens { + Some(0) => return None, + Some(tokens) => u128::from(tokens), + None => u128::from(record.lanes) * u128::from(record.window), + }; + let excess = u128::from(record.per_token_bytes.saturating_sub(header_rate)); + u64::try_from(excess * tokens / u128::from(record.lanes)).ok() } /// THE PROCESS BEATS THE ARITHMETIC. When the live lane's anonymous footprint, read @@ -285,7 +291,7 @@ mod tests { let per_token = crate::inference::lane_footprint::per_token_from(anon, lanes, window, fp.base_compute_buffer_per_lane(), 0) .expect("test: a reading"); let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: per_token, lanes, window, allocated_tokens: None, anon_bytes: anon, last_ms: 0 }; - fp.fixed_per_lane_bytes = fixed_per_lane_from(header_rate, &record); + fp.fixed_per_lane_bytes = fixed_per_lane_from(header_rate, &record).expect("valid fixture geometry"); seen.push(fp.fixed_per_lane_bytes); } let tolerance = u64::from(window); // integer division loses under one byte per token @@ -311,9 +317,19 @@ mod tests { // across budgets the plan with it fits no more lanes than the header-only plan // and no fewer than the raised-rate plan — strictly between them somewhere. let record = crate::inference::lane_footprint::MeasuredCost { per_token_bytes: 55_925, lanes: 1, window: 67_340, allocated_tokens: None, anon_bytes: 0, last_ms: 0 }; - let fixed = fixed_per_lane_from(32_768, &record); + let fixed = fixed_per_lane_from(32_768, &record).expect("valid fixture geometry"); assert!((1_500_000_000..1_620_000_000).contains(&fixed), "{fixed} B per lane"); - assert_eq!(fixed_per_lane_from(65_536, &record), 0, "a sample under the rate carries nothing"); + assert_eq!(fixed_per_lane_from(65_536, &record), Some(0), "a sample under the rate carries nothing"); + let mut unified = record.clone(); + unified.per_token_bytes = 200; + unified.lanes = 2; + unified.window = 32_768; + unified.allocated_tokens = Some(32_768); + assert_eq!(fixed_per_lane_from(100, &unified), Some(1_638_400)); + unified.allocated_tokens = None; + assert_eq!(fixed_per_lane_from(100, &unified), Some(3_276_800), "legacy divided allocation"); + unified.lanes = 0; + assert_eq!(fixed_per_lane_from(100, &unified), None); let base = ModelFootprint { model_id: "m5-27b".into(), weights_bytes: 16_500_000_000, kv_per_token: 32_768, context_window: 262_144, capability_rank: 42, fixed_per_lane_bytes: 0, }; diff --git a/core/continuum-core/src/inference/lane_footprint.rs b/core/continuum-core/src/inference/lane_footprint.rs index 46db98644f..2398d71236 100644 --- a/core/continuum-core/src/inference/lane_footprint.rs +++ b/core/continuum-core/src/inference/lane_footprint.rs @@ -617,6 +617,10 @@ mod tests { ); save_to(&path, &costs); assert_eq!(load_from(&path), costs); + let mut legacy = serde_json::to_value(&costs).expect("record fixture"); + legacy["m"].as_object_mut().expect("record object").remove("allocated_tokens"); + std::fs::write(&path, serde_json::to_vec(&legacy).expect("legacy bytes")).expect("write legacy"); + assert_eq!(load_from(&path), costs, "old records omit allocated_tokens entirely"); std::fs::write(&path, b"{not json").expect("write"); assert!(load_from(&path).is_empty()); } diff --git a/core/continuum-core/src/inference/weight_residency.rs b/core/continuum-core/src/inference/weight_residency.rs index 67fece1af7..8f98cb8de0 100644 --- a/core/continuum-core/src/inference/weight_residency.rs +++ b/core/continuum-core/src/inference/weight_residency.rs @@ -32,11 +32,7 @@ impl WeightResidency { /// buffer types: `CPU`, `CPU_Mapped`, `CPU_REPACK`, `*_Host` (CUDA pinned host /// memory is still RAM), and BLAS (Accelerate on a Mac runs on the CPU). pub fn accelerator_bytes(&self) -> u64 { - self.per_backend - .iter() - .filter(|(name, _)| !is_host_backend(name)) - .map(|(_, b)| *b) - .sum() + self.per_backend.iter().filter(|(name, _)| !is_host_backend(name)).map(|(_, b)| *b).sum() } pub fn total_bytes(&self) -> u64 { @@ -45,11 +41,7 @@ impl WeightResidency { /// One line for a probe or a refusal message: `Metal=4.7GB CPU_Mapped=0.3GB`. pub fn summary(&self) -> String { - self.per_backend - .iter() - .map(|(n, b)| format!("{n}={:.2}GB", *b as f64 / 1e9)) - .collect::>() - .join(" ") + self.per_backend.iter().map(|(n, b)| format!("{n}={:.2}GB", *b as f64 / 1e9)).collect::>().join(" ") } } @@ -81,11 +73,7 @@ impl EngineMemory { /// The bytes BEYOND the weights on accelerators: KV cache + compute buffers on every buffer /// type that is not host memory. What the device delta measures on a discrete GPU. pub fn accelerator_beyond_weights(&self) -> u64 { - self.per_buffer - .iter() - .filter(|b| !is_host_backend(&b.buffer_type)) - .map(|b| b.context_bytes + b.compute_bytes) - .sum() + self.per_buffer.iter().filter(|b| !is_host_backend(&b.buffer_type)).map(|b| b.context_bytes + b.compute_bytes).sum() } /// The KV (context) bytes alone on accelerators, compute buffers excluded. @@ -133,7 +121,7 @@ impl EngineContextReading { // (`{"error": …}`), or a geometry that is missing, null or zero is not an old engine, // and a missing breakdown there is no reading (Codex on #4961). The same parse decides // here and in `from_props`, so the two cannot disagree about what a geometry is. - if slot_geometry(props).is_none() { + if slot_geometry(props).and_then(|(slots, window)| allocated_capacity(props, slots, window)).is_none() { return Self::Invalid; } if props.get("memory_breakdown").is_none() { @@ -149,25 +137,29 @@ impl EngineContext { pub fn from_props(props: &serde_json::Value) -> Option { let memory = EngineMemory::from_props(props)?; let (slots, n_ctx_per_slot) = slot_geometry(props)?; - let allocated_tokens = match props.get("context_geometry") { - Some(geometry) => { - let tokens = geometry.get("allocated_tokens")?.as_u64()?; - let capacity = geometry.get("sequence_capacity")?.as_u64()?; - let window = geometry.get("max_tokens_per_sequence")?.as_u64()?; - if tokens == 0 || capacity != u64::from(slots) || window != u64::from(n_ctx_per_slot) || window > tokens { - return None; - } - tokens - } - // Older managed engines used divided caches. Only absence permits their - // legacy geometry; a present malformed receipt must never take this path. - None => u64::from(slots) * u64::from(n_ctx_per_slot), - }; + let allocated_tokens = allocated_capacity(props, slots, n_ctx_per_slot)?; let context_bytes = memory.accelerator_context(); (context_bytes > 0).then(|| Self { context_bytes, beyond_weights: memory.accelerator_beyond_weights(), slots, allocated_tokens, n_ctx_per_slot }) } } +fn allocated_capacity(props: &serde_json::Value, slots: u32, n_ctx_per_slot: u32) -> Option { + match props.get("context_geometry") { + Some(geometry) => { + let tokens = geometry.get("allocated_tokens")?.as_u64()?; + let capacity = geometry.get("sequence_capacity")?.as_u64()?; + let window = geometry.get("max_tokens_per_sequence")?.as_u64()?; + if tokens == 0 || capacity != u64::from(slots) || window != u64::from(n_ctx_per_slot) || window > tokens { + return None; + } + Some(tokens) + } + // Older managed engines used divided caches. Only absence permits their + // legacy geometry; a present malformed receipt must never take this path. + None => Some(u64::from(slots) * u64::from(n_ctx_per_slot)), + } +} + /// The slot geometry an engine reports on `/props`: `total_slots` and each slot's `n_ctx`, both /// present, in range and nonzero. `None` otherwise. ONE parse, shared by the reading and by /// the legacy test, so "a valid props document" means one thing. @@ -227,6 +219,9 @@ mod tests { ] { unified["context_geometry"] = invalid; assert_eq!(EngineContextReading::of(&unified), EngineContextReading::Invalid); + let mut no_breakdown = unified.clone(); + no_breakdown.as_object_mut().expect("props fixture").remove("memory_breakdown"); + assert_eq!(EngineContextReading::of(&no_breakdown), EngineContextReading::Invalid); } // present but unusable is no reading, never the legacy fallback (Codex on #4961) assert_eq!(EngineContextReading::of(&props), EngineContextReading::Invalid, "no slot geometry");