Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/continuum-engine/src/inference/llama_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ mod control;
pub use control::{
EngineRetirementError, EngineRetirementReceipt, EngineRetirementStatus, EnsureOutcome,
LlamaServerControl, LlamaServerError, OwnedEngineIdentity, OwnedRestoreSession,
OwnedServingTarget, ServingLifecycleCheck,
ObservedGeometry, OwnedServingTarget, ServingLifecycleCheck,
};
mod prepared_launch;
use prepared_launch::{unsupported_launch_environment, PreparedLocalLaunch};
Expand Down
21 changes: 19 additions & 2 deletions core/continuum-engine/src/inference/llama_server/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,22 @@ pub struct OwnedServingTarget {
/// Public diagnostic projection of explicit arguments and managed environment.
/// Only the private original prepared receipt can authorize exact replay.
pub invocation: crate::inference::lane_args::LaneInvocation,
pub observed_context_window: u32,
pub observed_lanes: u32,
/// The geometry the running engine reported when it came ready.
pub observed: ObservedGeometry,
pub launched_host_prompt_cache_mib: u32,
}


/// What a running engine reported about its context when it came ready, read off its own `/props`:
/// each sequence's limit (`n_ctx`, capped at the trained window), its sequences (`total_slots`),
/// and its whole KV pool (`context_geometry.allocated_tokens`, our fork's report).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ObservedGeometry {
pub context_window: u32,
pub lanes: u32,
pub pool_tokens: u32,
}

/// Checked at the endpoint's drained lifecycle-admission boundary. Once admitted,
/// the operation may settle even if newer intent arrives; its result keeps its epoch.
pub type ServingLifecycleCheck<'a> = dyn Fn() -> bool + Send + Sync + 'a;
Expand Down Expand Up @@ -332,6 +342,13 @@ pub trait LlamaServerControl: Send + Sync {
/// `n_ctx` (a loud invariant violation — never a guessed window).
async fn served_context_window(&self) -> Result<u32, LlamaServerError>;

/// The tokens the engine's KV holds in all, from `/props` `context_geometry.allocated_tokens`
/// (`llama_n_ctx`): the ONE shared pool under `--kv-unified`, the sum of the slots without
/// it. Never `n_ctx` x slots: under a unified cache the fork caps each slot's `n_ctx` at the
/// model's trained window (server-context.cpp, "the slot context exceeds the training
/// context"), so `n_ctx` reads 32,768 on a 65,536 pool (IntelMac, 2026-11-03 07:32Z).
async fn served_pool_tokens(&self) -> Result<u32, LlamaServerError>;

/// The REAL number of continuous-batching slots the running server serves,
/// read from its own `/props` (`total_slots`) — the LANE sibling of
/// [`Self::served_context_window`], and for the same reason.
Expand Down
13 changes: 13 additions & 0 deletions core/continuum-engine/src/inference/llama_server/control_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,19 @@ impl LlamaServerControl for LlamaServerProcess {
})
}

async fn served_pool_tokens(&self) -> Result<u32, LlamaServerError> {
let body = self.props_json().await?;
crate::inference::weight_residency::ContextGeometry::from_props(&body)
.and_then(|geometry| u32::try_from(geometry.allocated_tokens).ok())
.ok_or_else(|| {
LlamaServerError::Unreachable(
"/props has no valid context_geometry: the engine is not our fork's (refusing \
to guess the pool)"
.to_string(),
)
})
}

