From ff6cb3dcbfb48dc5df417837fd124bc1b77729ed Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Thu, 5 Nov 2026 20:42:48 +0100 Subject: [PATCH] STRA-338 S21: leleka-gateway-domain (layer L2): the pure gateway domain leaves strata-control New crate crates/gateway-domain, the first member of layer L2 in architecture.json (L2 is now a pure layer: tokio, axum, reqwest, libc and the other adapter crates are forbidden dependencies there). It depends on serde, serde_json, leleka-sampler-ref and leleka-tokenizer only. Moved out of control-plane/src with git mv, content unchanged apart from paths: sampling (request sampling extensions, validation) and EngineTune (was in wire.rs), reasoning_budget (the budget driver and its tests), codec (Family, TextCodec, TokenDecoder, QwenCodec), json_order, and the Chat Completions translation (chat_completions: Request -> Responses request, reply fields; the axum handlers stay in chat.rs). strata-control re-exports codec, json_order, reasoning_budget and sampling under their old paths, and wire.rs re-exports EngineTune, so no caller and no test outside the moved modules changed. 4 new tests cover the chat translation. Architecture gate: layer entry added; dyn-trait:leleka-gateway-domain = 5 appears because the five dyn in the moved code (Box, Box in the budget driver, &dyn Fn, ...) change crate; dyn-trait:strata-control fell 21 -> 16 in the same step, so the total is unchanged (--allow-increase was needed for the new per-crate key only). Test outcomes: 597 ok / 2 ignored before, 615 ok / 2 ignored after (18 new tests); the 13 moved tests keep their ids in the new crate and their outcome. --- Cargo.lock | 11 +++ Cargo.toml | 4 +- architecture-baseline.json | 3 +- architecture.json | 6 +- control-plane/Cargo.toml | 1 + control-plane/src/chat.rs | 84 +---------------- control-plane/src/lib.rs | 7 +- control-plane/src/wire.rs | 8 +- crates/gateway-domain/Cargo.toml | 18 ++++ crates/gateway-domain/src/chat_completions.rs | 92 +++++++++++++++++++ .../src/chat_completions/content.rs | 13 ++- .../src/chat_completions/request.rs | 31 +------ .../src/chat_completions/response.rs | 29 ++++++ .../src/chat_completions/tests.rs | 88 ++++++++++++++++++ .../gateway-domain}/src/codec.rs | 16 ++-- .../gateway-domain}/src/json_order.rs | 0 crates/gateway-domain/src/lib.rs | 18 ++++ .../gateway-domain}/src/reasoning_budget.rs | 0 .../src/reasoning_budget/budget_fn.rs | 0 .../src/reasoning_budget/run.rs | 0 .../src/reasoning_budget/tests.rs | 0 .../gateway-domain}/src/sampling.rs | 8 +- scripts/dev/test-outcomes.py | 9 +- 23 files changed, 299 insertions(+), 147 deletions(-) create mode 100644 crates/gateway-domain/Cargo.toml create mode 100644 crates/gateway-domain/src/chat_completions.rs rename control-plane/src/chat/invalid.rs => crates/gateway-domain/src/chat_completions/content.rs (88%) rename control-plane/src/chat/impl_request.rs => crates/gateway-domain/src/chat_completions/request.rs (86%) create mode 100644 crates/gateway-domain/src/chat_completions/response.rs create mode 100644 crates/gateway-domain/src/chat_completions/tests.rs rename {control-plane => crates/gateway-domain}/src/codec.rs (90%) rename {control-plane => crates/gateway-domain}/src/json_order.rs (100%) create mode 100644 crates/gateway-domain/src/lib.rs rename {control-plane => crates/gateway-domain}/src/reasoning_budget.rs (100%) rename {control-plane => crates/gateway-domain}/src/reasoning_budget/budget_fn.rs (100%) rename {control-plane => crates/gateway-domain}/src/reasoning_budget/run.rs (100%) rename {control-plane => crates/gateway-domain}/src/reasoning_budget/tests.rs (100%) rename {control-plane => crates/gateway-domain}/src/sampling.rs (95%) diff --git a/Cargo.lock b/Cargo.lock index 1a79b1ab..64a25511 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1320,6 +1320,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "leleka-gateway-domain" +version = "0.1.0" +dependencies = [ + "leleka-sampler-ref", + "leleka-tokenizer", + "serde", + "serde_json", +] + [[package]] name = "leleka-gateway-text" version = "0.1.0" @@ -2793,6 +2803,7 @@ dependencies = [ "http-body-util", "jsonschema", "leleka-backend-api", + "leleka-gateway-domain", "leleka-gateway-text", "leleka-gguf", "leleka-harmony", diff --git a/Cargo.toml b/Cargo.toml index da60bb41..0ce1bd40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"] -default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"] +members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"] +default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"] [workspace.package] edition = "2024" diff --git a/architecture-baseline.json b/architecture-baseline.json index 08ad8406..901b8e95 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -133,6 +133,7 @@ "dyn-trait:leleka-cuda-driver": 51, "dyn-trait:leleka-deploy": 17, "dyn-trait:leleka-experimental-ref": 3, + "dyn-trait:leleka-gateway-domain": 5, "dyn-trait:leleka-gptoss": 10, "dyn-trait:leleka-gptoss-igpu": 4, "dyn-trait:leleka-gptoss-npu": 4, @@ -141,7 +142,7 @@ "dyn-trait:leleka-model-format": 8, "dyn-trait:leleka-runtime": 70, "dyn-trait:leleka-tokenizer": 2, - "dyn-trait:strata-control": 21, + "dyn-trait:strata-control": 16, "dyn-trait:strata-desktop-core": 2, "env-read:leleka-cpu-kernels": 1, "env-read:leleka-cpu-worker": 2, diff --git a/architecture.json b/architecture.json index 26d1e873..6cb2aa5c 100644 --- a/architecture.json +++ b/architecture.json @@ -1,8 +1,8 @@ { - "_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) is reserved: it is empty until the engine/gateway domain crates are extracted (steps S19, S21). Every workspace package appears in exactly one layer.", + "_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) holds the extracted domain crates: leleka-gateway-domain (S21); the engine domain crates follow (S19). Every workspace package appears in exactly one layer.", "max_lines": 400, "adapter_layer": "L3", - "pure_layers": ["L0", "L1"], + "pure_layers": ["L0", "L1", "L2"], "forbidden_in_pure": ["tokio", "axum", "tonic", "tonic-prost", "reqwest", "hyper", "libc", "rustix", "windows-sys", "sysinfo", "wgpu"], "layers": { "L0": ["leleka-backend-api", "leleka-worker-protocol"], @@ -11,7 +11,7 @@ "leleka-tokenizer", "leleka-gguf", "leleka-kar-codec", "leleka-experimental-ref", "leleka-cpu-sys", "leleka-cpu-kernels", "leleka-shm", "leleka-openvino", "leleka-memory", "leleka-gateway-text" ], - "L2": [], + "L2": ["leleka-gateway-domain"], "L3": [ "leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu", "leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker", diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index e3ee6a0a..71b9ef3e 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -15,6 +15,7 @@ axum = "0.8" futures-core = "0.3" hex = "0.4" leleka-gguf = { path = "../crates/gguf" } +leleka-gateway-domain = { path = "../crates/gateway-domain" } leleka-gateway-text = { path = "../crates/gateway-text" } leleka-worker-protocol = { path = "../crates/worker-protocol" } leleka-obs = { path = "../crates/obs" } diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs index 4f49ca08..85a4009a 100644 --- a/control-plane/src/chat.rs +++ b/control-plane/src/chat.rs @@ -8,7 +8,6 @@ use axum::{ response::{IntoResponse, Response, Sse, sse::Event}, }; use futures_core::Stream; -use serde::Deserialize; use serde_json::{Value, json}; use std::{ convert::Infallible, @@ -18,91 +17,10 @@ use std::{ use tokio::sync::mpsc; use crate::native_events::{MAX_EVENT, NativeEvents}; - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Request { - model: String, - messages: Vec, - #[serde(default)] - stream: bool, - stream_options: Option, - n: Option, - max_tokens: Option, - max_completion_tokens: Option, - temperature: Option, - top_p: Option, - #[serde(default)] - tools: Vec, - tool_choice: Option, - parallel_tool_calls: Option, - response_format: Option, - reasoning_effort: Option, - store: Option, - stop: Option, - logprobs: Option, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct StreamOptions { - include_usage: Option, - include_obfuscation: Option, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Message { - role: String, - content: Option, - tool_calls: Option>, - tool_call_id: Option, - refusal: Option, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Call { - id: String, - #[serde(rename = "type")] - kind: String, - function: CallFunction, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct CallFunction { - name: String, - arguments: String, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Tool { - #[serde(rename = "type")] - kind: String, - function: Function, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Function { - name: String, - description: Option, - parameters: Option, - strict: Option, -} - -type Invalid = (&'static str, &'static str); -/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses -/// shape (`input_text` / `input_image`), whose order the template keeps. -enum Content { - Text(String), - Parts(Vec), -} +use leleka_gateway_domain::chat_completions::{Request, call, finish, identity, usage}; struct Events(mpsc::Receiver); -mod invalid; -#[allow(unused_imports)] -pub use invalid::*; -mod impl_request; -#[allow(unused_imports)] -pub use impl_request::*; mod completion; #[allow(unused_imports)] pub use completion::*; diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index f6b0f0cd..811dc343 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -25,12 +25,13 @@ macro_rules! wlog { /// The boxed error the command-line and offline-tool functions return. pub type BoxError = Box; +pub use leleka_gateway_domain::{codec, json_order, reasoning_budget, sampling}; + pub mod adapters; pub mod app; pub mod asset_bundle; pub mod auth; pub mod backend_worker; -pub mod codec; pub mod config; pub mod derived_iq3; pub mod derived_mixed; @@ -48,7 +49,6 @@ mod history_store; mod immutable_directory; pub use leleka_quant_core::iq3_s; pub mod hardware_view; -pub mod json_order; pub mod kar; pub mod kar_codec; pub mod kar_fixture; @@ -104,8 +104,6 @@ pub mod service_switch; pub mod queue; pub mod request_log; -pub mod sampling; - pub mod server_api; pub mod stage_trace; @@ -113,5 +111,4 @@ pub mod stage_trace; pub mod settings; pub mod mcp; -pub mod reasoning_budget; pub mod vision; diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index ea158584..d834e215 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -2,13 +2,7 @@ use leleka_sampler_ref::RequestSampling; -/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of -/// missed experts and the draft-probability floor, both in `0..=1`. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct EngineTune { - pub pcie_frac: Option, - pub spec_min_p: Option, -} +pub use leleka_gateway_domain::EngineTune; /// Reasoning-budget wrap-up (`reasoning_budget_tokens`, issue #123 of the Original): once the model /// has thought for `budget` tokens, at a clean point the worker stops the pass, appends `wrap_up` diff --git a/crates/gateway-domain/Cargo.toml b/crates/gateway-domain/Cargo.toml new file mode 100644 index 00000000..13ce2508 --- /dev/null +++ b/crates/gateway-domain/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "leleka-gateway-domain" +version = "0.1.0" +description = "Pure domain of the HTTP/Responses gateway: request sampling, reasoning budget, model-family codec, JSON ordering. No async runtime, no HTTP, no OS." +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[dependencies] +leleka-sampler-ref = { path = "../sampler-ref" } +leleka-tokenizer = { path = "../tokenizer" } +serde = { version = "1", features = ["derive"] } +# `preserve_order` and `float_roundtrip` as in leleka-gateway-text and strata-control: tool-call arguments and schemas keep +# the order the client wrote them (json_order.rs builds the sorted forms explicitly). +serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] } + +[lints] +workspace = true diff --git a/crates/gateway-domain/src/chat_completions.rs b/crates/gateway-domain/src/chat_completions.rs new file mode 100644 index 00000000..30dbda04 --- /dev/null +++ b/crates/gateway-domain/src/chat_completions.rs @@ -0,0 +1,92 @@ +//! Chat Completions requests as Responses requests (STRA-338 S21): the wire types, the translation, and the response fields a +//! chat reply takes from the native Responses object. Pure JSON in, JSON out; the HTTP adapter is `strata-control`'s `chat`. + +use serde::Deserialize; +use serde_json::{Value, json}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + model: String, + messages: Vec, + #[serde(default)] + stream: bool, + stream_options: Option, + n: Option, + max_tokens: Option, + max_completion_tokens: Option, + temperature: Option, + top_p: Option, + #[serde(default)] + tools: Vec, + tool_choice: Option, + parallel_tool_calls: Option, + response_format: Option, + reasoning_effort: Option, + store: Option, + stop: Option, + logprobs: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StreamOptions { + include_usage: Option, + include_obfuscation: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Message { + role: String, + content: Option, + tool_calls: Option>, + tool_call_id: Option, + refusal: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Call { + id: String, + #[serde(rename = "type")] + kind: String, + function: CallFunction, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CallFunction { + name: String, + arguments: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Tool { + #[serde(rename = "type")] + kind: String, + function: Function, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Function { + name: String, + description: Option, + parameters: Option, + strict: Option, +} + +pub type Invalid = (&'static str, &'static str); +/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses +/// shape (`input_text` / `input_image`), whose order the template keeps. +pub enum Content { + Text(String), + Parts(Vec), +} + +mod content; +mod request; +mod response; + +use content::*; + +pub use response::{call, finish, identity, usage}; + +#[cfg(test)] +mod tests; diff --git a/control-plane/src/chat/invalid.rs b/crates/gateway-domain/src/chat_completions/content.rs similarity index 88% rename from control-plane/src/chat/invalid.rs rename to crates/gateway-domain/src/chat_completions/content.rs index d9e33227..a85e8a7c 100644 --- a/control-plane/src/chat/invalid.rs +++ b/crates/gateway-domain/src/chat_completions/content.rs @@ -1,21 +1,20 @@ -//! Moved out of the parent module by STRA-338: fn invalid, impl Content, fn image_part, fn content. +//! Message content and picture parts of a chat request. -#[allow(unused_imports)] use super::*; -pub(super) fn invalid(param: &'static str, message: &'static str) -> Invalid { +pub(crate) fn invalid(param: &'static str, message: &'static str) -> Invalid { (param, message) } impl Content { - pub(super) fn text(self) -> Option { + pub(crate) fn text(self) -> Option { match self { Self::Text(text) => Some(text), Self::Parts(_) => None, } } - pub(super) fn into_value(self) -> Value { + pub(crate) fn into_value(self) -> Value { match self { Self::Text(text) => Value::String(text), Self::Parts(parts) => Value::Array(parts), @@ -25,7 +24,7 @@ impl Content { /// An `image_url` part (`serve/frontend.py` `_image_source`): `"image_url": {"url": ..., "detail": ...}` or the bare /// string. The source itself is checked when it is read, so an empty one fails there with the Python server's words. -pub(super) fn image_part(part: &serde_json::Map) -> Result { +pub(crate) fn image_part(part: &serde_json::Map) -> Result { let bad = || { invalid( "messages", @@ -59,7 +58,7 @@ pub(super) fn image_part(part: &serde_json::Map) -> Result, role: &str) -> Result, Invalid> { +pub(crate) fn content(value: Option, role: &str) -> Result, Invalid> { match value { None | Some(Value::Null) => Ok(None), Some(Value::String(s)) => Ok(Some(Content::Text(s))), diff --git a/control-plane/src/chat/impl_request.rs b/crates/gateway-domain/src/chat_completions/request.rs similarity index 86% rename from control-plane/src/chat/impl_request.rs rename to crates/gateway-domain/src/chat_completions/request.rs index 1b3c2a29..9b3cc876 100644 --- a/control-plane/src/chat/impl_request.rs +++ b/crates/gateway-domain/src/chat_completions/request.rs @@ -1,10 +1,9 @@ -//! Moved out of the parent module by STRA-338: impl Request, fn usage, fn call, fn finish, fn identity. +//! `Request::into_responses`: the checks of the supported Chat subset and the native request it becomes. -#[allow(unused_imports)] use super::*; impl Request { - pub(super) fn into_responses(self) -> Result<(Value, bool, bool), Invalid> { + pub fn into_responses(self) -> Result<(Value, bool, bool), Invalid> { if self.n.is_some_and(|n| n != 1) { return Err(invalid("n", "only n=1 is supported")); } @@ -199,29 +198,3 @@ impl Request { Ok((request, self.stream, include_usage)) } } - -pub(super) fn usage(response: &Value) -> Value { - let u = &response["usage"]; - json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"], - "prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]}, - "completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}}) -} -pub(super) fn call(item: &Value) -> Value { - json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}}) -} -pub(super) fn finish(response: &Value) -> &'static str { - if response["status"] == "incomplete" { - "length" - } else if response["output"] - .as_array() - .is_some_and(|items| items.iter().any(|i| i["type"] == "function_call")) - { - "tool_calls" - } else { - "stop" - } -} -pub(super) fn identity(response: &Value, object: &str) -> Value { - json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object, - "created":response["created_at"],"model":response["model"]}) -} diff --git a/crates/gateway-domain/src/chat_completions/response.rs b/crates/gateway-domain/src/chat_completions/response.rs new file mode 100644 index 00000000..875aa8fa --- /dev/null +++ b/crates/gateway-domain/src/chat_completions/response.rs @@ -0,0 +1,29 @@ +//! The fields of a chat reply that come from the native Responses object. + +use serde_json::{Value, json}; + +pub fn usage(response: &Value) -> Value { + let u = &response["usage"]; + json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"], + "prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]}, + "completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}}) +} +pub fn call(item: &Value) -> Value { + json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}}) +} +pub fn finish(response: &Value) -> &'static str { + if response["status"] == "incomplete" { + "length" + } else if response["output"] + .as_array() + .is_some_and(|items| items.iter().any(|i| i["type"] == "function_call")) + { + "tool_calls" + } else { + "stop" + } +} +pub fn identity(response: &Value, object: &str) -> Value { + json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object, + "created":response["created_at"],"model":response["model"]}) +} diff --git a/crates/gateway-domain/src/chat_completions/tests.rs b/crates/gateway-domain/src/chat_completions/tests.rs new file mode 100644 index 00000000..16e79008 --- /dev/null +++ b/crates/gateway-domain/src/chat_completions/tests.rs @@ -0,0 +1,88 @@ +//! Tests of the Chat Completions to Responses translation (new in STRA-338 S21; the HTTP behaviour is covered by the +//! gateway's own tests). + +use super::*; + +fn translate(body: Value) -> Result<(Value, bool, bool), Invalid> { + serde_json::from_value::(body) + .expect("a well-formed chat request") + .into_responses() +} + +#[test] +fn a_plain_chat_becomes_a_stateless_responses_request_without_reasoning() { + let (request, stream, usage) = translate(json!({ + "model": "m", + "messages": [{"role": "system", "content": "be brief"}, {"role": "user", "content": "hi"}], + "max_tokens": 7, "temperature": 0.5 + })) + .unwrap(); + assert_eq!((stream, usage), (false, false)); + assert_eq!(request["store"], false); + assert_eq!(request["reasoning"]["effort"], "none"); + assert_eq!(request["max_output_tokens"], 7); + assert_eq!( + request["input"][1], + json!({"role": "user", "content": "hi"}) + ); +} + +#[test] +fn tool_calls_and_results_become_function_items() { + let (request, ..) = translate(json!({ + "model": "m", + "messages": [ + {"role": "user", "content": "weather?"}, + {"role": "assistant", "tool_calls": [{"id": "c1", "type": "function", + "function": {"name": "lookup", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "3C"} + ], + "tools": [{"type": "function", "function": {"name": "lookup", "description": "d"}}] + })) + .unwrap(); + assert_eq!(request["input"][1]["type"], "function_call"); + assert_eq!( + request["input"][2], + json!({"type": "function_call_output", "call_id": "c1", "output": "3C"}) + ); + assert_eq!(request["tools"][0]["name"], "lookup"); + assert_eq!(request["tools"][0]["description"], "d"); +} + +#[test] +fn unsupported_features_name_the_parameter() { + for (extra, param) in [ + (json!({"n": 2}), "n"), + (json!({"logprobs": true}), "logprobs"), + (json!({"stop": ["x"]}), "stop"), + (json!({"reasoning_effort": "high"}), "reasoning_effort"), + ( + json!({"stream_options": {"include_usage": true}}), + "stream_options", + ), + ] { + let mut body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]}); + body.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + assert_eq!(translate(body).unwrap_err().0, param); + } +} + +#[test] +fn reply_fields_come_from_the_native_response() { + let response = json!({"id": "resp_1", "created_at": 5, "model": "m", "status": "incomplete", + "output": [], "usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}}); + assert_eq!(finish(&response), "length"); + assert_eq!( + identity(&response, "chat.completion")["id"], + "chatcmpl-resp_1" + ); + assert_eq!(usage(&response)["total_tokens"], 7); + let calling = json!({"status": "completed", "output": [{"type": "function_call"}]}); + assert_eq!(finish(&calling), "tool_calls"); + assert_eq!( + call(&json!({"call_id": "c", "name": "n", "arguments": "{}"}))["id"], + "c" + ); +} diff --git a/control-plane/src/codec.rs b/crates/gateway-domain/src/codec.rs similarity index 90% rename from control-plane/src/codec.rs rename to crates/gateway-domain/src/codec.rs index 1b602bed..f15fd174 100644 --- a/control-plane/src/codec.rs +++ b/crates/gateway-domain/src/codec.rs @@ -41,7 +41,7 @@ pub trait TextCodec: Send + Sync { } /// The Qwen tokenizer behind this codec, for what only that family has (control-token marks, pictures, the /// reasoning budget, the runtime backend); `None` for the other families. - fn qwen(&self) -> Option<&Arc> { + fn qwen(&self) -> Option<&Arc> { None } } @@ -58,7 +58,7 @@ pub fn decode_all(codec: &dyn TextCodec, ids: &[u32]) -> Result, String> } /// Qwen3.5 decodes token by token with no state. -struct QwenDecoder(Arc); +struct QwenDecoder(Arc); impl TokenDecoder for QwenDecoder { fn push(&mut self, id: u32) -> Result, String> { @@ -71,16 +71,16 @@ impl TokenDecoder for QwenDecoder { } /// The Qwen tokenizer as a codec; hold it in an `Arc` and call [`qwen_codec`]. -pub struct QwenCodec(Arc); +pub struct QwenCodec(Arc); -pub fn qwen_codec(tokenizer: crate::tokenizer::Tokenizer) -> QwenCodec { +pub fn qwen_codec(tokenizer: leleka_tokenizer::Tokenizer) -> QwenCodec { QwenCodec(Arc::new(tokenizer)) } /// The codec is the tokenizer plus the family's grammar; the Qwen-only code (control-token marks, pictures) reaches the /// tokenizer through it. impl std::ops::Deref for QwenCodec { - type Target = crate::tokenizer::Tokenizer; + type Target = leleka_tokenizer::Tokenizer; fn deref(&self) -> &Self::Target { &self.0 @@ -88,7 +88,7 @@ impl std::ops::Deref for QwenCodec { } /// The codec over a tokenizer that is shared with other code (the runtime backend counts with the same one). -pub fn qwen_codec_shared(tokenizer: Arc) -> QwenCodec { +pub fn qwen_codec_shared(tokenizer: Arc) -> QwenCodec { QwenCodec(tokenizer) } @@ -115,12 +115,12 @@ impl TextCodec for QwenCodec { } /// Control-token text inside the messages is marked by the renderer and encoded as ordinary text - /// ([`crate::tokenizer::Tokenizer::encode_marked`]). + /// ([`leleka_tokenizer::Tokenizer::encode_marked`]). fn encode_prompt(&self, prompt: &str) -> Result, String> { self.0.encode_marked(prompt).map_err(|e| e.to_string()) } - fn qwen(&self) -> Option<&Arc> { + fn qwen(&self) -> Option<&Arc> { Some(&self.0) } diff --git a/control-plane/src/json_order.rs b/crates/gateway-domain/src/json_order.rs similarity index 100% rename from control-plane/src/json_order.rs rename to crates/gateway-domain/src/json_order.rs diff --git a/crates/gateway-domain/src/lib.rs b/crates/gateway-domain/src/lib.rs new file mode 100644 index 00000000..faa41285 --- /dev/null +++ b/crates/gateway-domain/src/lib.rs @@ -0,0 +1,18 @@ +//! Pure domain of the HTTP/Responses gateway (`strata-control`), layer L2 of `architecture.json`. +//! +//! * `sampling`: the sampling extensions a client may send and their validation, `EngineTune`. +//! * `reasoning_budget`: the thinking budget driver (generic over the engine and the tokenizer). +//! * `codec`: the model family (`TextCodec`, `Family`, `TokenDecoder`) as the Responses code sees it. +//! * `chat_completions`: a Chat Completions request as a Responses request, and the chat reply fields. +//! * `json_order`: tool results and schemas in the order the client wrote them, or sorted where wanted. +//! +//! Nothing here starts a thread, opens a socket or reads the environment, so the gateway rules can be tested without +//! tokio, axum or an engine. The HTTP layer, the ports and their adapters stay in `strata-control`. + +pub mod chat_completions; +pub mod codec; +pub mod json_order; +pub mod reasoning_budget; +pub mod sampling; + +pub use sampling::EngineTune; diff --git a/control-plane/src/reasoning_budget.rs b/crates/gateway-domain/src/reasoning_budget.rs similarity index 100% rename from control-plane/src/reasoning_budget.rs rename to crates/gateway-domain/src/reasoning_budget.rs diff --git a/control-plane/src/reasoning_budget/budget_fn.rs b/crates/gateway-domain/src/reasoning_budget/budget_fn.rs similarity index 100% rename from control-plane/src/reasoning_budget/budget_fn.rs rename to crates/gateway-domain/src/reasoning_budget/budget_fn.rs diff --git a/control-plane/src/reasoning_budget/run.rs b/crates/gateway-domain/src/reasoning_budget/run.rs similarity index 100% rename from control-plane/src/reasoning_budget/run.rs rename to crates/gateway-domain/src/reasoning_budget/run.rs diff --git a/control-plane/src/reasoning_budget/tests.rs b/crates/gateway-domain/src/reasoning_budget/tests.rs similarity index 100% rename from control-plane/src/reasoning_budget/tests.rs rename to crates/gateway-domain/src/reasoning_budget/tests.rs diff --git a/control-plane/src/sampling.rs b/crates/gateway-domain/src/sampling.rs similarity index 95% rename from control-plane/src/sampling.rs rename to crates/gateway-domain/src/sampling.rs index 546f692e..c79ee7c1 100644 --- a/control-plane/src/sampling.rs +++ b/crates/gateway-domain/src/sampling.rs @@ -12,7 +12,13 @@ use leleka_sampler_ref::RequestSampling; use serde::Deserialize; use serde_json::{Map, Value}; -use crate::wire::EngineTune; +/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of +/// missed experts and the draft-probability floor, both in `0..=1`. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct EngineTune { + pub pcie_frac: Option, + pub spec_min_p: Option, +} /// Top-level body keys that the Chat and Messages adapters pass through to the native request /// unchanged. Removed before their own `deny_unknown_fields` parse. diff --git a/scripts/dev/test-outcomes.py b/scripts/dev/test-outcomes.py index 9ddf048e..fdd70419 100644 --- a/scripts/dev/test-outcomes.py +++ b/scripts/dev/test-outcomes.py @@ -68,11 +68,18 @@ def main(argv): moved.append((key, new_same[0])) only_before.remove(key) only_after.remove(new_same[0]) + # A test that moved to another crate keeps its full module path: pair those when unique too. + for key in list(only_before): + same = [k for k in only_after if k[1] == key[1]] + if len([k for k in only_before if k[1] == key[1]]) == 1 and len(same) == 1: + moved.append((key, same[0])) + only_before.remove(key) + only_after.remove(same[0]) for old_key, new_key in moved: if before[old_key] != after[new_key]: changed.append((old_key, before[old_key], after[new_key])) else: - print(f"MOVED {old_key[0]} :: {old_key[1]} -> {new_key[1]} ({after[new_key]})") + print(f"MOVED {old_key[0]} :: {old_key[1]} -> {new_key[0]} :: {new_key[1]} ({after[new_key]})") for key, was, now in changed: print(f"CHANGED {key[0]} :: {key[1]}: {was} -> {now}") for key in only_before: