# Host-side request latency: control plane, tokenizer, gRPC (`claude/cp-latency`) Status: measured and fixed on the host side of a request (everything before the engine starts the prefill and after tokens leave it). The numbers below are a paired A/B of the code before and after, on the same workload, with an *instant* engine (it answers the moment it has the prompt), so they are the cost of the host path only and say nothing about the engine, the model or its quality. Token ids and prompt text are bit-identical to the old path on all the data checked (section 4). The real-engine run (section 6) is queued as job `9f1-cp-live-ab` and is not part of the numbers until it ran. Branch `claude/cp-latency`, cut from `claude/port-gpu-bringup` at `cfe0a02`. The baseline for every "before" is `dbf487b` (the original request path plus the env-gated stage spans and the replay driver, nothing else); the "after" is the branch head. ## 1. What was measured and how **Workload.** The engine side capture of two real Codex sessions (`capture/943b-codex-ttt`, `capture/945-codex-crm`: the rendered prompt token ids of every request) was inverted into the Responses requests Codex sends: `scripts/cp/synth_session.py` decodes the prompt with the pinned vocabulary and turns the system block into `instructions` and `tools`, the user turns into messages, the assistant turns into `reasoning` / `message` / `function_call` items and the `` turns into `function_call_output` items. The history of the CRM session (123,239 tokens) is extended with the second session (call ids and text tagged so no two items are identical) to reach 196k tokens. Check: rendering and tokenizing the synthesized request for the last captured round gives **exactly the 123,239 captured prompt ids** (and 82,315 for the other session), through the real HTTP layer. The captures and the synthesized sessions stay outside Git. **Driver.** `control-plane/examples/cp_replay.rs`: real axum router, real `backend_worker`, real tokenizer, real loopback HTTP (keep-alive, SSE), request bodies exactly as Codex sends them (`reasoning.effort` medium, `store: false`, 12 tools, `stream`). For each history size (20k, 60k, 120k, 180k tokens, picked by the server's own `/v1/responses/input_tokens`) it replays 16 consecutive rounds of the session on a fresh stack: turn 0 is **cold** (nothing cached), turns 1.. are the **steady state** of a real session (each request is the previous history plus a few new items). Two engines behind it: * `proc`: an in-process engine implementing `leleka_backend_api::Backend` (answers at once with a 420-token reasoning + tool-call reply, 24-byte deltas 1 ms apart after a 20 ms wait, so the response's opening events have left before the first token); * `grpc`: the same engine behind the real `RuntimeServer` and the control plane's `GrpcBackend` (`desktop-core/examples/cp_replay_grpc.rs`): snapshot RPC, a 640 KB prompt string over HTTP/2 on loopback, the event stream back. **Metrics** (ms per request, warm turns, p50 / p95): `pre_engine` = the client finished sending -> the engine has the prompt (body read, JSON parse, validation, chat template, tokenization, queue, prompt text for the engine, the engine call); `first_event` = the engine's first text delta -> its SSE event at the client; `tail` = the engine's terminal event -> `response.completed` at the client. The stage table comes from the spans (`STRATA_STAGE_TRACE=1`, off by default: one relaxed atomic load per span; `STRATA_STAGE_TRACE=log` writes `stage t_unix_ms=` lines to stderr, which `scripts/cp/live_report.py` joins with a client's timings). **Noise.** The laptop (WSL2 Ubuntu 24.04, i9-11900H 8C/16T, rustc 1.99.0, other agents building and running jobs on it) is shared. Base and new runs alternate (`scripts/cp/run-ab.sh`), five repeats, and each cell is the *minimum over the repeats* of that repeat's p50 (resp. p95): the least disturbed estimate of each build. Raw per-turn rows are in the result JSONs the driver writes. ## 2. What was found and what changed (largest first) At a 180k-token history, warm turn, `grpc` engine, per request, before -> after: | # | finding | before -> after | | --- | --- | --- | | 1 | **The whole history was tokenized twice before the engine saw it.** The HTTP layer encoded the rendered prompt (`tokenize`), and the text-level worker then decoded those ids back to text and encoded that again to prove the round trip (`worker_prompt_text`), because the engine contract carries text. The tokenizer (regex pre-tokenizer + string BPE) ran at 1.0-1.3 Mtok/s. | `tokenize` 177 -> 1.0 ms, `worker_prompt_text` 187 -> 0.95 ms | | 2 | **A new tokenizer fast path with a segment cache** (`crates/tokenizer`): a hand-written scanner for the pinned pre-tokenizer pattern (Unicode classes read out of `regex-syntax`, the crate the regex engine uses), byte-level BPE over token ids with a rank table instead of re-built strings, and a bounded cache of the ids of text between special tokens, keyed by the exact text (a hit is verified byte for byte). Uncached 11.5 Mtok/s (9x); a repeated history costs a hash and a memcpy: 123k tokens in 0.24 ms against 100 ms. The agent resends its whole history every turn, so every turn after the first only tokenizes its new tail. The same crate runs in the engine process (`prepare_prompt` encodes the prompt string again, on every request, before the prefill), so that request-path copy of the cost goes away there too. | cold 123k tokens 100 -> 11 ms (the whole cold `pre_engine` at 180k: 340 -> 24 ms), warm 0.24 ms | | 3 | **The runtime gRPC server had Nagle on.** `serve_with_incoming_shutdown` ignores the builder's `tcp_nodelay` and `TcpListenerStream` does not set it, so every small response frame (the accept of a generation, the first delta, the terminal) waited for the client's delayed ACK. `TcpIncoming::with_nodelay(true)` in `desktop-core/src/runtime_rpc.rs`. | `engine_start` 42 -> 2.2, first token to the client 19.2 -> 0.4, completion 36.7 -> 1.4 | | 4 | **Chat template over the whole history**: three copies of every message (`Owned`, `Json`, minijinja `Value`) and the Jinja loop. For this template every message after the leading system messages renders to text that depends on that message alone (`preserve_thinking` is never set), so only the head (tools, reasoning instruction, merged system text) goes through Jinja and the messages are written directly (`prompt::render_native`; `STRATA_REFERENCE_RENDER=1` goes back to the template). | `render` 2.4 -> 0.98 | | 5 | Tool-schema validation compiled a JSON-schema validator per tool, three times per request (parse, initial envelope, final response). Memoized by the schema text. | `request_validate` 0.26 -> 0.07 | | 6 | The two per-generation log lines were written before the engine call / before the terminal event reached the client, under the stderr lock. Their timestamps are unchanged; the write now follows. | off the response path | | 7 | `TCP_NODELAY` on the HTTP listener (SSE events and small responses must not wait for an ACK). | not measurable on loopback; correct for a LAN | Not changed, measured: body read + JSON parse 1.4 ms (a borrowed/typed parse would save about 1 ms and needs the validation error texts re-proved), the snapshot RPC before every generation 0.7 ms (it is a deliberate identity check), the 640 KB prompt over HTTP/2 about 1.6 ms (frame size and window settings made no difference), `response.created` is sent after tokenization (Codex does not wait for it). Per streamed token the host spends about 12 us (decode, event JSON, SSE), 0.08 % of one core at 65 tok/s: flush batching per engine round would change the event contract for nothing. ## 3. Results Headline, 180k-token history, warm turn (steady state of a session), p50 (p95), ms, minimum over 5 interleaved repeats: | | before (`dbf487b`) | after | | --- | --- | --- | | `pre_engine`, engine behind the real gRPC hop | 376 (398) | **6.5 (6.8)** | | `pre_engine`, in-process engine | 347 (371) | 5.2 (5.6) | | `first_event` (engine's first delta -> client), gRPC | 19.2 (20.0) | 0.39 (0.47) | | `tail` (engine's terminal -> `response.completed`), gRPC | 36.7 (41.6) | 1.44 (1.53) | | `pre_engine`, first request of a session (cold), gRPC | 340 | 24 | The same at the other sizes (`pre_engine`, gRPC, warm p50): 20k 90 -> 2.9, 60k 149 -> 3.8, 120k 270 -> 5.3. The cost used to grow with the history (about 2 ms per 1k tokens); it now grows by about 0.02 ms per 1k tokens. Per request that is roughly 370 ms before the engine plus about 55 ms of gRPC stalls around the first token and the completion, at 180k. Full tables as printed by `scripts/cp/summarize.py` (p50 / p95 per cell; stage names as in section 1): #### in-process instant engine | metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | |---|---|---|---|---|---|---|---|---| | pre_engine_ms | 76.32 / 94.96 | 2.36 / 2.65 | 137.11 / 155.63 | 3.06 / 3.32 | 264.87 / 287.44 | 4.40 / 4.92 | 346.77 / 370.86 | 5.18 / 5.64 | | first_event_ms | 0.30 / 0.38 | 0.24 / 0.34 | 0.31 / 0.38 | 0.28 / 0.36 | 0.38 / 0.47 | 0.23 / 0.33 | 0.44 / 0.49 | 0.29 / 0.39 | | tail_ms | 1.32 / 1.37 | 1.08 / 1.17 | 1.44 / 1.51 | 1.10 / 1.24 | 1.53 / 1.65 | 1.24 / 1.35 | 1.60 / 1.75 | 1.31 / 1.37 | | stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | |---|---|---|---|---|---|---|---|---| | http_body_json | 0.30 / 0.36 | 0.35 / 0.43 | 0.56 / 0.71 | 0.59 / 0.69 | 1.14 / 1.22 | 1.08 / 1.15 | 1.35 / 1.43 | 1.32 / 1.53 | | request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.06 | 0.09 / 0.11 | 0.09 / 0.10 | 0.12 / 0.15 | 0.12 / 0.15 | | request_validate | 0.22 / 0.24 | 0.07 / 0.08 | 0.23 / 0.24 | 0.07 / 0.07 | 0.24 / 0.27 | 0.06 / 0.07 | 0.25 / 0.28 | 0.07 / 0.07 | | render | 0.64 / 0.71 | 0.44 / 0.47 | 1.09 / 1.21 | 0.55 / 0.61 | 1.81 / 1.91 | 0.82 / 0.90 | 2.31 / 2.53 | 0.99 / 1.02 | | tokenize | 36.75 / 42.84 | 0.46 / 0.61 | 65.94 / 73.67 | 0.62 / 0.73 | 125.56 / 137.45 | 0.91 / 1.31 | 163.90 / 175.74 | 1.05 / 1.23 | | worker_prompt_text | 37.86 / 47.49 | 0.35 / 0.40 | 67.95 / 78.76 | 0.48 / 0.54 | 133.91 / 142.57 | 0.74 / 0.85 | 176.74 / 188.26 | 0.97 / 1.07 | | engine_start | 0.38 / 0.43 | 0.28 / 0.31 | 0.49 / 0.53 | 0.39 / 0.42 | 0.71 / 0.77 | 0.65 / 0.67 | 0.90 / 0.97 | 0.80 / 0.86 | | post_decode | 0.16 / 0.19 | 0.08 / 0.10 | 0.17 / 0.20 | 0.08 / 0.10 | 0.18 / 0.19 | 0.09 / 0.10 | 0.18 / 0.20 | 0.09 / 0.10 | | post_assemble | 0.67 / 0.72 | 0.53 / 0.57 | 0.70 / 0.74 | 0.54 / 0.59 | 0.70 / 0.76 | 0.55 / 0.60 | 0.70 / 0.75 | 0.56 / 0.63 | | post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | | delta_retokenize | 1.92 / 2.29 | 0.50 / 0.59 | 2.00 / 2.25 | 0.44 / 0.55 | 2.11 / 2.29 | 0.47 / 0.54 | 1.97 / 2.33 | 0.49 / 0.61 | cold first request (ms, min over repeats): base pre_engine cold: 20k=57.0, 60k=120.6, 120k=235.5, 180k=317.4 new pre_engine cold: 20k=5.6, 60k=9.2, 120k=16.5, 180k=22.8 #### instant engine behind the real gRPC runtime server | metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | |---|---|---|---|---|---|---|---|---| | pre_engine_ms | 89.96 / 100.84 | 2.93 / 3.38 | 148.72 / 166.45 | 3.81 / 4.16 | 269.81 / 296.34 | 5.34 / 6.01 | 376.19 / 398.10 | 6.50 / 6.84 | | first_event_ms | 19.30 / 20.18 | 0.36 / 0.44 | 18.73 / 19.91 | 0.32 / 0.40 | 18.92 / 20.25 | 0.34 / 0.41 | 19.18 / 20.01 | 0.39 / 0.47 | | tail_ms | 37.11 / 41.51 | 1.18 / 1.34 | 34.79 / 40.25 | 1.21 / 1.30 | 35.73 / 42.66 | 1.31 / 1.40 | 36.65 / 41.56 | 1.44 / 1.53 | | stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | |---|---|---|---|---|---|---|---|---| | http_body_json | 0.31 / 0.38 | 0.32 / 0.43 | 0.58 / 0.71 | 0.58 / 0.66 | 1.07 / 1.23 | 1.00 / 1.17 | 1.39 / 1.67 | 1.35 / 1.52 | | request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.05 | 0.09 / 0.11 | 0.09 / 0.10 | 0.13 / 0.16 | 0.12 / 0.15 | | request_validate | 0.22 / 0.26 | 0.07 / 0.07 | 0.22 / 0.24 | 0.06 / 0.07 | 0.23 / 0.28 | 0.07 / 0.07 | 0.26 / 0.29 | 0.07 / 0.08 | | render | 0.68 / 0.78 | 0.42 / 0.47 | 1.06 / 1.16 | 0.56 / 0.64 | 1.85 / 1.99 | 0.84 / 0.88 | 2.37 / 2.50 | 0.98 / 1.04 | | tokenize | 40.90 / 45.94 | 0.46 / 0.65 | 70.57 / 79.79 | 0.63 / 0.76 | 127.94 / 148.69 | 0.90 / 1.29 | 176.81 / 202.94 | 1.03 / 1.32 | | worker_prompt_text | 43.00 / 50.17 | 0.34 / 0.43 | 75.03 / 84.18 | 0.47 / 0.53 | 135.32 / 149.33 | 0.76 / 0.84 | 186.68 / 203.86 | 0.95 / 1.06 | | engine_start | 1.74 / 40.88 | 1.08 / 1.22 | 39.36 / 41.22 | 1.34 / 1.57 | 40.51 / 42.04 | 1.77 / 1.95 | 41.66 / 42.40 | 2.15 / 2.47 | | post_decode | 0.16 / 0.19 | 0.08 / 0.09 | 0.17 / 0.21 | 0.08 / 0.09 | 0.15 / 0.18 | 0.08 / 0.10 | 0.16 / 0.20 | 0.09 / 0.11 | | post_assemble | 0.67 / 0.78 | 0.56 / 0.59 | 0.69 / 0.83 | 0.54 / 0.57 | 0.70 / 0.83 | 0.55 / 0.58 | 0.73 / 0.78 | 0.56 / 0.59 | | post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | | delta_retokenize | 1.97 / 2.17 | 0.53 / 0.58 | 2.07 / 2.33 | 0.45 / 0.49 | 1.94 / 2.12 | 0.49 / 0.54 | 1.99 / 2.24 | 0.54 / 0.57 | cold first request (ms, min over repeats): base pre_engine cold: 20k=61.6, 60k=127.0, 120k=253.7, 180k=340.2 new pre_engine cold: 20k=6.5, 60k=10.1, 120k=17.6, 180k=23.9 ## 4. Equivalence * `cp_replay --verify` replays **every round** of the synthesized sessions (135 rounds, 9k-196k tokens, and 52 rounds of the other session) through the real HTTP layer and checks: the ids of the production path equal `Tokenizer::encode_reference` (the original implementation) on the prompt the engine received; the ids decode back to that prompt; `/v1/responses/input_tokens` counts them; the round whose history is the captured request reproduces the **captured prompt ids** (123,239 and 82,315 tokens) exactly. The per-round `PROMPT round tokens prompt_fnv ids_fnv` lines of the baseline build, of the new build and of the new build with `STRATA_REFERENCE_RENDER=1` (Jinja for every prompt) are byte-identical (md5 of the 135 lines equal in all three). * `crates/tokenizer/tests/fast_path.rs`: the scanner splits every Unicode scalar value in 13 contexts and 400,000 fuzzed texts like the regex; `encode` equals `encode_reference` for ~3,000 fuzzed texts and the oracle cases on a cold cache, a warm cache and a cache too small to hold anything; real prompts (`LELEKA_TOKENIZER_DIR` / `LELEKA_TOKENIZER_TEXTS`) encode like the reference cold and warm; the existing Python-oracle test (`oracle_differential.rs`) still passes. * `prompt::native_render_equals_the_template`: 4,000 random conversations (whitespace of every kind at the edges, empty contents, template-looking and special-token text, with and without system messages and tools, every effort) render to the same bytes (or the same error) both ways; the ten golden chat cases pass. * `strata-control`: all 282 unit tests and every integration test, including the golden HTTP surface and the full-chain `backend_worker_http` suite (a new test covers the prompt-text pass-through: the text is sent only if the ids decode to it, else the old check runs); `strata-desktop-core` (the full chain with the real `RuntimeServer`), `leleka-runtime-client`, `leleka-backend-api`, `leleka-serving-policy`, and `leleka-runtime --lib` (510) pass. * Kill switches: `LELEKA_TOKENIZER_REFERENCE=1` (original tokenizer only), `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` (0 = no cache; default 64, both engine and control plane), `STRATA_REFERENCE_RENDER=1`. ## 5. How to reproduce ```text python3 scripts/cp/synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ OUT.json [--extend CAPTURE2 LAST2] cargo run --release -p strata-control --example cp_replay -- TOKENIZER_DIR OUT.json [--sizes 20000,60000] [--turns 16] [--out r.json] cargo run --release -p strata-desktop-core --example cp_replay_grpc -- TOKENIZER_DIR OUT.json # real gRPC hop cp_replay TOKENIZER_DIR OUT.json --verify [--verify-step 1] # equivalence scripts/cp/run-ab.sh BASE_TREE NEW_TREE TOKENIZER_DIR OUT.json OUT_DIR 5 --turns 16; python3 scripts/cp/summarize.py OUT_DIR LELEKA_TOKENIZER_DIR=... LELEKA_TOKENIZER_TEXTS=... cargo test --release -p leleka-tokenizer ``` ## 6. Real engine Job `scripts/e2e/codex/jobs/9f1-cp-live-ab.sh` (queue name `9f1-cp-live-ab`): one model load, the current `strata-next` on :8081 and the baseline `strata-next` on :8082 in front of the same engine (the new `leleka-inference`), one synthesized Codex session of about 100k tokens, 20 consecutive requests (`max_output_tokens` 64) sent alternately through the two so the engine sees the same prompt sequence either way. `scripts/cp/live_report.py` joins the client's timings with both servers' stage logs and the engine's `generation done` lines: client time to first token = pre-engine host time + engine time + post time. Queued behind the other jobs of `holder2/jobs` (23 pending when submitted); the result is appended here when it ran. ## 7. What remains * The engine contract carries the prompt as text, so the engine still tokenizes it (now a cache hit for a repeated history). Carrying the ids, or just the new tail plus a prefix digest, would remove the 640 KB string and the text/ids round trip; it is a contract change (proto, `RuntimeServer`, the engine), not made here. `runtime_rpc.rs` refuses a prompt above 1 MiB: at 3.76 bytes per token that is about 280k tokens, close to the 262k context for code-heavy text. * Body read and parse (1.4 ms at 180k), the snapshot RPC (0.7 ms), the prompt over HTTP/2 (1.6 ms) are the remaining 6.6 ms of `pre_engine`; the first two need semantics decisions (typed parse with identical errors; trusting the server-side epoch fence). * Clients that send `store: true` or `previous_response_id` (Codex sends neither) pay the history store before the terminal event: in memory it measured 1.2 ms at 180k (`post_store`, `cp_replay --store`); with persistence on it re-serializes and checksums *all* stored entries (up to 128 MiB) on every response, which was not measured; `previous_response_id` deep-copies the saved transcript. Not on the Codex path, not changed. * With `reasoning.effort` other than `none` the answer text (and tool calls) are withheld until the engine's terminal event (reasoning deltas stream live); the host cost of that is the 1.5 ms `tail`, the wait itself is the design. * The engine side of the prefix cache (block hash chain over 180k tokens, about 0.3 ms: one multiply-xor per token, sequential) and the cache resume grid belong to `claude/ttft`.