Files
leleka/docs/api-contract.md
T
Pavlo Ratushnyi d716dbaf70 Persist opt-in native Responses history across restarts (#16)
* feat: persist opt-in native Responses history across restarts

* fix: retain private snapshot mode under restrictive umask

* docs: clarify optional persistence on resource routes
2026-10-05 01:07:39 +02:00

545 lines
36 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Responses contract status
## 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.
`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. 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.