async fn served_engine_build(&self) -> Result<Option<String>, LlamaServerError> {
let body = self.props_json().await?;
Ok(body
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,11 @@ mod tests {
while !props_open.load(std::sync::atomic::Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(20)).await;
}
axum::Json(serde_json::json!({ "default_generation_settings": { "n_ctx": 32768 }, "total_slots": 1 }))
axum::Json(serde_json::json!({
"default_generation_settings": { "n_ctx": 32768 },
"total_slots": 1,
"context_geometry": { "allocated_tokens": 32768, "max_tokens_per_sequence": 32768, "sequence_capacity": 1 }
}))
}
}))
.route("/v1/models", axum::routing::get(|| async {
Expand Down
36 changes: 16 additions & 20 deletions core/continuum-engine/src/inference/llama_server/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ impl LlamaServerProcess {
return "<no home dir>".to_string();
};
match std::fs::read_to_string(&path) {
Ok(s) => tail_or_hang_marker(&s),
Ok(s) => tail_or_hang_marker(&path.display().to_string(), &s),
// The marker is the contract (never block the error path), but a bare
// "unreadable" hides WHY — permissions vs absent vs mid-rotation.
Err(e) => format!("<stderr log unreadable: {e}>"),
Expand All @@ -364,20 +364,18 @@ impl LlamaServerProcess {
/// dies before llama.cpp prints its banner) vs. a genuine early-init hang (child
/// still running at the deadline). A crash from bad args or a model-load fault
/// prints the banner + fault FIRST, so a non-empty tail carries that directly.
/// Pure so the load-bearing empty-vs-tail decision is unit-tested without touching
/// the real `~/.continuum/logs` path ([[self-test-via-command-feedback-surface-
/// never-blind]], and #72's env-dependent-test lesson).
pub(super) fn tail_or_hang_marker(contents: &str) -> String {
let mut lines: Vec<&str> = contents.lines().rev().take(20).collect();
lines.reverse();
let tail = lines.join("\n");
if tail.trim().is_empty() {
"<stderr log empty — child produced no output before it stopped: with a SIGKILL/137 \
exit this is an OS OOM/jetsam kill (a second large model that didn't fit in free \
memory); with no exit status it is a genuine early-init hang>"
.to_string()
} else {
tail
/// The report names the log (the whole output, reachable) and its last line (where a fault
/// prints); it never picks a fixed number of lines to keep. Pure so the load-bearing
/// empty-vs-fault decision is unit-tested without touching the real `~/.continuum/logs` path
/// ([[self-test-via-command-feedback-surface-never-blind]], and #72's env-dependent-test lesson).
pub(super) fn tail_or_hang_marker(log_path: &str, contents: &str) -> String {
match contents.lines().rev().find(|line| !line.trim().is_empty()) {
Some(last) => format!("{last} (full log: {log_path})"),
None => format!(
"<stderr log empty — child produced no output before it stopped: with a SIGKILL/137 \
exit this is an OS OOM/jetsam kill (a second large model that didn't fit in free \
memory); with no exit status it is a genuine early-init hang> (log: {log_path})"
),
}
}

Expand Down Expand Up @@ -407,8 +405,7 @@ impl LlamaServerProcess {
invocation: &crate::inference::lane_args::LaneInvocation,
prepared: Option<Arc<PreparedLocalLaunch>>,
engine_program: &str,
context: u32,
lanes: u32,
observed: ObservedGeometry,
) {
let mut child = self.child.lock().unwrap(); // JUSTIFIED: poison means prior panic mutating the owned child.
if let Some(owned) = child
Expand All @@ -417,7 +414,7 @@ impl LlamaServerProcess {
{
let prepared = prepared.map(|original| {
let mut verified = original.as_ref().clone();
verified.expected_geometry = Some((context, lanes));
verified.expected_geometry = Some((observed.context_window, observed.lanes));
Arc::new(verified)
});
owned.verified_target = Some(OwnedServingTarget {
Expand All @@ -429,8 +426,7 @@ impl LlamaServerProcess {
target: target.clone(),
engine_program: engine_program.to_string(),
invocation: invocation.clone(),
observed_context_window: context,
observed_lanes: lanes,
observed,
launched_host_prompt_cache_mib: self
.launched_prompt_cache_mib
.load(std::sync::atomic::Ordering::Relaxed),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ impl LlamaServerProcess {
}
let context = self.served_context_window().await?;
let slots = self.served_lanes().await?;
let pool = self.served_pool_tokens().await?;
if context == 0 || slots == 0 || self.child_exit_status().is_some() {
return Err(LlamaServerError::Spawn(
"engine readiness lacks live slot geometry".into(),
Expand Down Expand Up @@ -231,7 +232,7 @@ impl LlamaServerProcess {
transition
.ready(
&self.root,
&generation,
generation,
crate::inference::slots::KvPageContract {
model_id: target.model.id.clone(),
model: gguf,
Expand All @@ -253,13 +254,12 @@ impl LlamaServerProcess {
}
}
self.record_verified_target(
&generation,
generation,
target,
invocation,
Some(prepared.clone()),
&prepared.engine_program,
context,
slots,
ObservedGeometry { context_window: context, lanes: slots, pool_tokens: pool },
);
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,7 @@ where
&prepared.invocation,
Some(prepared.clone()),
&process.engine_bin().unwrap(),
11008,
4,
ObservedGeometry { context_window: 11008, lanes: 4, pool_tokens: 11008 * 4 },
);
drop(transition);
let captured = process.owned_serving_target().unwrap();
Expand Down Expand Up @@ -317,8 +316,7 @@ where
&prepared.invocation,
Some(prepared.clone()),
&process.engine_bin().unwrap(),
11008,
4,
ObservedGeometry { context_window: 11008, lanes: 4, pool_tokens: 11008 * 4 },
);
let transition = endpoint.transition().await;
transition
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-engine/src/inference/llama_server/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ impl LlamaServerControl for FakeControl {
// check is a no-op unless a test deliberately floors it.
Ok(self.served_window)
}
async fn served_pool_tokens(&self) -> Result<u32, LlamaServerError> {
// The fake's pool: its window over its lanes (at least one), as an engine reports it.
Ok(self.served_window.saturating_mul(self.served_lanes.max(1)))
}
async fn served_lanes(&self) -> Result<u32, LlamaServerError> {
// The slot count the fake's /props reports (configurable via
// `with_served_lanes`). Defaults to 0 = "nothing to compare", so the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,26 +103,19 @@ fn a_loading_engine_of_ours_is_not_a_failed_one() {
}

#[test]
fn tail_or_hang_marker_fingerprints_empty_and_tails_nonempty() {
fn tail_or_hang_marker_fingerprints_empty_and_names_the_fault_and_the_log() {
let log = "/logs/llama-server-58057.log";
assert!(
tail_or_hang_marker("").contains("OOM/jetsam"),
tail_or_hang_marker(log, "").contains("OOM/jetsam"),
"an empty log is the no-output fingerprint naming the OOM-kill cause, not a silent blank"
);
assert!(
tail_or_hang_marker(" \n\n \t \n").contains("OOM/jetsam"),
tail_or_hang_marker(log, " \n\n \t \n").contains("OOM/jetsam"),
"whitespace-only counts as empty"
);
let log = (1..=30)
.map(|i| format!("line{i}"))
.collect::<Vec<_>>()
.join("\n");
let tail = tail_or_hang_marker(&log);
assert!(
tail.contains("line30") && tail.contains("line11") && !tail.contains("line10"),
"keeps the LAST 20 lines in original order, not the first: {tail}"
);
// sanity: order preserved (line11 appears before line30)
assert!(tail.find("line11") < tail.find("line30"));
let report = tail_or_hang_marker(log, "load_model: loading\nGGML_ASSERT(n_ctx > 0) failed\n\n");
assert!(report.starts_with("GGML_ASSERT(n_ctx > 0) failed"), "the last printed line leads: {report}");
assert!(report.contains(log), "the whole log stays reachable by its path: {report}");
}

// what this catches (M5 2026-10-25, card 9e3350bd's second site): a synthetic smoke decode
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,7 @@ async fn retiring_page_owner_requires_observed_child_exit() {
&invocation,
Some(prepared),
&process.engine_bin().unwrap(),
11008,
4,
ObservedGeometry { context_window: 11008, lanes: 4, pool_tokens: 11008 * 4 },
);
drop(engine_install);
let captured = process.owned_serving_target().unwrap();
Expand Down Expand Up @@ -272,15 +271,15 @@ async fn retiring_page_owner_requires_observed_child_exit() {
true,
);
let launched = invocation.clone();
process.record_verified_target(&generation, &launch_target, &invocation, None, &process.engine_bin().unwrap(), 11008, 4);
process.record_verified_target(&generation, &launch_target, &invocation, None, &process.engine_bin().unwrap(), ObservedGeometry { context_window: 11008, lanes: 4, pool_tokens: 11008 * 4 });
// A later resolved choice cannot mutate the already verified generation.
invocation.args.push("--different-future-policy".into());
let recorded = process
.owned_serving_target()
.expect("verified owned provenance");
assert_eq!(recorded.target.context_window, launch_target.context_window);
assert_eq!(recorded.observed_context_window, 11008);
assert_eq!(recorded.observed_lanes, 4);
assert_eq!(recorded.observed.context_window, 11008);
assert_eq!(recorded.observed.lanes, 4);
assert_eq!(recorded.engine_program, process.engine_bin().unwrap());
assert_eq!(recorded.invocation, launched);
let restore_admitted = std::sync::atomic::AtomicBool::new(false);
Expand All @@ -305,7 +304,7 @@ async fn retiring_page_owner_requires_observed_child_exit() {
let mut drifted = launch_target.clone();
// Downsize from what the engine actually serves, not the larger original
// request: half of 32768 still exceeds this fixture's 11008-token lane.
drifted.context_window = recorded.observed_context_window / 2;
drifted.context_window = recorded.observed.context_window / 2;
drifted.host_prompt_cache_mib = launch_target.host_prompt_cache_mib.saturating_add(1);
let admissions = AtomicUsize::new(0);
let admit = || {
Expand Down
24 changes: 24 additions & 0 deletions core/continuum-engine/src/inference/llama_server/tests/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,27 @@ fn real_token_delivery_is_recorded_as_liveness_evidence() {
"a decode recorded just now must read as recent, got {since}ms"
);
}

// what this catches (IntelMac, 2026-11-03 07:32Z): the share divided the slot's `n_ctx`, which
// the fork caps at the trained window under `--kv-unified` (a 65,536 pool reads 32,768), so
// each of 2 minds was published 16,384 instead of 32,768. The pool is `allocated_tokens`.
#[tokio::test]
async fn the_pool_is_the_engines_allocated_tokens_never_the_capped_slot_window() {
let app = axum::Router::new().route(
"/props",
axum::routing::get(|| async {
axum::Json(serde_json::json!({
"default_generation_settings": {"n_ctx": 32_768},
"total_slots": 2,
"context_geometry": {"allocated_tokens": 65_536, "max_tokens_per_sequence": 32_768, "sequence_capacity": 2}
}))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("test: bind");
let root = format!("http://{}", listener.local_addr().expect("test: addr"));
let server = tokio::spawn(async move { axum::serve(listener, app).await });
let process = LlamaServerProcess::with_root(root);
assert_eq!(process.served_context_window().await.expect("test: n_ctx"), 32_768);
assert_eq!(process.served_pool_tokens().await.expect("test: pool"), 65_536);
server.abort();
}
Loading
Loading