From 17bbcae2d506079f51cd010744bd90f67c85434d Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 16 Oct 2026 02:20:20 +0200 Subject: [PATCH] docs: options and decision for one API in front of the Rust engine Co-Authored-By: Claude Sonnet 5.5 --- docs/api-over-rust-engine.md | 112 +++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 docs/api-over-rust-engine.md diff --git a/docs/api-over-rust-engine.md b/docs/api-over-rust-engine.md new file mode 100644 index 00000000..e8cafcb2 --- /dev/null +++ b/docs/api-over-rust-engine.md @@ -0,0 +1,112 @@ +# 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`](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 ` / `T ` / `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|>`/`<|endoftext|>` ids as the end | engine stops at its single `eos` id and never emits it; no other stop handling | +| 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.rs` and 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-plane` source 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.rs` is 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: + +1. 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. +2. All existing `strata-next` tests stay valid by construction: the stdio worker is untouched, and the new worker is selected by + an explicit configuration block (`runtime`), mutually exclusive with `engine.executable`. +3. The engine contract stays the engine's: `crates/backend-api` and `leleka-runtime/src/backend*.rs` are not modified. The + things the contract cannot express are refused or documented, not papered over (below). +4. 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 reports `not ready` meanwhile. + +`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 + +See "Status" at the end of this page, written after the implementation.