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
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ impl LlmDeliberationFaculty {
let mut rejected_prompt_tokens = None;
let mut rejected_measured_tokens = None;
let mut request_template: Option<TextGenerationRequest> = 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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()));
}
Expand Down
7 changes: 4 additions & 3 deletions core/continuum-engine/src/ai/adapter/inference_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
12 changes: 12 additions & 0 deletions core/continuum-engine/src/ai/inference_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -93,6 +100,7 @@ impl InferenceError {
match self {
Self::ContextExceeded { .. } => false,
Self::Protocol(_) => false,
Self::TailToolsUnreachable { .. } => false,
Self::Unavailable(_) | Self::Transient(_) => true,
}
}
Expand Down Expand Up @@ -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"
),
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions core/continuum-engine/src/ai/openai_adapter/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 52 additions & 2 deletions core/continuum-engine/src/ai/openai_adapter/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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,
}
9 changes: 5 additions & 4 deletions core/continuum-engine/src/ai/openai_adapter/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,17 +358,18 @@ 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
// snapshot's VISION model (the #106 sidecar lane serving beside a
// 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
Expand Down
1 change: 1 addition & 0 deletions core/continuum-engine/src/ai/openai_adapter/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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");
}
Loading
Loading