RuntimeServer and the engine Proxy remembered every accepted request id for the life of an epoch and refused work after 256 (generation_capacity), which an agent session exhausts quickly. Both now use leleka_backend_api::RecentIds (16384 most recent ids, FIFO). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
14 KiB
One API in front of the Rust engine: options and decision
Status 2026-10-16, branch claude/api-over-rust-engine (base claude/m2-control-plane). Design note for the finding in
delivery-gap-audit.md section 0.1 ("two serving stacks"). No GPU, model or engine run is involved in
anything written here; nothing is a performance or quality claim.
The two stacks today
strata-next (control-plane/) |
leleka-daemon (desktop-core/src/runtime_gateway.rs) |
|
|---|---|---|
| API surface | Responses (JSON+SSE, stored, previous_response_id, input_tokens), Chat Completions, Messages, tools (function, custom, regex), text.format, reasoning, MCP hub, drain, history, metrics |
Responses text subset; Codex-shaped bodies get 400; max_output_tokens <= 4096; tools off by default |
| Engine link | child process, stdio lines GEN <ids> / T <id> / DONE (wire.rs, worker.rs) |
gRPC leleka.runtime.v1 (runtime.proto) to leleka-inference |
| Unit of exchange with the engine | token ids in, token ids out | text prompt in (GenerateRequest.prompt), text deltas out (TextDelta) |
| Where the chat template is rendered | strata-next (minijinja, prompt.rs) |
the daemon (a path-included copy of prompt.rs) |
| Where text is tokenized | strata-next (leleka-tokenizer, encode(prompt, parse_special=true)) |
the engine (backend.rs prepare_prompt: encode(prompt, true), same crate) |
| Where output is detokenized | strata-next (decode_bytes per token, incremental UTF-8) |
the engine (TextDelta, UTF-8 safe) |
| Stop handling | engine emits the stop token; strata-next treats `< |
im_end |
| Tool-call parsing | strata-next from decoded text (tool_output.rs, incremental) |
the daemon adapter, from text (runtime_tools.rs); ToolCallDelta is unused by the engine (supports_tool_call_streaming false) |
| Reasoning budget, images | token-level wrap-up (worker.rs), GENI embeddings |
absent |
The engine contract (crates/backend-api, version 2) is therefore text-level: one prompt string, TextDelta strings,
a terminal with usage and a finish reason (Stop/Length/ToolCalls), cancel(request_id), and a model handle plus epoch.
Options
A. A runtime backend for strata-next (the whole existing API in front of the Rust engine)
Add a second implementation of the worker seam of strata-next (the GenerationCommand channel plus WorkerStatus/Control,
today fed only by the stdio supervisor worker::run_supervised). It drives any leleka_backend_api::Backend; the production
Backend is a gRPC client of leleka-inference (leleka-runtime-client, extracted from desktop-core so both binaries share
one proto and one frame validator), and tests drive an in-process scripted engine implementing the same trait.
- Protocol correctness: all of
responses.rs/chat.rs/messages.rsand their ~600 unit tests, fixtures and smokes stay the single implementation. The new code is only the engine edge: request mapping, event mapping, terminal guarantees. - Token-level semantics: the HTTP layer needs token ids (context accounting, reasoning budget, usage) and the engine speaks text, so the edge must convert both ways (section "Token-level edge" below). This is the one real cost of A.
- Risk: the engine edge becomes the place where subtle divergence can hide (double tokenization, stop markers, finish reasons). It is small (hundreds of lines) and testable without a GPU.
B. Extend leleka-daemon with the missing API surface
Grow runtime_gateway.rs until it accepts Codex bodies, stores responses, serves Chat/Messages, tools, text.format.
- Protocol correctness: a second implementation of ~10k lines of wire behaviour. The daemon already path-includes three
control-planesource files (prompt.rs,response_tools.rs,tool_output.rs) which is a fragile form of sharing: every change of those files recompiles inside two crates with different feature sets. Every API fix must be made and tested twice, and Gate A (100% terminal events, tool arguments intact, schema validation) would need the whole fixture set ported. - Token-level semantics: natural (text in, text out, same as the engine) but the daemon has no token ids at all, so context
accounting,
input_tokens, reasoning budgets would need a tokenizer added there anyway. - Upside: keeps
leleka-daemon's lifecycle/epoch/operation semantics and one fewer hop.
C. A shared API crate used by both binaries
Extract the Responses/Chat/Messages implementation into a library with an Engine trait, link it into strata-next and
leleka-daemon.
- Cleanest end state; also the largest blast radius:
responses.rsis 5.7k lines wired into axum state,WorkerStatus, lifecycle, history and settings. Not achievable as a reviewable slice, and it would be designed against two engine edges that do not exist yet in one place. - It is where A leads: A introduces exactly the seam C needs (the engine edge behind one trait) while keeping everything green.
Decision: A, with C as the direction
Reasons:
- It is the only option that gives Codex the complete, already-tested native API on top of the Rust engine without rewriting it and without a compatibility bridge or Python.
- All existing
strata-nexttests stay valid by construction: the stdio worker is untouched, and the new worker is selected by an explicit configuration block (runtime), mutually exclusive withengine.executable. - The engine contract stays the engine's:
crates/backend-apiandleleka-runtime/src/backend*.rsare not modified. The things the contract cannot express are refused or documented, not papered over (below). - Lifecycle stays with the operator tooling: the new worker attaches to an already loaded runtime (snapshot, epoch, handle)
and never issues
Load/Unload, so a 55 GB sealed-archive start is never a side effect of an HTTP request. It follows the runtime across engine restarts (new epoch, model not ready) and reportsnot readymeanwhile.
leleka-daemon remains the lifecycle gateway (/runtime/load|unload|operation, nodes, tunnels) until its remaining roles
move into strata-next; it is not extended with API surface.
Token-level edge (the part that needs care)
Prompt direction. strata-next renders the chat template and encodes the whole prompt with parse_special=true; the engine
encodes the prompt string again with parse_special=true using the same leleka-tokenizer crate. The worker therefore
decodes the ids back to text and verifies encode(decode(ids), true) == ids before sending. A prompt that does not survive
the round trip (for example ids that are not the canonical encoding of any text, or an image-expanded prompt) fails the request
instead of being served with different tokens than the ones that were counted. Both sides must also use the same tokenizer
assets; the contract carries no tokenizer fingerprint (open item).
Output direction. The engine returns text deltas; the HTTP layer consumes Event::Token(id). The worker re-encodes each delta with
encode(text, parse_special=false) and checks that decoding gives back exactly the same bytes, so every byte that reaches the
client is a byte the engine produced. The ids themselves are not the engine's sampled ids: token counts in usage come from the
engine's terminal usage (output_tokens), not from the re-encoding; reasoning_tokens in usage details is approximate for
the same reason. Passing the engine's ids in TextDelta (additive field) is the contract change that removes this
approximation; it is listed as a follow-up, not done here.
Stop handling. The engine stops at its eos id. strata-next additionally ends the text at <|im_end|> or <|endoftext|>.
The worker scans the delta stream for those two literals (holding back a possible partial prefix across deltas), truncates the
text, cancels the engine generation and reports stop. Consequence: a model that spells one of those literals with ordinary
byte tokens is cut as well (the engine contract gives no way to tell the special token from its spelling).
Finish reasons. Stop -> stop, Length -> length, ToolCalls -> stop (tool calls are parsed by strata-next from the
text; an engine ToolCallDelta while supports_tool_call_streaming is false is a protocol violation and fails the request),
Cancelled after a client disconnect -> cancel, Failed -> error, a stream that ends without a terminal event -> failure and
the worker leaves ready until the runtime is attached again. SSE termination is guaranteed by the HTTP layer, which already
ends every stream with response.failed when the worker side closes without a Done.
Not expressible over the text contract, refused (fail closed, with an explicit message, never silently dropped): image input
(GENI embeddings), reasoning_budget_tokens wrap-up (needs prompt + generated ids continuation), strata_tune,
experimental_speed_projection, and sampling values that are not exact thousandths/millionths (same rule as the daemon).
What the slice delivers and what it does not
Delivered (branch claude/api-over-rust-engine)
| piece | where |
|---|---|
worker for a text-level engine, selected by the runtime config block; same GenerationCommand channel, WorkerStatus and Control as the stdio supervisor |
control-plane/src/backend_worker.rs, runtime_config.rs, main.rs (serve) |
Backend over the real gRPC contract that attaches to a loaded runtime (no Load/Unload RPC), re-reads epoch and handle before every generation |
crates/runtime-client (GrpcBackend); the proto, conversions and validated client moved here from desktop-core, which re-exports them unchanged |
in-process scripted engine implementing the same Backend trait (feature scripted) |
crates/backend-api/src/scripted.rs |
| literal stop markers across deltas | crates/serving-policy/src/stop.rs |
harmless Codex hints accepted (service_tier, user, text.verbosity, reasoning.effort: minimal, summary: none) |
control-plane/src/responses.rs |
a test-only fake leleka-inference over the real RuntimeServer, driven by the existing scripted engine.sh programs |
desktop-core/examples/fake_runtime.rs, scripts/test-api-over-runtime.py, fixture.runtime_stack() in scripts/smoke-worker-cancel.py |
Tests (no GPU, no model; commands run from the repository root)
| layer | command | what it covers |
|---|---|---|
| API + worker over the scripted engine, real HTTP/SSE | cargo test -p strata-control --test backend_worker_http (27) |
Responses JSON/SSE, Chat, tools (function and custom), text.format valid/invalid, finish reasons, stop literals, client disconnect, generation deadline, wedged engine, dying engine, native tool-call delta, refused features, output cap, sampling fixed point, token counting, Codex-shaped two-turn exchange with stateless replay, tool_choice / parallel_tool_calls |
GrpcBackend over loopback HTTP/2 |
cargo test -p leleka-runtime-client (11) |
attach checks, no Load RPC, frame mapping, missing terminal, drop/cancel, stale epoch, unreachable runtime |
whole chain: router -> worker -> GrpcBackend -> gRPC -> real RuntimeServer -> scripted engine |
cargo test -p strata-desktop-core --test api_over_runtime (6) |
streaming, finish reasons, tool call, stop marker, disconnect through gRPC, failure and engine death, runtime restart and re-attach, the 256-generation limit |
| existing HTTP smokes, unchanged assertions, engine moved behind the runtime | python3 scripts/test-api-over-runtime.py target/debug/strata-next target/debug/examples/fake_runtime (10 scripts) |
replay driver and corrupted-stream rejection, custom tools, Chat, Messages, 216 tool-policy cases, input tokens, stored responses across a restart, keep-alive, drain, queue deadline |
The ten scripts are the ones whose assertions do not depend on strata-next owning the engine process. Not moved:
smoke-worker-cancel.py (a wedged engine ends the stdio supervisor; the runtime backend re-attaches instead),
smoke-signal-drain.py (expects QUIT on the engine's stdin) and smoke-generation-deadline.py (the deadline is a
runtime.generation_timeout_s here, covered by backend_worker_http).
Not covered / known gaps
- No real engine ran. Nothing here loads a model or touches CUDA. Tokenizer agreement between
strata-next's assets and the engine's GGUF tokenizer is checked per request (prompt round trip) and by the input-token counter comparison (the engine counted N input tokens, the control plane Mon stderr), but never against the real vocabulary. - Output budget.
RuntimeServer::generaterefusesmax_output_tokens > 4096; the worker carries that cap (runtime.max_output_tokens), clamps default budgets to it and refuses larger explicit ones. Codex's 32768 default is therefore not reachable until the runtime's cap is raised (its value belongs to the engine owner). - Generation identity ledger. Found by the e2e run:
RuntimeServer(MAX_IDS) and the engine backend (seen) used to remember every accepted request id for the whole epoch and refused new work after 256 (generation_capacity). Both now hold a bounded window (leleka_backend_api::RecentIds, 16384 most recent ids, oldest forgotten first), so an agent session no longer ends the runtime; a repeat of a recent id is still refused (api_over_runtime::serves_more_than_256_generations_in_one_runtime_epoch). - Token ids.
usage.output_tokensis the engine's;reasoning_tokensis derived from re-tokenized text, approximate, and clamped to the engine total. Reasoning-budget wrap-up, images,strata_tuneand control vectors are refused (fail closed). - No prefix reuse and no prefill progress. The runtime resets to position 0 per request (
original-serve.md), and the text contract has no progress events, so the stall watchdog is off by default;: keep-alivecomments still flow. - Sampling precision is refused at generation time (502), not at admission (400), for values that are not exact thousandths/millionths.
- Lifecycle stays with the operator:
/unloadreportsunsupportedand/loadis a no-op while attached; the runtime must already be loaded (leleka-cli load-mtp) with the mode named in theruntimeblock. leleka-daemonis unchanged and still has its narrow Responses subset; retiring that route is a separate step.