Add optional active generation execution deadline

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 08:52:18 +02:00
parent e0a92c4714
commit eccfabff66
11 changed files with 397 additions and 13 deletions
+2
View File
@@ -98,6 +98,8 @@ jobs:
run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native drain and resume without GPU
run: python3 scripts/smoke-native-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native generation deadline and recovery without GPU
run: python3 scripts/smoke-generation-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Static CLI HTTP cancellation failure isolation
run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Static CLI HTTP crash recovery without request replay
+13
View File
@@ -37,6 +37,7 @@ struct FileEngine {
#[serde(default)]
args: Vec<String>,
startup_timeout_s: Option<u64>,
generation_timeout_s: Option<u64>,
max_restarts: Option<u32>,
tokenizer_dir: Option<PathBuf>,
}
@@ -103,11 +104,23 @@ impl Config {
if max_restarts > 3 {
return Err("max_restarts must be between 0 and 3".into());
}
let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")?
.map(|value| value.parse::<u64>())
.transpose()?
.or_else(|| {
file.engine
.as_ref()
.and_then(|engine| engine.generation_timeout_s)
});
if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
return Err("generation_timeout_s must be between 1 and 86400".into());
}
let worker = match executable {
Some(executable) if !executable.is_empty() => Some(WorkerConfig {
executable,
args,
startup_timeout: Duration::from_secs(startup_timeout_s),
generation_timeout: generation_timeout_s.map(Duration::from_secs),
max_restarts,
}),
Some(_) => return Err("engine executable cannot be empty".into()),
+1
View File
@@ -37,6 +37,7 @@ pub fn check(path: Option<&Path>) -> Result<serde_json::Value, &'static str> {
"platform": std::env::consts::OS,
"bind": config.bind.to_string(),
"max_in_flight_requests": config.max_in_flight_requests,
"generation_timeout_s": config.worker.as_ref().and_then(|worker| worker.generation_timeout.map(|duration| duration.as_secs())),
"model": config.model,
"authentication_enabled": config.api_key.is_some(),
"engine": engine,
+2
View File
@@ -3400,6 +3400,7 @@ mod tests {
expert_lookups: None,
}));
match command.result {
GenerationResult::Finished => panic!("fixture received finished command"),
GenerationResult::Buffered(sender) => {
sender.send(Ok(events)).unwrap();
}
@@ -3642,6 +3643,7 @@ mod tests {
expert_lookups: None,
}));
match command.result {
GenerationResult::Finished => panic!("fixture received finished command"),
GenerationResult::Buffered(sender) => {
sender.send(Ok(events)).unwrap();
}
+123 -13
View File
@@ -21,13 +21,19 @@ pub struct GenerationCommand {
pub enum GenerationResult {
Buffered(oneshot::Sender<Result<Vec<Event>, String>>),
Streaming(mpsc::Sender<Result<Event, String>>),
Finished,
}
impl GenerationResult {
fn take(&mut self) -> Self {
std::mem::replace(self, Self::Finished)
}
fn is_closed(&self) -> bool {
match self {
Self::Buffered(sender) => sender.is_closed(),
Self::Streaming(sender) => sender.is_closed(),
Self::Finished => true,
}
}
@@ -35,6 +41,7 @@ impl GenerationResult {
match self {
Self::Buffered(sender) => sender.closed().await,
Self::Streaming(sender) => sender.closed().await,
Self::Finished => {}
}
}
@@ -77,6 +84,7 @@ pub struct WorkerConfig {
pub executable: OsString,
pub args: Vec<String>,
pub startup_timeout: Duration,
pub generation_timeout: Option<Duration>,
pub max_restarts: u32,
}
@@ -256,11 +264,26 @@ async fn run_session(
// including STOP/QUIT and failed-process termination.
let _activity = command.activity.take();
tokio::select! {
result = generate(&mut stdin, &mut lines, command, max_context, status) => {
(timed_out, result) = async {
let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status);
match config.generation_timeout {
Some(duration) => match timeout(duration, generation).await {
Ok(result) => (false, result),
Err(_) => (true, Err("generation exceeded configured execution deadline".to_owned())),
},
None => (false, generation.await),
}
} => {
if let Err(error) = result {
eprintln!("Strata engine protocol failed: {error}");
update(status, WorkerState::Failed, None).await;
terminate(&mut child, &mut stdin).await;
// A full streaming channel must not delay process cleanup
// or finite restart indefinitely. Closing it also signals
// failure to the response adapter once buffered tokens drain.
if timed_out {
let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await;
}
return SessionExit::RuntimeFailed;
}
}
@@ -281,7 +304,7 @@ async fn run_session(
async fn generate(
stdin: &mut Option<ChildStdin>,
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
mut command: GenerationCommand,
command: &mut GenerationCommand,
max_context: usize,
status: &RwLock<WorkerStatus>,
) -> Result<(), String> {
@@ -295,7 +318,7 @@ async fn generate(
.is_some_and(|total| total <= max_context);
if !fits_context {
send_failure(
command.result,
command.result.take(),
"prompt, output budget, and 8-token margin exceed context".to_owned(),
)
.await;
@@ -304,7 +327,7 @@ async fn generate(
let request = match command.request.line() {
Ok(line) => line,
Err(error) => {
send_failure(command.result, error.to_owned()).await;
send_failure(command.result.take(), error.to_owned()).await;
return Ok(());
}
};
@@ -337,18 +360,16 @@ async fn generate(
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
status.write().await.metrics.fail();
send_failure(command.result, message).await;
send_failure(command.result.take(), message).await;
return Ok(());
}
Some(event @ Event::Done(_)) => {
if let Event::Done(done) = &event {
status
.write()
.await
.metrics
.finish(done, stopped || command.result.is_closed());
}
match command.result {
let Event::Done(done) = &event else {
unreachable!()
};
let done = done.clone();
let disconnected = stopped || command.result.is_closed();
match command.result.take() {
GenerationResult::Buffered(sender) => {
events.push(event);
let _ = sender.send(Ok(events));
@@ -356,13 +377,16 @@ async fn generate(
GenerationResult::Streaming(sender) => {
let _ = sender.send(Ok(event)).await;
}
GenerationResult::Finished => {}
}
status.write().await.metrics.finish(&done, disconnected);
return Ok(());
}
Some(_) if stopped => {}
Some(event) => match &command.result {
GenerationResult::Buffered(_) => events.push(event),
GenerationResult::Streaming(_) => command.result.send_event(event).await,
GenerationResult::Finished => {}
},
None => {}
}
@@ -377,6 +401,7 @@ async fn send_failure(result: GenerationResult, message: String) {
GenerationResult::Streaming(sender) => {
let _ = sender.send(Err(message)).await;
}
GenerationResult::Finished => {}
}
}
@@ -442,6 +467,7 @@ mod tests {
executable: script,
args: vec![mode.to_owned()],
startup_timeout: Duration::from_secs(timeout_s),
generation_timeout: None,
max_restarts: 0,
}
}
@@ -459,6 +485,90 @@ mod tests {
.expect("worker state transition");
}
#[tokio::test]
async fn execution_deadline_covers_blocked_engine_stdin() {
let mut config = fixture_config("blocked-input", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result, received) = oneshot::channel();
requests
.send(GenerationCommand {
activity: None,
request: Generate {
token_ids: vec![10000; 200000],
max_new: 1,
temperature: None,
top_p: None,
},
result: GenerationResult::Buffered(result),
})
.await
.unwrap();
let error = timeout(Duration::from_secs(5), received)
.await
.unwrap()
.unwrap()
.unwrap_err();
assert_eq!(error, "generation exceeded configured execution deadline");
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
}
#[tokio::test]
async fn execution_deadline_covers_full_stream_channel_and_releases_activity() {
let mut config = fixture_config("flood", 5);
config.generation_timeout = Some(Duration::from_millis(100));
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (_stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(2);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
requests_rx,
));
wait_for(&status, WorkerState::Ready).await;
let lifecycle = crate::lifecycle::Lifecycle::default();
let (events, mut received) = mpsc::channel(1);
requests
.send(GenerationCommand {
activity: Some(lifecycle.generation()),
request: Generate {
token_ids: vec![10],
max_new: 100,
temperature: None,
top_p: None,
},
result: GenerationResult::Streaming(events),
})
.await
.unwrap();
// Do not read until the worker exits: channel backpressure must not mask timeout.
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Failed);
assert_eq!(status.read().await.metrics.failed_or_interrupted, 1);
assert_eq!(status.read().await.metrics.completed, 0);
assert_eq!(lifecycle.snapshot().generation_jobs, 0);
assert!(matches!(received.recv().await, Some(Ok(Event::Token(31)))));
assert!(received.recv().await.is_none());
}
#[tokio::test]
async fn ready_requires_handshake_and_shutdown_sends_quit() {
let status = Arc::new(RwLock::new(WorkerStatus::default()));
+9
View File
@@ -30,6 +30,15 @@ case "$2" in
esac
done
;;
blocked-input)
printf 'READY 262144 stop\n'
exec sleep 30
;;
flood)
printf 'READY 262144 stop\n'
IFS= read -r line || exit 3
while :; do printf 'T 31\n'; done
;;
cancel)
printf 'READY 262144 stop\n'
while IFS= read -r line; do
+15
View File
@@ -23,6 +23,21 @@ worker handshake completes. A startup failure or an exhausted budget leaves
the service unhealthy for inference until an operator restarts it; `/health`
remains available. See [the API contract](../docs/api-contract.md).
An optional `engine.generation_timeout_s` (or `STRATA_GENERATION_TIMEOUT_S`)
sets an absolute active-command deadline, 1–86400 seconds. It is **disabled
when omitted**. Select a budget that accommodates the model's longest prefill
and output. The clock starts when the worker takes the command; HTTP parsing,
tokenization and queue wait are excluded. Engine stdin writes, reading tokens
and waiting on the streaming channel are included. Native `check-config`
reports this value, or null when disabled/unconfigured.
On expiry the supervisor revokes readiness and kills/reaps that worker rather
than attempting to reuse its unfinished protocol stream. The failed command
and queued work are never replayed. The existing finite restart budget applies;
model loading and caches must be rebuilt after restart. With zero restarts the
worker remains failed. Connected clients receive the terminal failure described
in [the API contract](../docs/api-contract.md#active-generation-deadline).
## Native Linux service lifecycle
`strata-next service-unit` renders a **systemd user unit** to stdout. It does
+20
View File
@@ -313,6 +313,26 @@ CPU fixtures verify transport and replay, including multiline Unicode and
whitespace, with exact equality. Real-model custom-tool quality and grammar
support remain unqualified; the existing GPU user trial has not been upgraded.
## 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
@@ -0,0 +1,56 @@
# Optional active-generation deadline — STRA-29
Date: 2026-10-04. The control plane supports an operator-selected absolute
execution deadline through `engine.generation_timeout_s` or
`STRATA_GENERATION_TIMEOUT_S`, integer 1–86400 seconds. Omission leaves it
disabled. Native preflight reports the effective value. The clock covers the
active worker command, including blocked stdin and result-channel backpressure;
it excludes parsing, tokenization and queue wait.
Timeout revokes readiness and kills/reaps the worker before bounded failure
delivery and the existing finite restart policy. Neither the interrupted request
nor queued work is replayed. A consuming client receives JSON 502
`generation_failed` or terminal SSE `response.failed`. See the
[API contract](../api-contract.md#active-generation-deadline) for slow-client
delivery limits and [deployment notes](../../deploy/README.md#worker-recovery).
## Verification
- Rust 1.99.0: full 137-test library suite passed, including the new full-channel
deadline test. The subsequently added blocked-stdin regression and full-channel
test both passed together (138 distinct library tests now present). Clippy
all-targets with warnings denied, fmt and diff checks passed.
- The blocked-stdin test sends a command larger than pipe capacity to an engine
that does not read. Its 100 ms deadline yields explicit failure and a failed
worker. The full-channel test does not consume tokens until the supervisor
exits: cleanup still completes, failure counts once, generation activity is
released, and the channel closes after its buffered token. These are timeout
acceptance tests, not speed measurements.
- `smoke-generation-deadline.py` passed four HTTP cases on macOS debug and Linux
x86_64 musl release: streaming/non-streaming crossed with restart budget 0/1.
Every stalled command terminates with failure, original PID is gone, readiness
is revoked, queued work is not executed, and generation activity returns to zero.
Restart-enabled cases serve a fresh request with exact output `OK` (zero text
tolerance). SSE event numbering stays contiguous without a completed event.
- `smoke-config-check.py` passed 35 cases on each platform, including absent
deadline, valid 1/86400 bounds, invalid 0/86401, JSON configuration and environment
precedence. The new HTTP smoke is wired into Linux CI; hosted Actions has not run.
- A first development run exposed changed crash-channel semantics; failure
delivery was restricted to deadline expiry, and the original crash/no-replay
regression then passed in the full suite. Existing cancellation and shutdown
tests also pass with deadlines disabled.
Private preview:
`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-deadline-preview`,
**17,437,920 bytes**, SHA-256
`11b427c42e27cc1492770075bc970f9ad480d9644f6a17d7ab9352d3b80815a5`.
Source revision and checks are recorded in adjacent private JSON. The isolated
remote fixture directory and release intermediates were removed; the final
artifact remains private. The user's GPU trial remained PID 4031422/start ticks
558428413, with the existing tunnel returning ready; no inference or management
mutation was sent to it.
No real-model deadline budget, speed improvement or long-term stability claim is
made. A timeout deliberately loses that worker's caches and may reload the model.
This feature is ready for QA, not independently approved or installed over the
qualified user trial.
+12
View File
@@ -66,6 +66,18 @@ def main():
assert result['engine'] == 'external' and result['inference_configured']
assert result['tokenizer_validated']
assert result['max_in_flight_requests'] == 2
assert result['generation_timeout_s'] is None
for seconds in [1, 86400]:
assert run({'STRATA_GENERATION_TIMEOUT_S': str(seconds)})['generation_timeout_s'] == seconds
for seconds in [0, 86401]:
run({'STRATA_GENERATION_TIMEOUT_S': str(seconds)}, success=False, expected_error='configuration or API key')
config.write_text(json.dumps({**base, 'engine': {**base['engine'], 'generation_timeout_s': seconds}}))
run(success=False, expected_error='configuration or API key')
assert run({'STRATA_GENERATION_TIMEOUT_S': '1'})['generation_timeout_s'] == 1
config.write_text(json.dumps(base))
config.write_text(json.dumps({**base, 'engine': {**base['engine'], 'generation_timeout_s': 30}}))
assert run()['generation_timeout_s'] == 30
config.write_text(json.dumps(base))
for capacity in [1, 256]:
assert run({'STRATA_MAX_IN_FLIGHT_REQUESTS': str(capacity)})['max_in_flight_requests'] == capacity
for capacity in [0, 257]:
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""CPU-only HTTP execution deadline, no replay, and recovery acceptance."""
import concurrent.futures
import http.client
import importlib.util
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import tempfile
import time
def exercise(binary, fixture, streaming, restarts):
with tempfile.TemporaryDirectory(prefix='strata-deadline-http-') as directory:
root = Path(directory)
fixture.tokenizer(root)
engine = root / 'engine.sh'
engine.write_text('''#!/bin/sh
printf '%s\\n' "$$" >> "$2/pids"
if [ -e "$2/booted" ]; then recovered=1; else recovered=0; fi
: > "$2/booted"
printf 'READY 262144 stop\\n'
while IFS= read -r line; do
case "$line" in
'GEN '*)
printf '%s\\n' "$line" >> "$2/requests"
printf 'T 79\\n'
if [ "$recovered" = 1 ]; then
printf 'T 75\\nDONE 2 7 1.0 2.0 stop\\n'
else
# Never finish this command. An execution deadline must kill us.
while IFS= read -r ignored; do :; done
exit 3
fi ;;
QUIT) exit 0 ;;
esac
done
''')
engine.chmod(0o700)
with socket.socket() as probe:
probe.bind(('127.0.0.1', 0))
port = probe.getsockname()[1]
env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}',
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_GENERATION_TIMEOUT_S': '1',
'STRATA_MAX_WORKER_RESTARTS': str(restarts)}
def request(path, body=None):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
try:
connection.request('POST' if body is not None else 'GET', path,
json.dumps(body) if body is not None else None,
{'Content-Type': 'application/json'})
response = connection.getresponse()
content = response.read().decode()
return response.status, content
finally:
connection.close()
def get(path):
return json.loads(request(path)[1])
def wait_for(predicate):
deadline = time.monotonic() + 8
while True:
try:
if predicate():
return
except OSError:
pass
assert process.poll() is None and time.monotonic() < deadline, 'condition timed out'
time.sleep(0.01)
with tempfile.TemporaryFile() as logs, concurrent.futures.ThreadPoolExecutor(2) as pool:
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs,
start_new_session=True)
try:
wait_for(lambda: request('/ready')[0] == 200)
payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8,
'reasoning': {'effort': 'none'}, 'stream': streaming}
active = pool.submit(request, '/v1/responses', payload)
wait_for(lambda: (root / 'requests').exists())
original_pid = int((root / 'pids').read_text().splitlines()[0])
queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False})
wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 2)
code, content = active.result(timeout=6)
if streaming:
assert code == 200
events = [json.loads(line[5:]) for line in content.splitlines() if line.startswith('data:')]
assert [e['sequence_number'] for e in events] == list(range(len(events)))
assert events[-1]['type'] == 'response.failed'
assert events[-1]['response']['status'] == 'failed'
assert 'configured execution deadline' in json.dumps(events[-1])
assert not any(e['type'] == 'response.completed' for e in events)
else:
assert code == 502 and json.loads(content)['error']['code'] == 'generation_failed'
assert 'configured execution deadline' in content
assert queued.result(timeout=6)[0] in (502, 503)
assert len((root / 'requests').read_text().splitlines()) == 1, 'queued work replayed'
wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 0)
assert request('/ready')[0] == 503
assert get('/metrics')['generation']['failed_or_interrupted'] == 1
try:
os.kill(original_pid, 0)
except ProcessLookupError:
pass
else:
raise AssertionError('expired worker still alive')
if restarts:
wait_for(lambda: request('/ready')[0] == 200)
code, content = request('/v1/responses', {**payload, 'stream': False})
assert code == 200 and json.loads(content)['output'][0]['content'][0]['text'] == 'OK'
assert len((root / 'requests').read_text().splitlines()) == 2
assert len((root / 'pids').read_text().splitlines()) == 2
assert get('/metrics')['generation']['completed'] == 1
else:
assert get('/status')['worker'] == 'failed'
assert request('/health')[0] == 200
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def main():
binary = Path(sys.argv[1]).resolve()
spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py'))
fixture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fixture)
for streaming in (False, True):
for restarts in (0, 1):
exercise(binary, fixture, streaming, restarts)
print('Generation deadline: 4 HTTP cases passed; terminal failures, kill/reap, no replay, fresh recovery output exactly OK; CPU only')
if __name__ == '__main__':
main()