diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs index 5a66c9f7ec..c0f43d62cb 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs @@ -548,3 +548,46 @@ fn an_over_budget_prompt_is_a_budget_fault_never_a_clipped_prompt() { assert!(fault.contains("prompt budget violated"), "{fault}"); assert!(view.messages.first().is_some_and(|m| m.content_text().contains("turn_0 ")), "nothing was cut to comply"); } + +// what this catches (Codex on #5491): a tail her destination can no longer take, either silently +// dropped (she is offered a head missing verbs she was told she had) or turned into a lost turn. +// The typed refusal rebuilds her request ONCE on the activity's own surface, with no tail, and +// sends it; a second refusal after that rebuild is a named fault, never a loop. +#[tokio::test] +async fn a_refused_tail_rebuilds_her_request_without_it_once() { + use crate::ai::inference_error::InferenceError; + use crate::cognition::workspace::Burst; + + for refusals in [1usize, 2] { + let persona = Uuid::new_v4(); + let adapter = Arc::new(ScriptedAdapter::new(vec![make_response(FinishReason::Stop, "PASS", None)])); + let mut left = refusals; + *adapter.on_request.lock().expect("fixture request hook") = Some(Box::new(move |_request| { + (left > 0).then(|| { + left -= 1; + InferenceError::TailToolsUnreachable { model: "scripted".into() } + }) + })); + let faculty = LlmDeliberationFaculty::new(persona, "Ivar", "You are Ivar.", adapter.clone()) + .with_context_window(32_768) + .with_tools(vec![read_tool()]); + let ws = Workspace::new(Burst::from_turns( + crate::identity::ActivityRoom::mint(), + vec![BurstTurn::attributed(false, "Peer", "Read src/lib.rs and tell me what it exports.", Some(1))], + )); + let contribution = faculty.contribute(&ws).await.expect("a verdict or named fault"); + let seen = adapter.seen.lock().expect("fixture requests"); + assert_eq!(seen.len(), 2, "one refusal, one rebuilt send: never a third ({refusals} refusals)"); + let rebuilt = &seen[1]; + assert!(rebuilt.tail_tools.is_none(), "the rebuilt request carries no tail"); + let offered: Vec<&str> = rebuilt.tools.iter().flatten().map(|tool| tool.name.as_str()).collect(); + let activity = faculty.select_activity_surface(&ws); + let expected: Vec<&str> = activity.specs.iter().flat_map(|specs| specs.iter()).map(|tool| tool.name.as_str()).collect(); + assert!(!offered.is_empty() && offered == expected, "she is offered exactly her activity's surface: {offered:?}"); + if refusals == 1 { + assert!(contribution.fault.is_none(), "the rebuilt request answered: {:?}", contribution.fault); + } else { + assert!(contribution.fault.is_some(), "a refusal after the rebuild is a named fault"); + } + } +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs index 156c40b039..9eb03d5cc1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tool_surface.rs @@ -77,7 +77,7 @@ impl LlmDeliberationFaculty { u32::try_from(budget).unwrap_or(u32::MAX), // unwrap_or: a share past u32 bounds nothing a schema set can reach &cost, ); - if !binding.adapter.accepts_tail_tools() { + if !binding.adapter.accepts_tail_tools(binding.requested_model()) { return selected; } let reserve = next.as_ref().map_or(0, |next| next.tokens() as usize); // map_or: no next head reserves nothing beyond this one @@ -101,6 +101,13 @@ impl LlmDeliberationFaculty { /// consecutive acts in one activity send byte-identical schemas, so the prefix after the /// system prompt survives (goal 10; [`crate::cognition::tool_surface`] has the why). pub fn select_tool_surface(&self, ws: &Workspace) -> SelectedSurface<'_> { + self.with_learned_head(self.select_activity_surface(ws), ws) + } + + /// The activity's own surface, without her learned head: what she is offered when her + /// destination refused the tail (`InferenceError::TailToolsUnreachable`), so every verb she + /// sees is one she can call. + pub(super) fn select_activity_surface(&self, ws: &Workspace) -> SelectedSurface<'_> { let selected = self.surface.select(&ws.room_affordances, self.binding.load().context_window); if !ws.room_affordances.is_empty() && !matches!(selected.reason, SurfaceReason::RoomAffordances | SurfaceReason::NoTools) @@ -114,7 +121,7 @@ impl LlmDeliberationFaculty { the rule binds nothing here; offering her hands instead" ); } - self.with_learned_head(selected, ws) + selected } /// Her view started a new epoch, the one moment her head may change: her tool head learns @@ -131,7 +138,7 @@ impl LlmDeliberationFaculty { continuum_base::probe!( class = "delib.tool_head.epoch", persona = %self.persona_name, - sent = self.binding.load().adapter.accepts_tail_tools(), + sent = { let binding = self.binding.load(); binding.adapter.accepts_tail_tools(binding.requested_model()) }, learned = cost.learned, calls = cost.calls, misses = cost.misses, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index c6985640af..c9012d764e 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -121,6 +121,9 @@ impl LlmDeliberationFaculty { let mut rejected_prompt_tokens = None; let mut rejected_measured_tokens = None; let mut request_template: Option = None; + // Her destination refused the tail her learned head promised: rebuilt once on the + // activity's own surface, so she is never offered a verb she cannot call. + let mut tail_refused = false; let mut view = self.prompt_view_with_visual_feedback(ws, fit_window, calibration, visual.as_ref()); let mut gen_await_ms = 0u64; @@ -207,7 +210,7 @@ impl LlmDeliberationFaculty { // [`Self::select_tool_surface`] so the budget in `prompt_view_within` reaches the // SAME answer (card dec1a7ff). if request_template.is_none() { - let mut selected = self.select_tool_surface(ws); + let mut selected = if tail_refused { self.select_activity_surface(ws) } else { self.select_tool_surface(ws) }; // Verbs she loaded into the tail ride beside the head, callable natively. let tail = std::mem::take(&mut selected.tail); if selected.reason == SurfaceReason::CoreHandsForWindow { @@ -335,6 +338,17 @@ impl LlmDeliberationFaculty { } }; } + Err(crate::ai::inference_error::InferenceError::TailToolsUnreachable { model }) if !tail_refused => { + continuum_base::probe!( + class = "delib.tool_head.tail_refused", + persona = %self.persona_name, + model = %model, + "the engine her request reaches cannot take her tail verbs now: rebuilding \ + on the activity's surface, never sending a head missing verbs she was offered" + ); + tail_refused = true; + request_template = None; + } Err(error) => { return Some(Contribution::deliberation_fault(error.to_string())); } diff --git a/core/continuum-engine/src/ai/adapter/inference_device.rs b/core/continuum-engine/src/ai/adapter/inference_device.rs index bbcc2594c6..1dded42d63 100644 --- a/core/continuum-engine/src/ai/adapter/inference_device.rs +++ b/core/continuum-engine/src/ai/adapter/inference_device.rs @@ -415,9 +415,10 @@ pub trait AIProviderAdapter: Send + Sync { AdapterCapabilities::text_only() } - /// Whether this adapter's server accepts `tail_tools` (callable verbs outside the rendered - /// head). Default `false`: only a server that declares it gets a learned tool head. - fn accepts_tail_tools(&self) -> bool { + /// Whether a request for `model` reaches a server that accepts `tail_tools` (callable verbs + /// outside the rendered head), decided for the destination that request is routed to. + /// Default `false`: only a server that declares it gets a learned tool head. + fn accepts_tail_tools(&self, _model: &str) -> bool { false } diff --git a/core/continuum-engine/src/ai/inference_error.rs b/core/continuum-engine/src/ai/inference_error.rs index 856b25e993..67954b8896 100644 --- a/core/continuum-engine/src/ai/inference_error.rs +++ b/core/continuum-engine/src/ai/inference_error.rs @@ -81,6 +81,13 @@ pub enum InferenceError { /// field, unexpected schema). Retrying verbatim is unlikely to help; this /// is a bug on one side of the wire, so it must stay loud. Protocol(String), + + /// The request carried `tail_tools` (verbs callable outside her rendered head), but the + /// engine it is routed to now does not take them: the lane was replaced, its build is not + /// verified, or the route moved to another server. Sending it without the tail would hand + /// her a head that lacks verbs she was told she could call, so it is refused instead. + /// PERMANENT for the unchanged request: the caller rebuilds her surface without the tail. + TailToolsUnreachable { model: String }, } impl InferenceError { @@ -93,6 +100,7 @@ impl InferenceError { match self { Self::ContextExceeded { .. } => false, Self::Protocol(_) => false, + Self::TailToolsUnreachable { .. } => false, Self::Unavailable(_) | Self::Transient(_) => true, } } @@ -191,6 +199,10 @@ impl fmt::Display for InferenceError { Self::Unavailable(detail) => write!(f, "backend unavailable: {detail}"), Self::Transient(detail) => write!(f, "{detail}"), Self::Protocol(detail) => write!(f, "protocol error: {detail}"), + Self::TailToolsUnreachable { model } => write!( + f, + "the engine serving {model} does not take tail_tools now: rebuild the request without its tail" + ), } } } diff --git a/core/continuum-engine/src/ai/openai_adapter/provider.rs b/core/continuum-engine/src/ai/openai_adapter/provider.rs index b0e6b0d9fb..0b326d6c5e 100644 --- a/core/continuum-engine/src/ai/openai_adapter/provider.rs +++ b/core/continuum-engine/src/ai/openai_adapter/provider.rs @@ -13,8 +13,10 @@ impl AIProviderAdapter for OpenAICompatibleAdapter { &self.config.provider_id } - fn accepts_tail_tools(&self) -> bool { - self.config.tail_tools + /// The provider declares the family (our fork's gateway); the engine the request for `model` + /// actually reaches decides, by the build that engine itself reports (`route_now`). + fn accepts_tail_tools(&self, model: &str) -> bool { + self.route_now(model, &self.endpoints()).tail_tools } /// The live set the daemon's reconcile / `/v1/models` refresh verified diff --git a/core/continuum-engine/src/ai/openai_adapter/runtime.rs b/core/continuum-engine/src/ai/openai_adapter/runtime.rs index ea0574ec65..989e913562 100644 --- a/core/continuum-engine/src/ai/openai_adapter/runtime.rs +++ b/core/continuum-engine/src/ai/openai_adapter/runtime.rs @@ -154,9 +154,16 @@ impl OpenAICompatibleAdapter { /// [`PROVIDER_ID`](crate::inference::llama_server::PROVIDER_ID) const — no /// name sniffing), and the address exists only when `/props` confirmed /// sight, so pixels can never be aimed at a text lane. - pub(super) fn endpoints_for_model(&self, model: &str, base: &OpenAiBase) -> OpenAiBase { + /// + /// PURE over `snap`: the caller loads the snapshot once ([`Self::route_now`]) so the URL + /// and every decision about the destination (its `tail_tools`) read the same route. + pub(super) fn endpoints_for_model( + &self, + model: &str, + base: &OpenAiBase, + snap: &crate::inference::llama_server::ServingSnapshot, + ) -> OpenAiBase { if self.config.provider_id == crate::inference::llama_server::PROVIDER_ID { - let snap = crate::inference::llama_server::current_serving(); if snap.vision_ready && snap.vision_model.as_deref() == Some(model) && snap.active_model.as_deref() != Some(model) @@ -169,6 +176,40 @@ impl OpenAICompatibleAdapter { base.clone() } + /// The route a request for `model` takes NOW, and whether it may carry `tail_tools`, from ONE + /// serving snapshot and one evidence read: the head (`accepts_tail_tools`) and the send + /// (`stream_checked`) both take this pair, so the wire URL and the tail gate never come from + /// two different snapshots (Codex on #5491). + pub(super) fn route_now(&self, model: &str, base: &OpenAiBase) -> RequestRoute { + self.route_for( + model, + base, + &crate::inference::llama_server::current_serving(), + crate::inference::llama_server::serving_engine_takes_tail_tools(), + ) + } + + /// PURE: [`Self::route_now`] over one `snap`. The tail gate holds only where the route + /// ([`Self::endpoints_for_model`]) reaches the serving lane whose own reported build takes + /// `tail_tools` (`engine_takes`). That evidence is about the main lane only, so a request + /// routed to the vision sidecar, a dedicated lane, or any other base gets `false`, as does a + /// provider outside the fork-gateway family. + pub(super) fn route_for( + &self, + model: &str, + base: &OpenAiBase, + snap: &crate::inference::llama_server::ServingSnapshot, + engine_takes: bool, + ) -> RequestRoute { + let route = self.endpoints_for_model(model, base, snap); + let tail_tools = self.config.tail_tools + && !self.dedicated_lane + && engine_takes + && !snap.base_url.is_empty() + && route.root() == OpenAiBase::new(&snap.base_url).root(); + RequestRoute { base: route, tail_tools } + } + /// Fetch the live model list from the provider's /v1/models endpoint. /// Used by adapters that have dynamic catalogs (DMR above all — the list /// changes every time the user runs `docker model pull`). Populates @@ -425,3 +466,12 @@ impl OpenAICompatibleAdapter { Ok(pool) } } + + +/// Where one request goes and whether it may carry `tail_tools`, decided together from one +/// snapshot ([`OpenAICompatibleAdapter::route_now`]). +#[derive(Debug, Clone)] +pub(super) struct RequestRoute { + pub(super) base: OpenAiBase, + pub(super) tail_tools: bool, +} diff --git a/core/continuum-engine/src/ai/openai_adapter/stream.rs b/core/continuum-engine/src/ai/openai_adapter/stream.rs index 53c91c2501..aa015cb0a3 100644 --- a/core/continuum-engine/src/ai/openai_adapter/stream.rs +++ b/core/continuum-engine/src/ai/openai_adapter/stream.rs @@ -358,7 +358,10 @@ impl OpenAICompatibleAdapter { // Finish the body for the wire (thinking policy, response_format, native tools, // tool-surface probe) — `inference::request_body`. - crate::inference::request_body::finish_body(&self.config, &request, model, &mut body); + // ONE snapshot decides both where this request goes and whether it may carry its tail; + // a tail the destination cannot take is refused, never dropped (Codex on #5491). + let route = self.route_now(model, &endpoints); + crate::inference::request_body::finish_body(&self.config, &request, model, route.tail_tools, &mut body)?; // Make request — the endpoint base for THIS request's model. Normally the // runtime/config base; for the local serving gateway, a request for the @@ -366,9 +369,7 @@ impl OpenAICompatibleAdapter { // text-only mind) routes to the snapshot's verified `vision_base_url`. // Snapshot-driven: the daemon publishes the address only after `/props` // confirmed sight, so this can never aim pixels at a text lane. - let url = self - .endpoints_for_model(model, &endpoints) - .chat_completions(); + let url = route.base.chat_completions(); let mut request_builder = self .client diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs index aed7da28f5..b3ae242dbb 100644 --- a/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs +++ b/core/continuum-engine/src/ai/openai_adapter/tests/mod.rs @@ -18,6 +18,7 @@ mod lane_transport; mod lora_page_in; mod prefill_progress_is_liveness; mod request_shaping; +mod tail_tools_reach_the_verified_lane_only; mod unguaranteed_model_refusal_says_which_situation; /// Minimal adapter for pure payload-assembly tests — no network, no registry. diff --git a/core/continuum-engine/src/ai/openai_adapter/tests/tail_tools_reach_the_verified_lane_only.rs b/core/continuum-engine/src/ai/openai_adapter/tests/tail_tools_reach_the_verified_lane_only.rs new file mode 100644 index 0000000000..3d2d0f289d --- /dev/null +++ b/core/continuum-engine/src/ai/openai_adapter/tests/tail_tools_reach_the_verified_lane_only.rs @@ -0,0 +1,89 @@ +#![cfg(test)] + +use super::*; +use crate::ai::inference_error::InferenceError; +use crate::inference::llama_server::ServingSnapshot; + +const MAIN: &str = "http://127.0.0.1:8080/v1"; +const SIDECAR: &str = "http://127.0.0.1:8090/v1"; + +fn gateway(base: &str) -> OpenAICompatibleAdapter { + OpenAICompatibleAdapter::new(OpenAICompatibleConfig { + provider_id: crate::inference::llama_server::PROVIDER_ID.into(), + base_url: base.into(), + tail_tools: true, + capabilities: [crate::model_registry::Capability::ToolUse].into_iter().collect(), + ..test_adapter().config + }) +} + +/// The main lane serves `mind`; when `eyes_on_sidecar`, a vision sidecar serves `eyes`. +fn serving(active: &str, eyes_on_sidecar: bool) -> ServingSnapshot { + ServingSnapshot { + active_model: Some(active.into()), + ready: true, + base_url: MAIN.into(), + vision_ready: eyes_on_sidecar, + vision_base_url: eyes_on_sidecar.then(|| SIDECAR.into()), + vision_model: eyes_on_sidecar.then(|| "eyes".into()), + ..ServingSnapshot::empty() + } +} + +// what this catches (Codex on #5491): the capability decided for the main lane while the request +// goes elsewhere. A request for the vision sidecar's model is routed to `vision_base_url`, an +// engine whose build the gateway reconcile never read, so it must not carry tail verbs; nor may a +// dedicated lane, a provider outside the fork family, or a lane whose build is not verified. +#[test] +fn tail_tools_are_decided_for_the_engine_the_request_reaches() { + let snap = serving("mind", true); + let adapter = gateway(MAIN); + let base = adapter.endpoints(); + let main = adapter.route_for("mind", &base, &snap, true); + assert!(main.tail_tools && main.base.root() == OpenAiBase::new(MAIN).root(), "the main lane, verified"); + let eyes = adapter.route_for("eyes", &base, &snap, true); + assert!(!eyes.tail_tools && eyes.base.root() == OpenAiBase::new(SIDECAR).root(), "routed to the unverified sidecar"); + assert!(!adapter.route_for("mind", &base, &snap, false).tail_tools, "the main lane's build is not verified"); + let dedicated = gateway(MAIN).with_dedicated_lane(); + assert!(!dedicated.route_for("mind", &dedicated.endpoints(), &snap, true).tail_tools, "a dedicated lane"); + let other = gateway("http://127.0.0.1:9999/v1"); + assert!(!other.route_for("mind", &other.endpoints(), &snap, true).tail_tools, "another server"); + let cloud = OpenAICompatibleAdapter::new(OpenAICompatibleConfig { base_url: MAIN.into(), ..test_adapter().config }); + assert!(!cloud.route_for("mind", &cloud.endpoints(), &snap, true).tail_tools, "outside the fork-gateway family"); +} + +// what this catches (Codex on #5491): a TRANSITION between selection and send. Her head was built +// while `eyes` was served by the main lane (tail accepted); by send time the sidecar serves it. +// The send decides URL and gate from ONE snapshot, so the pair is consistent (sidecar, no tail), +// and the tail she was promised is refused for a rebuild instead of being silently dropped. +#[test] +fn a_route_that_moves_between_selection_and_send_refuses_the_tail_never_drops_it() { + let adapter = gateway(MAIN); + let base = adapter.endpoints(); + let at_selection = adapter.route_for("eyes", &base, &serving("eyes", false), true); + assert!(at_selection.tail_tools, "selected while the main lane served her model"); + + let at_send = adapter.route_for("eyes", &base, &serving("mind", true), true); + assert_eq!(at_send.base.root(), OpenAiBase::new(SIDECAR).root(), "the send goes to the sidecar now"); + assert!(!at_send.tail_tools, "and the gate comes from the same snapshot as that URL"); + + let spec = |name: &str| crate::ai::types::NativeToolSpec { + name: name.to_owned(), + description: format!("{name} does one thing"), + input_schema: crate::ai::types::ToolInputSchema { + schema_type: "object".to_owned(), + properties: serde_json::json!({}), + required: None, + definitions: None, + }, + }; + let request = TextGenerationRequest { + tools: Some(vec![spec("commands_help")]), + tail_tools: Some(vec![spec("code_git_apply")]), + ..Default::default() + }; + let mut body = serde_json::json!({ "model": "eyes" }); + let sent = crate::inference::request_body::finish_body(&adapter.config, &request, "eyes", at_send.tail_tools, &mut body); + assert_eq!(sent, Err(InferenceError::TailToolsUnreachable { model: "eyes".into() })); + assert!(!InferenceError::TailToolsUnreachable { model: "eyes".into() }.is_retryable_unchanged(), "rebuilt, never resent as is"); +} diff --git a/core/continuum-engine/src/inference/lane_registry.rs b/core/continuum-engine/src/inference/lane_registry.rs index 0a2411812c..e17c1ea33d 100644 --- a/core/continuum-engine/src/inference/lane_registry.rs +++ b/core/continuum-engine/src/inference/lane_registry.rs @@ -176,6 +176,18 @@ pub fn live_lane() -> Option { (rec.role == LaneRole::Live && rec.pid == pid).then_some(rec) } +/// The incarnation (pid + OS start time + port) of the LIVE lane the canonical pidfile names, +/// from its registry record alone: two small file reads, no process-table probe, so the gateway +/// reconcile can ask it every tick. Every live launch rewrites both files, so a replacement +/// engine always reads as a different incarnation. `None` without a pidfile or a matching live +/// record, or for a record without a start time, which names no one process. +pub fn live_incarnation() -> Option { + let pid = lane_pidfile::read()?; + let body = std::fs::read_to_string(lanes_dir()?.join(format!("{pid}.lane"))).ok()?; + let rec = serde_json::from_str::(&body).ok()?; + (rec.role == LaneRole::Live && rec.pid == pid && rec.started_s != 0).then(|| rec.incarnation()) +} + /// WHY a sweep is running — the one axis on which boot and shutdown differ. /// /// They differ in exactly one judgement: what a still-alive LIVE-role record diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index e222222c48..3ffbf10607 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -85,6 +85,9 @@ pub(crate) use genome::gene_stage_name; pub use genome::{engine_accepts_train_dir, engine_train_dir, GenomeInPlace}; use genome::{engine_help_lists_train_dir, ENGINE_TRAIN_DIR}; mod engine_install; +mod engine_features; +pub use engine_features::serving_engine_takes_tail_tools; +use engine_features::{forget_served_engine, observe_served_engine}; #[cfg(windows)] pub(crate) use engine_install::engine_override; pub(crate) use engine_install::{installed_engine_commit, lane_runs_installed_engine}; diff --git a/core/continuum-engine/src/inference/llama_server/control.rs b/core/continuum-engine/src/inference/llama_server/control.rs index a5ae58685e..407a95fb1f 100644 --- a/core/continuum-engine/src/inference/llama_server/control.rs +++ b/core/continuum-engine/src/inference/llama_server/control.rs @@ -361,6 +361,16 @@ pub trait LlamaServerControl: Send + Sync { Ok(None) } + /// The engine process serving this endpoint now ([`EngineIncarnation`]: pid + OS start + /// time + port), owned or adopted, read from the lane pidfile and its registry record: + /// what a `/props` reading is evidence about. `None` = unknown (a fake or remote control, + /// no pidfile, a record without a start time): no reading outlives a probe error then. + /// + /// [`EngineIncarnation`]: crate::inference::engine_residency::EngineIncarnation + fn served_incarnation(&self) -> Option { + None + } + /// The multimodal capabilities the running server ITSELF reports in `/props` /// (`modalities.vision` / `modalities.audio`) — the endpoint-side truth of /// whether the `--mmproj` projector actually loaded (#106). `Ok(None)` means diff --git a/core/continuum-engine/src/inference/llama_server/control_impl.rs b/core/continuum-engine/src/inference/llama_server/control_impl.rs index e06ffc9c29..8ecc256ef8 100644 --- a/core/continuum-engine/src/inference/llama_server/control_impl.rs +++ b/core/continuum-engine/src/inference/llama_server/control_impl.rs @@ -317,6 +317,11 @@ impl LlamaServerControl for LlamaServerProcess { self.stamp_observed_placement().await; } + fn served_incarnation(&self) -> Option { + let (_host, port) = split_host_port(&self.root); + crate::inference::lane_registry::live_incarnation().filter(|lane| lane.port == port) + } + fn launch_kv(&self) -> Option { let (_host, port) = split_host_port(&self.root); let record = crate::inference::lane_registry::live_lane().filter(|r| r.port == port)?; diff --git a/core/continuum-engine/src/inference/llama_server/engine_features.rs b/core/continuum-engine/src/inference/llama_server/engine_features.rs new file mode 100644 index 0000000000..528c20b001 --- /dev/null +++ b/core/continuum-engine/src/inference/llama_server/engine_features.rs @@ -0,0 +1,131 @@ +//! What the RUNNING engine can do beyond a stock llama-server, decided from the build the lane +//! itself reports (`/props` `build_info`): never a table, an env var or a constant `true`. +//! +//! `tail_tools` (CambrianTech/llama.cpp#75) is a request field only: the fork's server names it +//! in no `/props` key and no `--help` flag, so nothing about the engine says it outright. The +//! evidence is the revision. A lane whose reported commit IS the commit this tree pins runs the +//! pinned source, and source-hygiene's `vendor_pin` proves that source parses `tail_tools`. Any +//! other build (an older lane a deploy left running, an operator's engine, a stock server, a +//! `build_info` naming no credible commit) is not evidence and answers `false`, so a mind's +//! learned tool head stays a shadow there instead of sending verbs a server would read as text. +//! Card ae4137f1 replaces the revision tie with a `/props` field once the fork reports one. +//! +//! The evidence belongs to ONE engine process ([`EngineIncarnation`]: pid + OS start time + +//! port), never to the URL: successive engines answer at the same address (Codex on #5491). + +use crate::inference::engine_residency::EngineIncarnation; + +/// The fork commit this tree pins, compiled in from the one file a PR edits to move it. +const PINNED_ENGINE: &str = include_str!("../../../../vendor/LLAMA_CPP_PIN"); + +/// The build one engine incarnation reported in its own `/props`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct ServedEngine { + /// The process the reading came from; `None` when the lane's identity could not be read. + incarnation: Option, + /// What its `/props` `build_info` named; `None` when it named none. + build: Option, +} + +impl ServedEngine { + /// One reconcile reading for the incarnation serving `now`. An answered `/props` replaces the + /// evidence. An unreadable one keeps it only while the SAME known incarnation still serves, + /// so a transient hiccup never flips her tool surface (and her cached prefix) for a tick, + /// while a replacement engine, or one whose identity is unknown, has no evidence until its + /// own `/props` answers. + pub(crate) fn observe(&mut self, now: Option, props: Result, ()>) { + match props { + Ok(build) => { + *self = Self { incarnation: now, build: build.map(str::to_owned) }; + } + Err(()) if now.is_some() && now == self.incarnation => {} + Err(()) => *self = Self::default(), + } + } + + /// Whether this evidence says the engine takes `tail_tools`: its build is the `pinned` one. + pub(crate) fn takes_tail_tools(&self, pinned: &str) -> bool { + self.build.as_deref().is_some_and(|build| build_takes_tail_tools(build, pinned)) + } +} + +/// The serving lane's evidence. Written only by the gateway reconcile (from the same `/props` +/// read that converges the engine) and cleared by every live-lane launch. +static SERVED_ENGINE: parking_lot::Mutex = + parking_lot::Mutex::new(ServedEngine { incarnation: None, build: None }); + +/// Record one reconcile reading of the serving lane (see [`ServedEngine::observe`]). +pub(super) fn observe_served_engine(now: Option, props: Result, ()>) { + SERVED_ENGINE.lock().observe(now, props); +} + +/// A new live engine is being launched: nothing is known about it until its own `/props` is read. +pub(super) fn forget_served_engine() { + *SERVED_ENGINE.lock() = ServedEngine::default(); +} + +/// PURE: whether a lane reporting `build_info` (`b10765-1c6681593`) runs the `pinned` commit, +/// whose source carries `tail_tools`. Both sides must be credible SHAs (the ONE SHA rule, +/// `deploy_provenance::sha_matches`); an unreadable build is not support. +pub(crate) fn build_takes_tail_tools(build_info: &str, pinned: &str) -> bool { + continuum_cli_lifecycle::deploy_provenance::sha_matches(super::engine_install::build_commit(build_info), pinned.trim()) +} + +/// Whether the serving lane's own reported build takes `tail_tools`. `false` until the gateway +/// reconcile has read the current engine's build, and for any build other than the pinned one. +pub fn serving_engine_takes_tail_tools() -> bool { + SERVED_ENGINE.lock().takes_tail_tools(PINNED_ENGINE) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pinned_build() -> String { + let short: String = PINNED_ENGINE.trim().chars().take(9).collect(); // the short commit llama.cpp stamps into build_info + format!("b10765-{short}") + } + + // what this catches: a learned tool head sent to an engine that cannot call a tail verb + // (an older lane a deploy left up, a stock or operator build, an unreadable build_info), + // or withheld from the lane that runs the pinned fork and does. + #[test] + fn only_a_lane_reporting_the_pinned_build_takes_tail_tools() { + assert!(build_takes_tail_tools(&pinned_build(), PINNED_ENGINE)); + assert!(build_takes_tail_tools(PINNED_ENGINE.trim(), PINNED_ENGINE)); + for other in ["b10765-e7e1077b3", "b10765-unknown", "b10765-", "", "unknown"] { + assert!(!build_takes_tail_tools(other, PINNED_ENGINE), "{other:?} must not take tail_tools"); + } + } + + // what this catches (Codex on #5491): a supported engine A replaced at the same URL by an + // engine B whose /props has not answered inheriting A's `true`; and the opposite slip, one + // transient /props error on the unchanged engine A flipping her surface off. + #[test] + fn evidence_survives_a_props_error_only_on_the_same_incarnation() { + let a = EngineIncarnation { pid: 100, started_s: 1_700_000_000, port: 8080 }; + let b = EngineIncarnation { pid: 200, started_s: 1_700_000_500, port: 8080 }; + let pinned = pinned_build(); + + let mut seen = ServedEngine::default(); + seen.observe(Some(a), Ok(Some(&pinned))); + assert!(seen.takes_tail_tools(PINNED_ENGINE), "A reports the pinned build"); + + seen.observe(Some(a), Err(())); + assert!(seen.takes_tail_tools(PINNED_ENGINE), "same incarnation, transient error: A's reading stands"); + + seen.observe(Some(b), Err(())); + assert!(!seen.takes_tail_tools(PINNED_ENGINE), "B replaced A and its /props errored: no evidence"); + + seen.observe(Some(a), Ok(Some(&pinned))); + seen.observe(None, Err(())); + assert!(!seen.takes_tail_tools(PINNED_ENGINE), "an unknown identity cannot be the same engine"); + + seen.observe(Some(b), Ok(Some("b10765-e7e1077b3"))); + assert!(!seen.takes_tail_tools(PINNED_ENGINE), "B answered with an older build"); + + let mut launched = ServedEngine::default(); // what `forget_served_engine` stores at every live launch + launched.observe(Some(b), Err(())); + assert!(!launched.takes_tail_tools(PINNED_ENGINE), "a launch clears the evidence until the new engine answers"); + } +} diff --git a/core/continuum-engine/src/inference/llama_server/engine_install.rs b/core/continuum-engine/src/inference/llama_server/engine_install.rs index a3397fa88c..8ee6750dc3 100644 --- a/core/continuum-engine/src/inference/llama_server/engine_install.rs +++ b/core/continuum-engine/src/inference/llama_server/engine_install.rs @@ -137,7 +137,7 @@ pub(super) fn installed_engine_stamp() -> Option { /// SHAs and they disagree; anything unreadable is not evidence (BigMama on 7c5f139d). pub(crate) fn lane_runs_installed_engine(build_info: &str, installed: &str) -> bool { use continuum_cli_lifecycle::deploy_provenance::sha_matches; - let lane = build_info.rsplit('-').next().unwrap_or(build_info).trim(); // unwrap_or: rsplit always yields one piece + let lane = build_commit(build_info); let credible = |sha: &str| sha_matches(sha, sha); // a SHA matches itself iff it is credible if !credible(lane) || !credible(installed) { return true; @@ -146,6 +146,13 @@ pub(crate) fn lane_runs_installed_engine(build_info: &str, installed: &str) -> b } +/// PURE: the commit a `/props` `build_info` (`b10765-965d38a90`) names: its last `-` piece, +/// trimmed. The one parse for every reader of a lane's build. +pub(super) fn build_commit(build_info: &str) -> &str { + build_info.rsplit('-').next().unwrap_or(build_info).trim() // unwrap_or: rsplit always yields one piece +} + + /// The stale-engine fact the reconcile last saw (`from -> to`), for the hour's health line /// (BigMama on 7c5f139d): "this node cannot dream" is read there, never inferred. pub(super) static ENGINE_STALE: parking_lot::Mutex> = parking_lot::Mutex::new(None); diff --git a/core/continuum-engine/src/inference/llama_server/launch.rs b/core/continuum-engine/src/inference/llama_server/launch.rs index 527ddc39b7..0e024e51cb 100644 --- a/core/continuum-engine/src/inference/llama_server/launch.rs +++ b/core/continuum-engine/src/inference/llama_server/launch.rs @@ -14,6 +14,11 @@ impl LlamaServerProcess { "prepared launch belongs to another endpoint".into(), )); } + if self.is_live_lane { + // A new engine process is coming: what the last one could take is not evidence + // for it (`tail_tools`); the reconcile reads the new one's own `/props`. + forget_served_engine(); + } let restore_generation = restore_session.map(|session| session.expected.lock().clone()); let restoring = restore_generation.is_some(); if restoring { diff --git a/core/continuum-engine/src/inference/llama_server/reconcile.rs b/core/continuum-engine/src/inference/llama_server/reconcile.rs index b5630b114b..171055173b 100644 --- a/core/continuum-engine/src/inference/llama_server/reconcile.rs +++ b/core/continuum-engine/src/inference/llama_server/reconcile.rs @@ -382,7 +382,11 @@ async fn serve_or_adopt( // neither the trade guard nor the memory gate applies: the relaunch is at the // same size, onto the binary already on disk. let installed_engine = installed_engine_commit(); - let served_engine = match ctrl.served_engine_build().await { + let served_engine_probe = ctrl.served_engine_build().await; + // The same reading decides what this engine process can take (`tail_tools`); an + // error keeps the evidence only while the same incarnation serves (Codex on #5491). + observe_served_engine(ctrl.served_incarnation(), served_engine_probe.as_ref().map(Option::as_deref).map_err(|_| ())); + let served_engine = match served_engine_probe { Ok(build) => build, Err(_) => None, // a probe error is "engine OK", as for the window and lanes }; diff --git a/core/continuum-engine/src/inference/request_body.rs b/core/continuum-engine/src/inference/request_body.rs index 620a244a1d..6aa7fd8c94 100644 --- a/core/continuum-engine/src/inference/request_body.rs +++ b/core/continuum-engine/src/inference/request_body.rs @@ -107,12 +107,19 @@ pub fn deliberation_reasoning_budget(max_tokens: u64) -> Option { Some(max_tokens - answer_share) } +/// `tail_tools`: whether the engine this request is routed to takes our fork's `tail_tools` +/// (the adapter's `route_now`, decided with the URL from one snapshot). A request that carries +/// a tail the body cannot send is refused as [`InferenceError::TailToolsUnreachable`]: dropping +/// it would leave her a head without verbs she was told she could call. +/// +/// [`InferenceError::TailToolsUnreachable`]: crate::ai::inference_error::InferenceError::TailToolsUnreachable pub(crate) fn finish_body( cfg: &OpenAICompatibleConfig, request: &TextGenerationRequest, model: &str, + tail_tools: bool, body: &mut Value, -) { +) -> Result<(), crate::ai::inference_error::InferenceError> { // Thinking suppression — the REAL lever for qwen3-family forged templates. // When this gateway suppresses reasoning, the adapter already appends the // `/no_think` soft-switch to the last user turn (build path above). But the @@ -189,9 +196,9 @@ pub(crate) fn finish_body( { body["tools"] = json!(openai_tools(tools)); if let Some(tail) = request.tail_tools.as_deref().filter(|tail| !tail.is_empty()) { - // Our fork's field: only a server that declares it gets it (a cloud provider + // Our fork's field: only an engine verified to take it gets it (a cloud provider // would reject an unknown field, a stock llama-server would ignore it). - if cfg.tail_tools { + if tail_tools { body["tail_tools"] = json!(openai_tools(tail)); } } @@ -229,7 +236,18 @@ pub(crate) fn finish_body( temperature = body.get("temperature").and_then(|t| t.as_f64()).unwrap_or(-1.0), "outbound chat request tool surface" ); - + let carried_tail = request.tail_tools.as_deref().is_some_and(|tail| !tail.is_empty()); + if carried_tail && body.get("tail_tools").is_none() { + // Every path that leaves a requested tail off the wire lands here: refused, never dropped. + continuum_base::probe!( + class = "ai.request.tail_tools_unreachable", + model = %model, + tail_tools_accepted = tail_tools, + "the request carries tail verbs its destination cannot take: refused for a rebuild" + ); + return Err(crate::ai::inference_error::InferenceError::TailToolsUnreachable { model: model.to_owned() }); + } + Ok(()) } // ── the head of assembly (carve 4): messages → base body ───────────────────────── @@ -691,8 +709,8 @@ mod tests { } // what this catches: a tail-loaded verb not reaching a llama.cpp-family server (she could - // read its schema and never call it), or the non-standard field going to a cloud provider - // that rejects unknown fields. + // read its schema and never call it), the non-standard field going to a cloud provider + // that rejects unknown fields, or a tail silently dropped (Codex on #5491). #[test] fn tail_tools_reach_only_a_llamacpp_family_server_and_never_join_the_head() { let spec = |name: &str| crate::ai::types::NativeToolSpec { @@ -728,11 +746,16 @@ mod tests { tail_tools: llamacpp, }; let mut served = json!({ "model": "m" }); - finish_body(&cfg(true), &request, "m", &mut served); + assert!(finish_body(&cfg(true), &request, "m", true, &mut served).is_ok()); assert_eq!(served["tools"].as_array().map(Vec::len), Some(1), "the head holds only its own verbs"); assert_eq!(served["tail_tools"][0]["function"]["name"], "code_git_apply"); + // A tail the destination cannot take is refused for a rebuild, never silently dropped. let mut cloud = json!({ "model": "m" }); - finish_body(&cfg(false), &request, "m", &mut cloud); - assert!(cloud.get("tail_tools").is_none(), "{cloud}"); + assert_eq!( + finish_body(&cfg(false), &request, "m", false, &mut cloud), + Err(crate::ai::inference_error::InferenceError::TailToolsUnreachable { model: "m".into() }) + ); + let headless = TextGenerationRequest { tail_tools: None, ..request.clone() }; + assert!(finish_body(&cfg(false), &headless, "m", false, &mut json!({ "model": "m" })).is_ok(), "no tail, nothing to refuse"); } } diff --git a/core/continuum-engine/src/inference/serving_guard.rs b/core/continuum-engine/src/inference/serving_guard.rs index c443860a1e..794d215426 100644 --- a/core/continuum-engine/src/inference/serving_guard.rs +++ b/core/continuum-engine/src/inference/serving_guard.rs @@ -274,7 +274,7 @@ pub(crate) async fn guard_resident_model( // the #106 sidecar lane beside a text-only mind. A request for the // sidecar's model is exactly as guaranteed as one for the active // model (the daemon verified its `/props` before publishing), and - // `endpoints_for_model` routes it to `vision_base_url`. + // `endpoints_for_model` (via `route_now`) routes it to `vision_base_url`. let mut snap = snap; if !snapshot_guarantees(&snap, model) && !settled_on_another_model(&snap) { // A TRANSITION, not a fault — wait it out instead of failing the turn. diff --git a/core/continuum-engine/src/model_registry/catalog/providers.rs b/core/continuum-engine/src/model_registry/catalog/providers.rs index ba015fba93..896d994f4c 100644 --- a/core/continuum-engine/src/model_registry/catalog/providers.rs +++ b/core/continuum-engine/src/model_registry/catalog/providers.rs @@ -230,9 +230,10 @@ pub fn providers() -> Vec { // 4B doesn't loop its `` block to the token budget // (same failure DMR hit; the in-process path defaults 1.1). llamacpp_sampling_extensions: true, - // `tail_tools` arrives with the fork pin that carries CambrianTech/llama.cpp#71; - // until then a mind's head stays her activity's static surface. - tail_tools: false, + // Our fork's gateway, whose pinned build takes `tail_tools` + // (CambrianTech/llama.cpp#75). The adapter offers it only while the running + // lane reports that build (`llama_server::serving_engine_takes_tail_tools`). + tail_tools: true, // Its served model ids match the registry rows (the forged // model now lives under this provider), so NO dynamic-catalog // name resolution — `dynamic_model_catalog` stays false and diff --git a/core/continuum-engine/src/model_registry/types.rs b/core/continuum-engine/src/model_registry/types.rs index 14fc858c7e..f6971542d5 100644 --- a/core/continuum-engine/src/model_registry/types.rs +++ b/core/continuum-engine/src/model_registry/types.rs @@ -259,10 +259,12 @@ pub struct ProviderCapabilities { /// `false`. #[serde(default)] pub llamacpp_sampling_extensions: bool, - /// The server accepts `tail_tools` (CambrianTech/llama.cpp#71): verbs callable through its - /// tool-call parser and grammar without rendering them in the head. A mind's learned tool - /// head (goal 10) is offered only where this holds, since a verb outside the head must stay - /// callable. Default: `false`. + /// The endpoint is our fork's server, whose pinned build accepts `tail_tools` + /// (CambrianTech/llama.cpp#75): verbs callable through its tool-call parser and grammar + /// without rendering them in the head. A declaration of the family only: the adapter offers a + /// mind's learned tool head (goal 10) while the RUNNING lane reports that build, since a verb + /// outside the head must stay callable. Cloud and stock servers leave it `false`. + /// Default: `false`. #[serde(default)] pub tail_tools: bool, } diff --git a/core/source-hygiene/src/vendor_pin.rs b/core/source-hygiene/src/vendor_pin.rs index b5326a0f0f..e930eb88ea 100644 --- a/core/source-hygiene/src/vendor_pin.rs +++ b/core/source-hygiene/src/vendor_pin.rs @@ -50,4 +50,23 @@ mod tests { in your worktree first — a stale worktree submodule staged with `git add -A` is how it regressed)." ); } + + // what this catches: the pin moving to an engine that no longer parses `tail_tools` while + // the core still offers a mind's learned tool head to every lane that reports the pinned + // build (`llama_server::engine_features`): her tail verbs would arrive as text, not calls. + #[test] + fn the_pinned_engine_source_parses_tail_tools() { + let parser = repo_root().join("core/vendor/llama.cpp/tools/server/server-common.cpp"); + let Ok(source) = std::fs::read_to_string(&parser) else { + eprintln!("{} not checked out — nothing to check", parser.display()); + return; + }; + assert!( + source.contains(r#"json_value(body, "tail_tools""#), + "the pinned llama.cpp ({}) does not parse `tail_tools`, but the core offers tail verbs to a \ + lane running exactly this build: move the pin to a fork commit that carries \ + CambrianTech/llama.cpp#75, or change `engine_features` in the same PR", + parser.display() + ); + } } diff --git a/core/vendor/LLAMA_CPP_PIN b/core/vendor/LLAMA_CPP_PIN index 8e89a77e6b..8620492124 100644 --- a/core/vendor/LLAMA_CPP_PIN +++ b/core/vendor/LLAMA_CPP_PIN @@ -1 +1 @@ -e7e1077b34144bba0c0bfb2f05af18653886279c +1c66815937abbc0839c5e41647b9fa2f6b6e62e3 diff --git a/core/vendor/llama.cpp b/core/vendor/llama.cpp index e7e1077b34..1c66815937 160000 --- a/core/vendor/llama.cpp +++ b/core/vendor/llama.cpp @@ -1 +1 @@ -Subproject commit e7e1077b34144bba0c0bfb2f05af18653886279c +Subproject commit 1c66815937abbc0839c5e41647b9fa2f6b6e62e3