Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
837 lines
56 KiB
Markdown
837 lines
56 KiB
Markdown
# Native API contract status
|
||
|
||
## Idle SSE transport
|
||
|
||
Native Responses (text, tools and buffered structured/reasoning output), Chat
|
||
Completions and Messages streams emit `: keep-alive` SSE comments after 15 seconds
|
||
without a stream event. These transport comments contain no model output, usage,
|
||
sequence number or completion signal. SSE clients must ignore comment-only frames.
|
||
The internal adapters and offline replay verifier do so. A finished stream ends
|
||
normally; keep-alive does not extend generation deadlines or retain disconnected
|
||
requests. Normal backpressure still applies; this is not a guarantee against
|
||
proxy timeouts shorter than 15 seconds or intermediaries that buffer SSE.
|
||
|
||
## Chat Completions (text/function subset)
|
||
|
||
`POST /v1/chat/completions` uses the native Responses generation path. The wire
|
||
shape follows [Chat Completions create](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create):
|
||
JSON `chat.completion` and live SSE `chat.completion.chunk` with one indexed choice,
|
||
assistant content/function calls, `stop` / `length` / `tool_calls` finish reasons,
|
||
and a final `data: [DONE]`. SSE text deltas arrive before engine completion.
|
||
Function calls are published only after native tool validation, with a complete
|
||
argument string in one delta per call. This deliberately does not stream
|
||
unvalidated argument fragments.
|
||
|
||
Supported inputs:
|
||
|
||
- `model`, `messages` with system/developer/user/assistant text and tool results;
|
||
text strings or arrays of `{"type":"text","text":"..."}` parts;
|
||
- assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and
|
||
tool `tool_call_id`/text; complete returned assistant messages can be reused;
|
||
- function tools, `auto`/`none`/`required` or a forced function name,
|
||
`parallel_tool_calls`, temperature and top_p, and the sampling controls listed under
|
||
"Sampling controls" below (`frequency_penalty`, `presence_penalty`, `seed`, `top_k`, `min_p`,
|
||
`repetition_penalty`, `penalty_last_n`);
|
||
- `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`;
|
||
- `response_format` text, json_object, or json_schema containing name/schema/strict
|
||
under `json_schema`; the same native schema subset and final validation apply.
|
||
This is validation of generated output, not constrained token sampling;
|
||
- `stream` and `stream_options.include_usage`: when requested, normal chunks carry
|
||
`usage: null`, followed by a final empty-choices usage chunk before `[DONE]`.
|
||
|
||
This first subset always uses `reasoning_effort: none` (also the default here)
|
||
and `store: false`; no hidden reasoning is requested or returned. Other efforts,
|
||
storage, multiple choices, multimodal input/output, custom/namespace tools,
|
||
custom stop sequences, log probabilities,
|
||
schema descriptions, non-null refusal text and unknown fields are rejected before
|
||
worker generation. It does not implement the full upstream API or stored Chat
|
||
retrieval. Omitted optional values use existing Responses defaults, including its
|
||
output-token limit. A Chat ID is not a Responses history ID.
|
||
|
||
Usage renames native input/output/total counters to prompt/completion/total tokens,
|
||
including cached/reasoning detail counters. Incomplete output uses `length` and
|
||
does not publish a truncated tool call. An error emits the native error object
|
||
(and `[DONE]` for SSE) without a successful finish reason or final usage. Text
|
||
already streamed before final schema validation can precede that error.
|
||
|
||
Auth, 16 MiB request bodies, admission/drain/queue limits and worker cancellation
|
||
are shared with Responses. The adapter bounds each native SSE event or JSON body
|
||
at 64 MiB; exceeding it fails explicitly. A disconnected Chat stream drops the
|
||
native stream consumer, triggering existing STOP/drain isolation; a failed request
|
||
is never replayed automatically. Request text and completions are not persisted.
|
||
|
||
The CPU HTTP gate compares actual engine `GEN` token IDs and fixture outputs
|
||
against equivalent Responses with tolerance zero, including tools/continuation,
|
||
Unicode, JSON/SSE/usage, errors and live disconnect→STOP→fresh request. This is
|
||
protocol qualification only; real-model/harness rollout remains a separate gate.
|
||
|
||
## Anthropic Messages (text/client-tool subset)
|
||
|
||
`POST /v1/messages` uses the same native Responses worker, with
|
||
`anthropic-version: 2023-06-01`. It follows the [Messages request/response](https://platform.claude.com/docs/en/api/messages/create)
|
||
and [named streaming events](https://platform.claude.com/docs/en/build-with-claude/streaming)
|
||
shapes for text and client tools. This serves the configured local model, not a
|
||
Claude model or an Anthropic cloud service.
|
||
|
||
Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks,
|
||
user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice`
|
||
(`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`,
|
||
temperature (0..1), top_p and top_k (plus the extension controls under "Sampling controls"). Text parts join with newlines; consecutive turns of
|
||
the same role combine. This initial subset requires first and last user messages;
|
||
assistant prefill is rejected. Assistant `tool_use` carries an object `input` and
|
||
ID; user `tool_result` returns the same `tool_use_id` and text or text blocks.
|
||
Omitted result `content` means empty text; explicit null and non-text blocks remain
|
||
invalid. [Client-tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)
|
||
with `is_error: true` are supported. Because the native template has text tool
|
||
outputs, the adapter serializes `{"content":"<normalized text>","is_error":true}`
|
||
as that call's tool output, preserving the flag and text (including escaped
|
||
control characters). Normal/`is_error: false` results retain their existing text
|
||
unchanged. Counting and serving share this conversion. This supports transport
|
||
of failures; recovery behavior still requires model qualification.
|
||
Tool names, arguments, results and choice policies reuse native validation.
|
||
|
||
Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless.
|
||
Thinking/redacted signatures, images/documents, cache_control, nonempty
|
||
stop_sequences, server tools, metadata, structured-output options,
|
||
beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent.
|
||
|
||
`POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens)
|
||
and returns `{"input_tokens": N}`. It accepts `model`, `messages`, optional `system`,
|
||
`tools`, `tool_choice` and disabled `thinking` from the subset above. Generation
|
||
fields (`max_tokens`, `stream`, sampling options) and unknown fields are rejected.
|
||
It uses the same serving conversion, prompt template and configured local tokenizer;
|
||
the count includes system/tool overhead and the generation prefix, without a cache
|
||
discount. It is not a Claude tokenizer estimate or a context/VRAM fit guarantee.
|
||
No worker generation or response-history writes occur, and it works while the
|
||
worker is unavailable if the tokenizer is configured. The same Messages version,
|
||
key/Bearer, body limit, admission/drain and error rules apply. CPU HTTP fixtures
|
||
compare the count to actual GEN input IDs with tolerance zero, including tool history.
|
||
|
||
JSON returns ordered text/tool_use blocks with `end_turn`, `tool_use` or
|
||
`max_tokens` stop reasons and null stop_sequence. SSE uses message_start,
|
||
content_block_start/delta/stop, message_delta and message_stop (no `[DONE]`).
|
||
Text streams before DONE; validated tool inputs arrive as one complete JSON string
|
||
in an input_json_delta. There is no fine-grained unvalidated tool streaming.
|
||
Errors use `{"type":"error","error":{"type":"...","message":"..."}}` and a named
|
||
SSE error event; failed streams never emit a successful message_stop. Partial
|
||
text can precede a final validation error. Malformed or incomplete tool syntax
|
||
fails explicitly instead of publishing a tool block.
|
||
|
||
Engine counters become known at DONE: message_start usage is provisional zero,
|
||
and the final message_delta supplies cumulative input/output/cache totals.
|
||
This uses the [SDK's optional cumulative input/cache usage fields](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_delta_usage.py).
|
||
Clients must replace these totals, not add them. input_tokens excludes native
|
||
reused tokens, cache_read_input_tokens reports reuse, cache_creation_input_tokens
|
||
is zero (no provider cache-directive contract), and output_tokens is native total
|
||
output. Older clients that ignore final input/cache updates may display zero input
|
||
usage during streaming. JSON carries final totals directly.
|
||
|
||
The existing local key can be sent as `x-api-key` **only on this route**, or as
|
||
Bearer. When authentication is configured, duplicate keys or a key combined with
|
||
Authorization are rejected; other API routes retain Bearer authentication.
|
||
The route shares the 16 MiB body limit, admission/drain and cancellation rules.
|
||
The bounded native SSE reader (64 MiB/event) is shared with Chat; each adapter
|
||
buffers at most eight output events. Disconnect releases the native consumer,
|
||
sends STOP and preserves the next request. No request/response history is stored.
|
||
|
||
The actual CPU HTTP gate compares GEN tokens and fixture output to equivalent
|
||
Responses (tolerance zero), reconstructs ordered JSON from named SSE, and checks
|
||
Unicode, system/combined turns, tools/continuation, usage, headers/errors,
|
||
admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth
|
||
regressions run alongside it; real-model/harness/GPU qualification remains open.
|
||
|
||
## Sampling controls
|
||
|
||
Every route that generates (Responses, Chat Completions, Messages) takes the Original server's
|
||
sampling fields at the top level of the request body, with the Original's defaults (an absent field
|
||
keeps the engine's greedy default) and ranges, and fails closed on a value outside them
|
||
(`crates/sampler-ref` `RequestSampling`, `docs/sampler-reference.md`):
|
||
|
||
| Field | Range | Notes |
|
||
| --- | --- | --- |
|
||
| `temperature` | 0..2 | `0` is greedy (Messages: 0..1) |
|
||
| `top_p` | 0..1 | `1` disables nucleus filtering |
|
||
| `top_k` | integer >= 0 | the sampler keeps at most 64: `0` and values above 64 use 64 |
|
||
| `min_p` | 0..1 | |
|
||
| `repetition_penalty` | > 0 | `1` is off |
|
||
| `frequency_penalty`, `presence_penalty` | -2..2 | |
|
||
| `penalty_last_n` | 0..2147483647 | a penalty without a window uses the last 64 tokens; the kernel caps the history at 4096 |
|
||
| `seed` | unsigned integer | `0` or absent draws a fresh clock seed per request |
|
||
| `strata_tune` | `{pcie_frac, spec_min_p}` in 0..1 | engine settings for this request only |
|
||
| `experimental_speed_projection` | boolean | switches a loaded control vector for this request (`cvec=0|1`) |
|
||
| `reasoning_budget_tokens` | whole number, `0` = none | see "Reasoning budget" |
|
||
|
||
The worker `GEN` line is built by the same code the Python server's `StrataEngine.sampling_keys`
|
||
is checked against (`control-plane/tests/fixtures/golden/gen_lines.json`, produced by running that
|
||
code). The Chat route no longer refuses nonzero presence/frequency penalties.
|
||
|
||
Server-wide defaults fill what a request leaves out: the config `sampling` block, then the Chat
|
||
settings shared through `POST /settings`; the request always wins and an explicit `temperature: 0`
|
||
stays greedy. A shared `max_tokens` and `reasoning_effort` apply to Responses requests that carry none
|
||
(Chat and Messages fix their own effort).
|
||
|
||
### Reasoning budget
|
||
|
||
With thinking on, a request's `reasoning_budget_tokens` (else the config's) caps how long the model
|
||
may think. At the budget, on a clean token boundary (no `</think>` prefix held back, no UTF-8
|
||
character split), the worker stops the pass, appends the Original's wrap-up text
|
||
(`"I have thought about this long enough; time to give my answer.\n</think>\n\n"`) to the output
|
||
and continues from `prompt + generated + wrap-up`, so the engine keeps its cached prefix. If the
|
||
wrap-up leaves no room to answer the request ends as `length`. The client sees one token stream and
|
||
one `DONE`: `generated` counts delivered tokens, `prompt_tokens`/`reused` are the first pass's,
|
||
timings are summed.
|
||
|
||
## Operational surface
|
||
|
||
Ported from `engine/strata/serve/server.py` and replayed against the real Python handlers in
|
||
`control-plane/tests/http_surface.rs`:
|
||
|
||
- `GET /props` (llama-server compatible: default generation settings from the config and shared
|
||
settings, chat template, `models_autoload`, `is_sleeping`), `GET /slots`, `GET /v1/status`,
|
||
`GET /api/health` (the Python `/health` body; `/health` keeps the minimal liveness body);
|
||
- `GET|POST /settings` (shared Chat settings, persisted next to the config; JSON from the server's
|
||
own page or a `trusted_origins` origin only);
|
||
- `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload` (own page, JSON object, `409
|
||
model_busy` while a request runs or waits), lazy start (`engine.lazy_load`), idle unload
|
||
(`engine.idle_unload_s`), reload gates (`engine.before_load`, `engine.min_free_vram_mib`); the next
|
||
request after an unload loads the engine again;
|
||
- CORS for `/v1/*` (`cors_origins`, `"*"` allowed) with the preflight answered before
|
||
authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`;
|
||
- engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request
|
||
ends the engine, fails the request with a clear error and uses the restart budget.
|
||
- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in
|
||
`control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file`
|
||
and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are
|
||
validated at start; stdio and Streamable HTTP servers start in the background, tools are listed
|
||
(all pages) and namespaced `<server>__<tool>`, a server that stopped is started again by its next
|
||
call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call
|
||
sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools
|
||
(`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop
|
||
(`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return
|
||
tool calls to the client, so no endpoint executes MCP tools on a client's behalf.
|
||
|
||
Differences from the Python server: authentication is Bearer on every path except `/health` and
|
||
`/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and
|
||
error bodies of the Rust authentication layer are its own.
|
||
|
||
## Model discovery
|
||
|
||
`GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or
|
||
an empty `data` array when no ID is configured. `GET /v1/models/{id}` returns
|
||
the same record; percent-encode the ID as one path segment (including `/`).
|
||
Unknown IDs return JSON `404 model_not_found`. Both routes use existing optional
|
||
bearer authentication. Nonempty query parameters return `400 unsupported_query`;
|
||
POST and DELETE are unsupported and never install or remove a model.
|
||
|
||
The response follows the [Models list](https://developers.openai.com/api/reference/resources/models/methods/list)
|
||
and [retrieve](https://developers.openai.com/api/reference/resources/models/methods/retrieve)
|
||
object shapes: `id`, `object: "model"`, `created: 0`, `owned_by: "local"`, wrapped
|
||
in `{"object":"list","data":[...]}` for the list. `created: 0` is this runtime's
|
||
explicit unknown-timestamp sentinel; `local` identifies a local deployment,
|
||
not the upstream model owner. No model provenance metadata is inferred.
|
||
|
||
This is configuration discovery. It stays available while the worker is loading,
|
||
failed or draining and does not acquire a generation slot or touch model files.
|
||
Use `/ready` to check inference availability. Listing does not download, start,
|
||
test or certify the model, and does not expose filesystem paths or credentials.
|
||
|
||
## Input token counting
|
||
|
||
`POST /v1/responses/input_tokens` returns
|
||
`{"object":"response.input_tokens","input_tokens":123}` using the same native
|
||
history expansion, prompt template and tokenizer as generation. The shape follows
|
||
the [Responses input token count endpoint](https://developers.openai.com/api/reference/resources/responses/subresources/input_tokens/methods/count).
|
||
The local subset requires `model` and `input` and accepts the supported create-request
|
||
fields; unknown fields and unsupported live features are rejected. Instructions,
|
||
reasoning, text format and tool definitions contribute exactly as they do to the
|
||
rendered generation prompt. `previous_response_id` includes the saved transcript
|
||
and new input; new instructions replace prior instructions. Missing, deleted or
|
||
evicted parents return `404 response_not_found`.
|
||
|
||
Counting requires a configured tokenizer, but does not require a ready worker,
|
||
queue inference, create a response ID or modify history (`store` has no effect).
|
||
It always returns ordinary JSON, including when `stream: true` is supplied.
|
||
Generation-only settings are validated but do not generate output. The count is
|
||
for the full rendered prompt, not only newly evaluated tokens or a prediction of
|
||
cache reuse, output length, model quality or available context space. It does not
|
||
truncate input or guarantee the request fits the worker's context.
|
||
|
||
The route shares optional bearer auth, the 16 MiB body limit and bounded HTTP
|
||
admission with create: drain returns 503 and exhausted admission returns 429.
|
||
It remains available during worker failure when the service is not draining.
|
||
The isolated CPU test compares counts against actual `GEN` token IDs, with exact
|
||
integer equality; this does not qualify real-model inference.
|
||
|
||
## Engine activity metrics
|
||
|
||
`GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional
|
||
bearer key as `/status`. This is a native JSON endpoint, not Prometheus text.
|
||
`/status` remains a stable discovery response. Metrics require the new binary;
|
||
the preserved console trial has not been upgraded to this feature.
|
||
|
||
- `active` and `active_elapsed_ms` cover an admitted generation from the attempt
|
||
to write `GEN` until engine `DONE`, `ERR`, or supervisor interruption. They
|
||
do not indicate GPU utilization or HTTP response completion.
|
||
- `queue_capacity` and `queue_used` describe the bounded command channel
|
||
(including reserved capacity), excluding the active command and HTTP handlers
|
||
waiting to enqueue. An unconfigured channel reports null. These snapshots
|
||
are observations, not an admission or safe-restart guarantee.
|
||
- `generation.started` counts admitted attempts. Context/validation rejections,
|
||
abandoned queued requests and requests rejected during restart are excluded.
|
||
`completed` counts non-cancelled DONEs, including length stops. `cancelled`
|
||
counts DONEs with cancel finish or a disconnected consumer. `failed_or_interrupted`
|
||
counts started attempts without DONE, including engine ERR, protocol failure,
|
||
expired cancellation drain and shutdown. Each attempt enters one terminal
|
||
bucket. Engine completion does not imply valid JSON/tool calls or task success.
|
||
- `done_generated_tokens`, `done_prompt_tokens`, `done_decode_ms`, and
|
||
`done_prefill_ms` sum engine DONE values, including cancelled generations.
|
||
Counts for failed attempts are unknown and excluded. Prompt counts are engine
|
||
input counts, not necessarily newly evaluated tokens. Integer totals saturate
|
||
at u64 max and timing totals at the largest finite f64.
|
||
- `done_decode_tokens_per_second` is total DONE tokens divided by total DONE
|
||
decode seconds. `last_done` exposes the last DONE's counts, milliseconds,
|
||
decode rate, raw finish reason, optional reused-token/draft/expert counters.
|
||
Unavailable counters and zero-duration/nonfinite rates are null. There is no
|
||
instantaneous token speed, prefill rate, TTFT, percentile or quality score.
|
||
|
||
Counters survive supervised child restarts and reset when the control-plane
|
||
process restarts. They contain no prompts, generated text, token IDs or keys.
|
||
Updates happen at generation boundaries; no per-token metrics lock is added.
|
||
Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support
|
||
observation; paired workload and quality measurements remain necessary for any
|
||
performance claim.
|
||
|
||
The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open.
|
||
|
||
The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility.
|
||
|
||
For native Qwen tool parameters, a direct property `type: "string"` preserves
|
||
raw text, including quotes. A direct type array containing `"string"` now does
|
||
the same unless the text parses as a declared **non-string** JSON type. Thus
|
||
`["string", "null"]` preserves `123`, `false`, `{}` and quoted text as strings,
|
||
while the literal `null` selects null. `["string", "integer"]` selects an integer
|
||
for `123` and a string for `1.5`. This is a deterministic interpretation of an
|
||
ambiguous raw-text format, not a search for any schema-valid coercion. Full-schema
|
||
validation still runs before publishing a callable item; enum/range violations
|
||
are not retried as strings. Scalar declarations and untyped handling retain
|
||
their previous behavior. Type inference through `$ref`, `anyOf` or `oneOf` is
|
||
not added by this rule. JSON and both live SSE paths use the same decoder;
|
||
CPU fixtures verify argument equality, not real-model tool-call quality.
|
||
|
||
`control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events.
|
||
|
||
Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. By default the store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB.
|
||
|
||
### Opt-in durable history (Unix preview)
|
||
|
||
Set `response_history_dir` in the serve config or `STRATA_RESPONSE_HISTORY_DIR`
|
||
(environment wins) to an absolute dedicated directory whose parent already exists.
|
||
The service creates it with mode `0700`; an existing directory must be owned by
|
||
its user with exactly that mode. Snapshot and lock files must be owned regular
|
||
`0600` files with one link. Symlinks are refused. An OS lock permits only one
|
||
service to use the directory. `check-config` reports `durable_unchecked` without
|
||
opening, creating or locking it. `provision` also leaves history untouched.
|
||
|
||
This explicitly persists **plaintext input, tool results, and terminal responses**;
|
||
use a private external volume, outside Git. It has the same single-operator API
|
||
key scope as memory history, with no encryption or tenant separation. Changing
|
||
API keys does not erase the store. `store: false` writes nothing. Omitting the
|
||
option retains memory-only behavior. Windows durable storage is not supported.
|
||
|
||
Completed/incomplete responses, expanded continuation transcripts and input-item
|
||
IDs survive service restarts. DELETE and oldest-entry eviction are committed too.
|
||
The existing limits remain 64 responses and 128 MiB of serialized response plus
|
||
transcript data. A versioned snapshot is bounded to 129 MiB including metadata;
|
||
this is not a total resident-memory bound. Each mutation writes a full snapshot
|
||
on a blocking pool, flushes it, atomically renames it and flushes the directory
|
||
before acknowledging success. Budget space for the current and staged snapshots.
|
||
This feature is not a throughput optimization.
|
||
|
||
Startup validates the store before asset preparation, worker or listener startup.
|
||
Invalid schema, SHA-256 checksum mismatch, corruption, insecure files, excess size or an occupied lock fail
|
||
startup without resetting history. An interrupted unpublished stage is discarded
|
||
under the lock; the committed snapshot is restored. Disk failures produce the
|
||
existing `response_storage_failed` JSON error or terminal SSE `response.failed`,
|
||
never a false successful commit. Earlier text deltas may already be visible.
|
||
A failed store fences further mutations until restart; existing in-memory GETs
|
||
remain available. Failure before rename preserves the previous snapshot. Failure
|
||
after rename while flushing the directory has an **uncertain outcome**: the
|
||
request was not acknowledged, but its record can be present after restart.
|
||
A disconnected client can likewise miss an already committed result. DELETE is
|
||
logical deletion, not secure erasure of filesystem blocks or backups.
|
||
No in-progress stream, worker state, KV state or automatic retry is restored.
|
||
|
||
|
||
Before switching the testing runtime, exercise all engine stop conditions and tool calls with the real tokenizer and model on Linux GPU, and compare sanitized real Codex replays against the upstream Python server. Native reasoning now has its own output items, streaming events and continuation path. Do not mark Gate A complete based on synthetic fixtures.
|
||
|
||
## Engine prefix metadata
|
||
|
||
The engine's `RESUME <n>` and `REUSED <n>` lines are validated as nonnegative
|
||
prefix counts and treated as nonterminal metadata. Usage counters come from
|
||
`DONE`. These lines must not fail or finish a generation; unknown wire tags
|
||
and malformed counts still fail the protocol.
|
||
|
||
## Stored response resources
|
||
|
||
`GET /v1/responses/{response_id}` returns the exact saved completed or incomplete
|
||
response object, including output, tool call IDs/arguments, reasoning, metadata
|
||
and usage. `DELETE` on the same path returns
|
||
`{"id":"...","object":"response.deleted","deleted":true}` and removes that
|
||
entry's response and continuation transcript. These route shapes follow the
|
||
official OpenAI [retrieve](https://developers.openai.com/api/reference/resources/responses/methods/retrieve)
|
||
and [delete](https://developers.openai.com/api/reference/resources/responses/methods/delete)
|
||
references; the implementation supports the bounded history subset described here.
|
||
|
||
- Both routes share the optional bearer authentication policy. They remain
|
||
available while draining or when the worker is unavailable; they do not invoke
|
||
the model. There is still one operator credential, without tenant isolation.
|
||
- Unknown, deleted, evicted, memory-only restarted and `store:false` IDs return
|
||
`404 response_not_found`. Repeated deletion also returns 404. Failed generations
|
||
are not stored; these routes do not poll or cancel in-progress jobs.
|
||
- Nonempty query strings return `400 unsupported_query`. Retrieval streaming,
|
||
stream resumption and optional include/query fields are not implemented.
|
||
- The shared FIFO limit is 64 entries or **128 MiB of serialized response plus
|
||
transcript data**. Both objects count toward the budget; this is not a process
|
||
RSS cap. Oversized records fail storage before publishing a successful terminal
|
||
response. Eviction removes both objects together; retrieval does not refresh
|
||
retention order. Disk storage is disabled unless explicitly configured above.
|
||
- Deletion prevents subsequent continuation using that ID. It does not erase
|
||
copies already included in descendant responses or an in-flight request that
|
||
obtained the transcript before deletion, and does not cancel generation.
|
||
|
||
These routes require the newer preview; the preserved user trial is unchanged.
|
||
CPU verification: `python3 scripts/smoke-response-history.py /path/to/strata-next`;
|
||
add `--durable` for actual process restart, corruption and disk-failure coverage.
|
||
|
||
### Input item listing
|
||
|
||
`GET /v1/responses/{response_id}/input_items` returns an authenticated list with
|
||
`data`, `first_id`, `last_id`, and `has_more`, following the documented
|
||
[OpenAI input-items route](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_items/methods/list).
|
||
It accepts `order=asc|desc` (default `desc`), `limit=1..100` (default 20), and an
|
||
`after` item cursor. Unknown, duplicate or malformed query options and foreign
|
||
cursors return `400 invalid_input_items_query`; optional `include` is not supported.
|
||
|
||
This is a projection of the stored effective input, including expanded
|
||
`previous_response_id` history and excluding this response's own output.
|
||
Instructions remain a separate request field and are not added to the list.
|
||
Message text is projected into role-appropriate typed text parts. List item IDs identify occurrences
|
||
within this response and remain stable while it is retained; they replace
|
||
client item IDs in this view so duplicate IDs cannot make pagination ambiguous.
|
||
Tool `call_id`, name, namespace, arguments and custom input are unchanged.
|
||
The transcript used to render subsequent model prompts is never modified.
|
||
|
||
The route shares the configured history retention, deletion and authentication
|
||
policy. It works during drain/worker outage without generating tokens. Missing,
|
||
`store:false`, deleted and evicted responses return 404. Restart clears default
|
||
memory history; the opt-in durable store described above also preserves these
|
||
input pages. No payload logging or tenant isolation is added.
|
||
CPU HTTP coverage includes both response modes, exact tool-payload replay,
|
||
pagination, stable cursors, failure cases and no extra worker generation.
|
||
|
||
## Cancellation failure isolation
|
||
|
||
Dropping a generation receiver sends `STOP` and drains that generation's output
|
||
for at most 20 seconds. Tokens or progress emitted after `STOP` are discarded
|
||
and do not extend the deadline. A terminal line before the deadline permits the
|
||
next queued request. If the worker does not terminate in time, readiness is
|
||
revoked, the process is killed and reaped, and queued receivers are closed.
|
||
The supervisor never reuses an unaligned output stream.
|
||
|
||
Both text and function-call SSE relays observe the HTTP consumer closing even
|
||
while the engine produces no events. They then drop their generation receiver
|
||
so cancellation reaches the supervisor immediately.
|
||
|
||
A sanitized shell worker that consumes `STOP` without reporting `DONE` covers
|
||
this failure path. This regression does not qualify full-model soak stability.
|
||
|
||
## Worker recovery policy
|
||
|
||
After a failure of a worker that previously sent `READY`, the supervisor can
|
||
start a fresh process. The default lifetime budget is three restarts, with
|
||
delays of 2, 4 and 8 seconds. Set `engine.max_restarts` in the JSON config or
|
||
`STRATA_MAX_WORKER_RESTARTS` to an integer from 0 through 3; zero disables
|
||
recovery. Environment overrides the file. Successful requests do not replenish
|
||
the lifetime budget. Initial or replacement startup failure stops recovery.
|
||
|
||
An active failed generation is not retried. Queued commands are failed during
|
||
recovery; requests arriving while restarting or starting are rejected. The
|
||
worker reports `restarting` during backoff, then `starting`, with no context or
|
||
readiness until a new positive `READY` handshake. Shutdown interrupts backoff.
|
||
After the lifetime budget is exhausted, the runtime must be restarted by its
|
||
operator. A real-model reload has passed; sustained soak remains open.
|
||
|
||
## Live structured text
|
||
|
||
Requests may select `text.format.type` as
|
||
`json_object` or `json_schema`. The runtime adds JSON-format instructions and,
|
||
for schemas, the schema itself to the model prompt. Invalid schemas and external
|
||
references are rejected before worker admission. Completed text must parse as
|
||
an object and, in schema mode, pass the supplied schema. The same validation
|
||
applies with `strict` true, false, or omitted. This implementation uses prompt
|
||
guidance and final validation; it does not yet constrain next-token sampling
|
||
with a JSON grammar and cannot guarantee successful generation for every schema.
|
||
|
||
JSON requests return HTTP 502 if completed model output fails validation.
|
||
Structured SSE sends `response.created` / `response.in_progress` immediately,
|
||
then buffers output until engine DONE. Valid output is emitted with the normal
|
||
item/text/terminal events. Invalid completed output emits `response.failed`
|
||
without publishing text or function-call items. This buffering trades token-by-
|
||
token structured output for validation before publication. Plain text streaming
|
||
is unchanged. Disconnect still cancels the active generation while buffering.
|
||
|
||
A token-budget stop returns `response.incomplete` with
|
||
`incomplete_details.reason: "max_output_tokens"`; its partial text may be invalid
|
||
JSON and must not be treated as a schema-valid completed result. Tool-only turns
|
||
remain valid: their arguments are checked against the tool schema, while the
|
||
text format applies to the eventual answer after tool results. History stores
|
||
successful and incomplete responses, never schema-failed responses.
|
||
|
||
Example format:
|
||
|
||
```json
|
||
{"text":{"format":{"type":"json_schema","name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}}
|
||
```
|
||
|
||
The field names and incomplete-result handling follow the
|
||
[OpenAI structured output contract](https://developers.openai.com/api/docs/guides/structured-outputs).
|
||
Recorded Codex/MCP replay remains a separate milestone.
|
||
|
||
## Native Qwen reasoning
|
||
|
||
`reasoning.effort` accepts `none`, `low`, `medium`, `high`, or `xhigh`.
|
||
Omitted/null effort uses upstream's `xhigh` default. The pinned model template
|
||
maps `high` to its xhigh instruction; `none` closes the thinking block in the
|
||
prompt. Effort is a template instruction, not a separate token budget.
|
||
`max_output_tokens` includes both reasoning and answer tokens.
|
||
|
||
Generated reasoning is returned as an output item with `type: "reasoning"`,
|
||
`content: [{"type":"reasoning_text","text":"..."}]` and `summary: []`.
|
||
SSE emits `response.reasoning_text.delta` during generation, followed by its
|
||
text/content/item done events and the normal answer or function-call events.
|
||
The current reasoning path buffers the final answer/tool items until DONE;
|
||
structured answers are validated before publication. `effort: none` plain-text
|
||
and tool streaming retain their incremental behavior. Disconnect during
|
||
reasoning cancels the worker generation.
|
||
|
||
The first Qwen `</think>` marker separates reasoning from answer text, even
|
||
when split over tokens. A normal stop without that marker fails; a token-budget
|
||
stop while thinking returns an incomplete reasoning item and no invented final
|
||
answer. `usage.output_tokens_details.reasoning_tokens` counts original emitted
|
||
tokens up to and including the closing-marker token; if one token straddles the
|
||
boundary it is assigned to reasoning. Truncated thinking counts all its tokens.
|
||
EOS tokens remain in total output usage, not reasoning usage.
|
||
|
||
Stored continuation and stateless replay preserve raw reasoning alongside
|
||
assistant messages/tool calls in the Qwen template. Reasoning-only incomplete
|
||
turns can precede a new user message. Summary-only and encrypted reasoning
|
||
cannot reconstruct this local model's raw context and are rejected explicitly.
|
||
`reasoning.summary: "auto"` or null is accepted, but no summarizer is implemented:
|
||
summary remains empty, and raw text is never mislabeled as a summary. Explicit
|
||
`concise`/`detailed` summaries are unsupported.
|
||
|
||
The reasoning content and event shapes follow the
|
||
[Responses raw-reasoning extension](https://developers.openai.com/cookbook/articles/gpt-oss/handle-raw-cot).
|
||
This local Qwen implementation does not provide OpenAI encrypted reasoning.
|
||
|
||
## Console request compatibility
|
||
|
||
The native route accepts the console's `include`, `prompt_cache_key`, and
|
||
string-valued `client_metadata` fields. It also accepts, validates and ignores the hosted-service hints a Codex
|
||
configuration may add: `service_tier` (`auto`, `default`, `flex`, `priority`, `scale`), `user`, `text.verbosity` (`low`,
|
||
`medium`, `high`; `text.format` may then be absent and means plain text), `reasoning.effort: minimal` (served as `low`, the template's
|
||
brief-thinking instruction) and `reasoning.summary: none`. Still refused: `concise`/`detailed` summaries, `max_tool_calls`,
|
||
other `include` values and unknown fields. Only `reasoning.encrypted_content` is
|
||
accepted in `include`: it is an optional inclusion hint, and this runtime still
|
||
returns **raw reasoning content, not encrypted content**. Metadata is not added
|
||
to the model prompt or persisted by the runtime. The cache key is a routing hint;
|
||
it does not partition the single worker's token-verified prefix cache.
|
||
|
||
Function namespaces are lowered to deterministic, collision-checked aliases for
|
||
the Qwen template. Output items retain the original function `name` and
|
||
`namespace`, and replay uses the same alias even for historical functions no
|
||
longer advertised. Duplicate identities, alias collisions, nested namespaces,
|
||
custom/free-form tools, and server-side web search are rejected. Typed argument
|
||
validation applies after namespace lowering on both JSON and SSE paths.
|
||
`function_call_output.output` accepts text or an array of `input_text` parts;
|
||
parts are joined with a newline. Image/file parts remain unsupported.
|
||
|
||
When `max_output_tokens` is omitted, generation reserves up to 32,768 tokens,
|
||
limited by the remaining context minus the worker's eight-token margin. An
|
||
explicit output limit is preserved. Configuring `model` (or `STRATA_MODEL_ID`)
|
||
exposes that identity in `/status` and rejects requests for another model.
|
||
An omitted configured identity preserves the earlier single-worker API behavior.
|
||
|
||
The opt-in console integration is installed with
|
||
`python3 scripts/install-qwen-native.py`. It adds the `strata-native` backend to
|
||
`qwen-codex-ctl` and uses a direct Responses provider in `qwen-codex`. This path
|
||
has no Python serving bridge. The launcher itself remains a local convenience
|
||
script. Existing selections remain unchanged, and an installation backup is
|
||
retained. `QWEN_CODEX_PROFILE` selects a separate console profile for tests.
|
||
|
||
The native preview requires a loopback connection (an SSH tunnel for a remote
|
||
GPU). Optional bearer authentication is described below; it does not add TLS.
|
||
Native discovery uses
|
||
`/status`, requires a configured model identity and a ready 256K worker, and does
|
||
not synthesize legacy `/props` or `/slots`. `stop` refuses to operate on this
|
||
externally managed runtime; `logs` identifies its host-side logs.
|
||
|
||
### Optional bearer authentication
|
||
|
||
Set `api_key_file` in the server JSON configuration or `STRATA_API_KEY_FILE`
|
||
(takes precedence) to enable one operator credential. The source must be a
|
||
regular private file (no group/other permissions on Unix), containing 32–512
|
||
printable ASCII bytes without whitespace; an optional trailing LF/CRLF is
|
||
accepted. Total file size is bounded at 514 bytes. Invalid/missing sources fail
|
||
startup before binding or launching the engine. FIFO sources fail without
|
||
blocking. Without a configured file, previous authentication-free behavior is
|
||
unchanged; the existing trial remains in that mode on loopback.
|
||
|
||
All routes except minimal `/health` require `Authorization: Bearer TOKEN`.
|
||
Missing, wrong, malformed or repeated Authorization headers return a generic
|
||
401 `invalid_api_key` and `WWW-Authenticate: Bearer` before request parsing.
|
||
`/status` and `/ready` are protected as well. No supplied credential is echoed.
|
||
The server's retained credential state is a SHA-256 digest, compared using
|
||
`subtle::ConstantTimeEq`; the key is never sent to the engine. This is one shared
|
||
operator credential, not multi-user authorization or response-history isolation.
|
||
Changing the key requires a deliberate server restart; hot rotation is not
|
||
implemented.
|
||
|
||
Rerun `scripts/install-qwen-native.py` to upgrade an existing native launcher;
|
||
fresh installs also include key-file support. Then an authenticated endpoint can
|
||
be selected with `qwen-codex-ctl connect strata-native --url LOOPBACK_URL
|
||
--key-file PRIVATE_FILE`. Discovery validates file permissions and uses the
|
||
credential header. Agent launch configures `/bin/cat` as the provider's auth
|
||
command, with only the absolute key-file path in its arguments. The token is
|
||
not written to launcher argv, environment or generated configuration. Existing
|
||
`--no-auth` connections and `native-service` commands remain unchanged.
|
||
|
||
Approval/review requests can append developer messages after user input. The
|
||
native adapter stably coalesces these instruction messages into the leading
|
||
Qwen system section, preserving their content and order. It does not demote
|
||
approval instructions to user messages or bypass the console's review step.
|
||
|
||
Stateless replay keeps adjacent assistant commentary and function calls in one
|
||
assistant turn, with their reasoning content attached. The commentary-to-call
|
||
separator matches the pinned Qwen template, including trimming commentary's
|
||
trailing whitespace. The sanitized `commentary-tool-prompt.json` fixture checks
|
||
this against an independently rendered upstream template, byte for byte.
|
||
|
||
Parallel tool outputs are matched by `call_id` and replayed in their original
|
||
call order. Qwen's tool-response markup has no ID field, so retaining arrival
|
||
order would swap results when parallel tools finish in another order. A
|
||
regression checks that ordered and reversed delivery produce identical prompts.
|
||
|
||
An omitted `temperature` uses the engine's greedy default (`0`), and response
|
||
metadata reports `0`. Explicit temperature values are preserved. This reflects
|
||
the existing engine protocol rather than changing sampling for console runs.
|
||
|
||
## Custom text tools
|
||
|
||
Native Responses accepts `{"type":"custom","name":"run"}` with an optional
|
||
string description and optional `"format":{"type":"text"}`. Namespace
|
||
containers may include custom tools. Regex format has the validation-only
|
||
preview described below. Lark, unknown custom fields and non-text outputs are
|
||
explicitly rejected. `tool_choice` supports `auto`, `none`, `required`, `allowed_tools`, and forced top-level custom
|
||
tools; see [Tool choice and call count](#tool-choice-and-call-count).
|
||
|
||
Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and
|
||
optional `namespace`; they never expose the internal JSON `arguments` wrapper.
|
||
SSE uses `response.custom_tool_call_input.delta` and
|
||
`response.custom_tool_call_input.done`, bracketed by the normal output-item
|
||
events. The names and public fields follow the official
|
||
[custom tools contract](https://developers.openai.com/api/docs/guides/function-calling)
|
||
and [streaming events](https://developers.openai.com/api/reference/resources/responses/streaming-events).
|
||
|
||
Internally, the Qwen template receives a function with one required string
|
||
parameter named `input`. Its complete envelope is validated before a callable
|
||
item is published. The public input is unwrapped without trimming or interpreting
|
||
its contents. This uses the engine's existing tool markup and its delimiter
|
||
limitations; it adds no grammar-constrained decoding. In ordinary text streaming,
|
||
validated complete calls can appear before engine DONE. Reasoning/structured
|
||
paths retain their existing buffering rules.
|
||
|
||
Replay accepts `custom_tool_call_output` with a string or `input_text` parts,
|
||
including `previous_response_id` continuation. Call IDs, namespace identities
|
||
and function/custom output kinds must remain paired; mixed parallel outputs
|
||
are reordered by call order. No custom tool is executed by the runtime.
|
||
|
||
CPU fixtures verify transport and replay, including multiline Unicode and
|
||
whitespace, with exact equality. Real-model custom-tool quality and constrained
|
||
sampling remain unqualified; the existing GPU user trial has not been upgraded.
|
||
|
||
### Regex custom input validation preview
|
||
|
||
The native preview also accepts
|
||
`"format":{"type":"grammar","syntax":"regex","definition":"[0-9]+"}`.
|
||
The request shape and Rust regex dialect follow the official
|
||
[Regex CFG documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg).
|
||
Strata provides prompt guidance and complete-input validation; it does **not**
|
||
constrain token sampling. A mismatch fails the response rather than repairing
|
||
or retrying the call. This distinction applies to this preview even though the
|
||
wire format uses `grammar`.
|
||
|
||
The entire input must match, including whitespace and Unicode; a substring match
|
||
is insufficient. Valid input is returned byte-for-byte. A completed call is
|
||
validated before its item-added, input delta or done events. Invalid input
|
||
produces a JSON generation failure or terminal `response.failed`; no callable
|
||
item for that invalid call is published. Earlier valid calls/text in a stream
|
||
cannot be retracted. Namespace lowering and continuation preserve their existing
|
||
identities and exact inputs. Replayed historical calls are not revalidated under
|
||
new tool definitions.
|
||
|
||
Definitions must be nonempty single-line strings, at most 8192 bytes; use escaped
|
||
`\n` to match newlines. Each request allows at most 32 regex tools and 64 KiB of
|
||
definitions, including namespaced tools. Each compiled regex and DFA cache has a
|
||
1 MiB limit; AST nesting is limited to 64. Lookarounds, backreferences, lazy
|
||
repetitions, verbose (`x`) and swap-greed (`U`) flags are rejected before inference,
|
||
as are malformed/unknown format fields and Lark. These are compilation/cache
|
||
bounds, not a total runtime memory or latency guarantee. Existing unformatted
|
||
and explicit text custom tools retain their semantics.
|
||
|
||
## Tool choice and call count
|
||
|
||
`tool_choice` omitted or `"auto"` preserves automatic tool selection.
|
||
`"none"` hides current tool declarations from the prompt and prevents any
|
||
generated callable item from being published. Declarations are still validated,
|
||
response metadata preserves the caller's tools/choice, and historical calls and
|
||
results remain in the replay transcript. Literal text that resembles tool markup
|
||
with no declared tools remains text, as in the existing no-tools path.
|
||
|
||
`parallel_tool_calls: false` permits zero or one function/custom call per
|
||
response, across all namespaces. Prompt guidance asks for at most one call;
|
||
the server enforces the count. Default/true permits multiple calls. These wire
|
||
semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice).
|
||
|
||
`"required"` requires at least one function/custom call at successful completion.
|
||
It needs a nonempty callable catalog (400 otherwise); together with
|
||
`parallel_tool_calls: false` it requires exactly one call. Namespaced calls
|
||
participate in the same count.
|
||
|
||
`{"type":"function","name":"lookup"}` forces exactly one call to the declared
|
||
top-level function `lookup`, regardless of the parallel flag. Missing/unknown
|
||
names, custom tools selected as functions and extra selector fields fail with
|
||
400 before inference. A name is never treated as an internal namespace alias.
|
||
`{"type":"custom","name":"patch"}` likewise forces exactly one declared
|
||
top-level custom tool. Its text input is restored without modification; an
|
||
optional supported regex format is still validated before publication. The
|
||
selector must match the original tool's type, not its internal function lowering.
|
||
This [official custom selector example](https://developers.openai.com/cookbook/examples/partners/aws/openai_models_with_amazon_bedrock#44-use-a-custom-text-tool)
|
||
uses the same type/name shape. Forced namespaced selectors remain unsupported.
|
||
Unsupported choice kinds return 501; no choice is silently replaced with auto.
|
||
|
||
`{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"lookup"}]}`
|
||
restricts new calls to a subset of declared top-level function/custom tools.
|
||
`mode: "required"` also requires at least one allowed call on successful
|
||
completion, as specified in the official [allowed-tools mode schema](https://github.com/openai/openai-python/blob/main/src/openai/types/responses/tool_choice_allowed_param.py).
|
||
The full declarations and historical calls/results remain in the prompt and
|
||
response metadata. Prompt guidance identifies the subset; the server rejects
|
||
disallowed calls before publishing their item or input/argument events.
|
||
This does not guarantee prompt-cache reuse or model compliance.
|
||
|
||
The envelope accepts exactly `type`, `mode`, and `tools`; each selector accepts
|
||
exactly `type` and `name` matching its original declaration. Missing fields,
|
||
unknown names, wrong types, duplicate selectors, namespaced/internal aliases,
|
||
built-in tool selectors and extra fields return 400 before generation.
|
||
An empty auto subset permits text only; an empty required subset is rejected.
|
||
Multiple allowed calls are permitted unless `parallel_tool_calls: false`.
|
||
|
||
These policies add prompt guidance while retaining declarations and history.
|
||
Their minimum count applies only to successful completion: a token-limit
|
||
`incomplete` response may contain no complete call. Wrong names and excessive
|
||
counts remain invalid even for incomplete responses. Initial streaming envelopes
|
||
are not subjected to a completion minimum. Original choice metadata is echoed.
|
||
|
||
Buffered output that violates the policy fails with 502 before any callable
|
||
output is returned. In ordinary live SSE, a first valid call may already have
|
||
been published: a second call is rejected before its item/argument/input events,
|
||
and the stream ends with `response.failed`. Forced choice rejects a wrong first
|
||
call before publishing it; required choice with zero calls fails at completion.
|
||
Under none, no callable item is
|
||
published. Earlier valid text/calls cannot be retracted. Reasoning/structured
|
||
paths keep their existing buffering behavior. The runtime does not truncate,
|
||
repair or retry tool calls; these policies do not implement constrained sampling
|
||
or parallel GPU requests.
|
||
|
||
## Active generation deadline
|
||
|
||
An operator can opt into `engine.generation_timeout_s` /
|
||
`STRATA_GENERATION_TIMEOUT_S` (1–86400 seconds, absent means disabled).
|
||
The deadline covers an active command, including worker pipe and result-channel
|
||
backpressure. It excludes request parsing, tokenization and command queue wait.
|
||
It is an absolute execution budget, not an idle-token timer or client end-to-end
|
||
deadline. Timeout fails the worker, kills/reaps it and uses the existing finite
|
||
restart policy. No active or queued request is replayed.
|
||
|
||
For a connected client consuming its response, buffered requests return 502
|
||
`generation_failed` with `generation exceeded configured execution deadline`;
|
||
SSE ends in `response.failed`, retaining its preceding event sequence. The
|
||
generation counts once as failed/interrupted. Failure delivery after process
|
||
cleanup is bounded to one second; a full streaming channel is then closed,
|
||
and the adapter emits a failure once the consumer drains buffered events.
|
||
Delivery cannot be guaranteed to a disconnected/non-reading client. This setting
|
||
does not replace HTTP/proxy timeouts. The default leaves existing long-context
|
||
generation behavior unchanged.
|
||
|
||
## Admission lifecycle
|
||
|
||
`POST /admin/drain`, `POST /admin/resume` and `GET /admin/lifecycle` expose the
|
||
native [maintenance drain protocol](../deploy/README.md#drain-before-maintenance).
|
||
They use the existing optional bearer gate. During drain, new Responses
|
||
requests fail with 503 `runtime_draining` before request-body validation;
|
||
previously admitted work continues. `/ready` returns 503 and `/status.ready`
|
||
becomes false. Response protocol events and worker output remain unchanged.
|
||
|
||
The configured `max_in_flight_requests` (default 17, range 1–256, overridden by
|
||
`STRATA_MAX_IN_FLIGHT_REQUESTS`) bounds concurrent POST Responses handlers before
|
||
JSON parsing or tokenization. A request holds capacity through response-body
|
||
completion/drop. When full, additional POST requests receive HTTP 429,
|
||
`Retry-After: 1`, and error code `runtime_overloaded`. Authentication runs first;
|
||
drain's 503 takes precedence over overload. Transient overload does not change
|
||
readiness. Health, management and stored-response GET/DELETE remain accessible.
|
||
Lifecycle reports `max_in_flight_requests` and `available_request_slots` (capacity
|
||
minus tracked requests, independent of drain mode); `check-config` reports the
|
||
configured maximum.
|
||
|
||
This bounds HTTP inference handlers, not GPU slots or generation jobs. The
|
||
worker still executes serially. On disconnect the HTTP guard can be released
|
||
while a generation's separate guard waits for STOP cleanup. This is not a cap
|
||
on TCP connections, total process memory, or GPU memory, and does not implement
|
||
batching. Admitted requests retain the existing queue and response semantics.
|
||
|
||
### Signal shutdown grace
|
||
|
||
Top-level `shutdown_grace_s`, overridden by `STRATA_SHUTDOWN_GRACE_S`, accepts
|
||
integer seconds 0–20; default 0 preserves immediate worker interruption.
|
||
`check-config` reports the effective value. With positive grace, SIGTERM/SIGINT
|
||
sets irreversible admission drain, makes readiness false and waits for both
|
||
tracked HTTP requests and generation jobs to reach zero, up to the deadline.
|
||
Already admitted requests can enqueue and finish during this interval. New
|
||
requests receive 503 `runtime_draining` while the listener remains open.
|
||
|
||
Lifecycle adds `shutting_down`. After a signal, `/admin/resume` returns the
|
||
current lifecycle with both `shutting_down` and `draining` true; it cannot reopen
|
||
admission. Ordinary administrative drain/resume remains reversible. The wait
|
||
ends early when both counters clear (checked every 25 ms), or on expiry proceeds
|
||
to existing worker interruption/QUIT and HTTP shutdown. A signal does not imply
|
||
that every request will finish: expiry can produce failed responses.
|
||
|
||
This setting bounds the admission drain phase only. Worker/process and HTTP
|
||
connection cleanup follow it. The rendered systemd unit retains its 45-second
|
||
hard stop; the 20-second grace cap reserves time for worker cleanup. Standalone
|
||
execution has no new overall exit deadline. For longer maintenance, explicitly
|
||
drain and wait before sending the stop signal.
|
||
|
||
## Runtime backend (text-level engine)
|
||
|
||
With a `runtime` block in the configuration (`control-plane/config.runtime.example.json`) the same Responses, Chat and Messages
|
||
routes run in front of a `leleka-inference` process over the `leleka.runtime.v1` gRPC contract instead of a stdio engine child.
|
||
The engine contract is text in, text out, so the surface differs from the stdio engine in these ways (see
|
||
`docs/api-over-rust-engine.md`): the prompt is sent as the rendered template text after a round-trip check against the token ids
|
||
that were counted; text deltas are re-tokenized for the HTTP layer with a byte-equality check, `<|im_end|>` / `<|endoftext|>`
|
||
end the text and cancel the engine generation, `usage.output_tokens` is the engine's own count and `reasoning_tokens` an
|
||
approximation bounded by it; images, `reasoning_budget_tokens`, `strata_tune` and `experimental_speed_projection` are
|
||
refused with an error; a default `max_output_tokens` is clamped to `runtime.max_output_tokens` (4096, the runtime's cap) and a larger
|
||
explicit value is refused; `/unload` is `unsupported` because the runtime's lifecycle belongs to its operator. A terminal event
|
||
(`response.completed`, `response.incomplete` or `response.failed`) ends every stream, including when the engine dies.
|