Respond to code review: sampling defaults, abort race, hardening + README

Bug fixes (from review/README.md):
- Apply config sampling defaults field-by-field, so an absent temperature no
  longer means greedy; expose top_k/min_p/repetition_penalty on ChatRequest;
  top_k=0 is "disabled" (-> 64), not greedy.
- Fix cross-request abort race: Engine::request_stop() sets the cancel flag only;
  the owning generate loop does STOP+drain itself, instead of a spawned abort()
  that could hit a later request holding the lock.
- Initialize tracing-subscriber (RUST_LOG, default info); events were dropped.
- TempFilesGuard removes materialized images on every exit path (error/panic/drop);
  build_prompt runs in spawn_blocking off the async worker; ureq image fetch gets a
  15s timeout, a 32MB cap and a basic SSRF guard (literal loopback/private hosts).
- Non-blocking shutdown (STOP+QUIT without taking the request lock first) and a
  bounded drain_to_done that marks the engine dead on timeout.

Operational hardening:
- Graceful shutdown on SIGTERM as well as SIGINT.
- Warn when binding a non-loopback address (no auth, allowed_hosts not enforced).
- Configurable startup/silence timeouts (optional config keys, default 600s).

Docs:
- Add README.md (English): what strata-ctl is, why Rust for stable server use,
  architecture, usage, honest status, and credits to Strata / Niko1221.

76 tests green + 2 real-file ignored; clippy clean; cargo fmt applied.
Deferred (heavy): automatic engine restart after a crash.
This commit is contained in:
adm committed 2026-11-24 18:42:56 +01:00
1 parent 597ac432e1
commit 5bafd000c8
13 files changed
+651 -51

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
# strata-ctl
A Rust control layer for the [Strata](https://github.com/Niko1221/Strata) inference
engine: an OpenAI-compatible HTTP API that drives the engine over its native line
protocol.
`strata-ctl` is a from-scratch **Rust rewrite of Strata's control framework** (the
Python "serve" layer that sits between HTTP clients and the C++ inference engine).
It is not a fork of the engine itself: the engine stays the upstream C++ binary
(`strata-inkling`); this project replaces the layer that supervises it and exposes
it to the network.
## Why Rust?
We believe Rust is a much better fit than Python for a process meant to run
**stably, unattended, on a server** for long periods:
- **Memory safety without a garbage collector** — no GC pauses, no reference-count
cycles leaking over weeks of uptime, no interpreter runtime to babysit.
- **Predictable latency and throughput** — compiled, no GIL, async I/O on `tokio`
with explicit control over blocking work.
- **Fearless concurrency** — the compiler enforces the ownership rules that keep a
shared, long-lived engine supervisor honest under concurrent requests.
- **A single self-contained binary** — trivial to deploy, supervise (systemd) and
reproduce; no virtualenv, no dependency drift at runtime.
The original Python layer remains the **behavioral specification**: this rewrite
aims to match what it does on the wire, while being a more dependable thing to
leave running on a server.
## Relationship to Strata
- **Strata** — "Run powerful AI on your own computer. Chat, code and work with
images, locally." Free, open source (MIT), by **Niko1221** and the Strata
contributors: <https://github.com/Niko1221/Strata>.
- This project targets Strata's **Inkling** engine (`strata-inkling`, the
`inkling2_loop` architecture) and its in-process Vision. The API layer is built
behind a model-agnostic `Formatter` seam, so other dialects can be added later.
- All credit for the engine, the model format and the original control-layer
behavior goes to the Strata project and its author. `strata-ctl` is an
independent reimplementation of the control layer only.
## Features
OpenAI-compatible endpoints:
- `POST /v1/chat/completions` — streaming (SSE) and non-streaming.
- `GET /v1/models`, `GET /health`.
Behavior implemented and validated against the real Inkling engine:
- **Chain-of-thought separation** — thinking is streamed live as
`reasoning_content`, distinct from the answer `content`.
- **Images** — OpenAI / Responses / Anthropic image parts (base64 data URLs,
http(s) URLs, local paths) are materialized and handed to the engine's
in-process Vision; unsupported formats are normalized to PNG.
- **Tool calling** — structured OpenAI `tool_calls` in the llama.cpp `--jinja`
style: the server renders tool declarations and parses the model's calls;
**execution is client-side** (the server never runs tools).
- **Stop sequences** — incremental matching with hold-back, so a stop string split
across streaming deltas is still caught.
- **Abort on client disconnect** — generation is stopped when the SSE client goes
away, freeing the engine for the next request.
- **Sampling** — per-request knobs override config defaults field-by-field
(`temperature`, `top_p`, `top_k`, `min_p`, penalties, `seed`); `top_k = 0` is
treated as "disabled", not greedy.
Operational hardening:
- Graceful shutdown on **SIGINT and SIGTERM**; the engine is signalled without
blocking on an in-flight request.
- Configurable startup and silence-watchdog timeouts.
- A warning when binding a non-loopback address (the API has no authentication).
- Blocking image I/O runs off the async event loop; temp files are cleaned on every
exit path; image fetches have a timeout, a size cap and a basic SSRF guard.
## Architecture
```
shared JSON config ──► InklingFormatter ──► Engine supervisor ──► axum HTTP API
(tolerant) tokenizer + chat line protocol /v1/...
template + dialect (GEN/T/DONE/STOP)
```
- `config` — tolerant loader for the shared `strata-inkling.json`: it reads what it
understands and ignores every other key, so one file can drive several tools.
- `inkling` — the model dialect: HF `tokenizers` (o200k BPE) wrapper, MiniJinja chat
template, the channel-token state machine, and the image bridge.
- `engine` — a pure protocol parser plus a supervisor that owns the child process,
serializes requests on its single control stream, and handles STOP/drain/QUIT.
- `api` — request/response types, the `Formatter`/`Decoder` seam, the completion
service (stream + non-stream) and the axum router.
## Building and running
Requires a Rust toolchain and a built Strata engine binary (`strata-inkling`).
```sh
cargo build --release
# Print the launch plan resolved from the config (default):
./target/release/strata-ctl --config /path/to/strata-inkling.json
# Start the engine and serve the API:
./target/release/strata-ctl --serve --config /path/to/strata-inkling.json
# overrides: --host 127.0.0.1 --port 8095
```
The default config path is `~/.config/strata-inkling/strata-inkling.json`. Logging
uses `tracing`; set `RUST_LOG` to control verbosity (default `info`).
### Configuration
The config is the same JSON the other Strata tools use. Keys acted on here include
`exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`,
`sampling`, and the optional `startup_timeout_secs` / `silence_timeout_secs`.
Everything else (`arch`, `mcp_servers`, `cors_origins`, `allowed_hosts`, …) is
preserved untouched and reported as ignored — unknown keys never break startup.
## Status
Working and tested (76 tests, plus 2 real-file tests run on demand). Text, images
and the full client-side tool loop have been validated live against the real
Inkling engine.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
engine restart after a crash, an API key / `allowed_hosts` enforcement, a full
SSRF guard against DNS rebinding, and the Anthropic / Responses native endpoints.
## License and credits
MIT, like Strata itself.
- **Strata** engine and original control layer: Niko1221 and the Strata
contributors — <https://github.com/Niko1221/Strata>.
- **strata-ctl** (this Rust control layer): Federico (`iz0eyj`).