Stop abandoned generations and active worker shutdown

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 18:46:56 +02:00
parent d5354c1c58
commit d1f326bcff
5 changed files with 177 additions and 12 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
The repository pins Rust 1.99.0 in [`rust-toolchain.toml`](../rust-toolchain.toml). `rustup` selects it automatically from this checkout. The `strata-next` executable defaults to `serve` and also supports `doctor`, `model fetch MANIFEST --output DIR`, `model verify MANIFEST --output DIR`, and `model inspect FILE.gguf`. `scripts/check-local.sh` runs formatting, Clippy, Rust tests, protocol replay, and the CPU engine tests.
The Rust control plane provides process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and marks readiness only after the engine emits `READY <max-context>`. It also exposes `POST /v1/responses` for request validation. This route returns 503 while the worker is unavailable and 501 while the native inference adapter is absent; it never fabricates a model response. Worker restart is not yet implemented.
The Rust control plane provides process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and marks readiness only after the engine emits `READY <max-context>`. An abandoned internal generation sends `STOP` and drains its terminal response before the next request; shutdown during generation sends `STOP` before `QUIT`. It also exposes `POST /v1/responses` for request validation. This route returns 503 while the worker is unavailable and 501 while the native inference adapter is absent; it never fabricates a model response. Worker restart is not yet implemented.
Run locally with `cargo run --manifest-path control-plane/Cargo.toml`. It binds to `127.0.0.1:8081` by default; set `STRATA_BIND` to another socket address if needed. Check `/health`, `/ready`, and `/status`.
+150 -11
View File
@@ -143,11 +143,20 @@ pub async fn run_with_requests(
command = requests.recv(), if !requests_closed => {
match command {
Some(command) => {
if let Err(error) = generate(&mut stdin, &mut lines, command, max_context).await {
eprintln!("Strata engine protocol failed: {error}");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
tokio::select! {
result = generate(&mut stdin, &mut lines, command, max_context) => {
if let Err(error) = result {
eprintln!("Strata engine protocol failed: {error}");
stop(&mut child, &mut stdin).await;
update(&status, WorkerState::Failed, None).await;
return;
}
}
_ = shutdown.changed() => {
update(&status, WorkerState::Stopping, None).await;
stop_active(&mut child, &mut stdin).await;
return;
}
}
}
None => requests_closed = true,
@@ -160,9 +169,12 @@ pub async fn run_with_requests(
async fn generate(
stdin: &mut Option<ChildStdin>,
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
command: GenerationCommand,
mut command: GenerationCommand,
max_context: usize,
) -> Result<(), String> {
if command.result.is_closed() {
return Ok(());
}
let fits_context = usize::try_from(command.request.max_new)
.ok()
.and_then(|new| command.request.token_ids.len().checked_add(new))
@@ -187,12 +199,18 @@ async fn generate(
.map_err(|error| error.to_string())?;
pipe.flush().await.map_err(|error| error.to_string())?;
let mut events = Vec::new();
let mut stopped = false;
loop {
let line = lines
.next_line()
.await
.map_err(|error| error.to_string())?
.ok_or("engine exited before a terminal line")?;
let line = tokio::select! {
line = lines.next_line() => line.map_err(|error| error.to_string())?,
_ = command.result.closed(), if !stopped => {
pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?;
pipe.flush().await.map_err(|error| error.to_string())?;
stopped = true;
continue;
}
}
.ok_or("engine exited before a terminal line")?;
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
let _ = command.result.send(Err(message));
@@ -236,6 +254,14 @@ async fn stop(child: &mut Child, stdin: &mut Option<ChildStdin>) {
}
}
async fn stop_active(child: &mut Child, stdin: &mut Option<ChildStdin>) {
if let Some(pipe) = stdin.as_mut() {
let _ = pipe.write_all(b"STOP\n").await;
let _ = pipe.flush().await;
}
stop(child, stdin).await;
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -366,4 +392,117 @@ mod tests {
.unwrap()
.unwrap();
}
#[tokio::test]
async fn dropped_generation_receiver_sends_stop_and_preserves_worker() {
let marker =
std::env::temp_dir().join(format!("strata-cancel-drop-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
drop(result_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![99],
max_new: 1,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
let events = timeout(Duration::from_secs(5), result_rx)
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
std::fs::remove_file(marker).unwrap();
}
#[tokio::test]
async fn shutdown_interrupts_active_generation() {
let marker =
std::env::temp_dir().join(format!("strata-cancel-shutdown-{}", std::process::id()));
let _ = std::fs::remove_file(&marker);
let mut config = fixture_config("cancel", 5);
config.args.push(marker.display().to_string());
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop_tx, stop_rx) = watch::channel(false);
let (commands_tx, commands_rx) = mpsc::channel(1);
let task = tokio::spawn(run_with_requests(
config,
status.clone(),
stop_rx,
commands_rx,
));
wait_for(&status, WorkerState::Ready).await;
let (result_tx, result_rx) = oneshot::channel();
commands_tx
.send(GenerationCommand {
request: Generate {
token_ids: vec![10, 20],
max_new: 3,
temperature: None,
top_p: None,
},
result: result_tx,
})
.await
.unwrap();
timeout(Duration::from_secs(5), async {
while !marker.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.unwrap();
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert!(result_rx.await.is_err());
std::fs::remove_file(marker).unwrap();
}
}
+19
View File
@@ -30,5 +30,24 @@ case "$2" in
esac
done
;;
cancel)
printf 'READY 262144 stop\n'
while IFS= read -r line; do
case "$line" in
'GEN 3 10,20')
: > "$3"
printf 'T 31\n'
IFS= read -r stop || exit 3
[ "$stop" = STOP ] || exit 4
printf 'DONE 1 2 1.0 2.0 cancel\n'
;;
'GEN 1 99')
printf 'T 42\nDONE 1 1 1.0 2.0 stop\n'
;;
QUIT) exit 0 ;;
*) printf 'ERR unexpected request\n' ;;
esac
done
;;
*) exit 2 ;;
esac
+6
View File
@@ -48,3 +48,9 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- The Linux/arm64 Docker musl CLI image built and its `--version` command ran inside a `scratch` container. The current source was also cross-compiled locally for `aarch64-unknown-linux-musl`; `file` reported a statically linked ELF, and `readelf` found no interpreter or dynamic section.
- Mounted the current binary into that `scratch` image. It fetched Rust 1.99.0's pinned README over HTTPS (`3,304` bytes), verified the manifest SHA-256 (`b3f6ef2fef88b98cb9ec013a5c86213095e53e40eb228679574e4d06517f33c8`), and matched the host reference byte for byte. This verifies embedded TLS roots and the small-file acquisition path, not the 83.6 GB model transfer.
- The GitHub Actions workflow has not run because this checkout has no project remote. No GPU node was used.
## 2026-10-02 — worker cancellation contract
- A dropped generation receiver now causes `STOP`, drains the worker's terminal `DONE`, and leaves the resident worker ready for a second request.
- Shutdown during an active generation sends `STOP` before `QUIT` and closes the pending result receiver.
- The two focused fake-worker tests pass, along with Rust 1.99 Clippy with warnings denied. No GPU inference was used.
+1
View File
@@ -62,6 +62,7 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [ ] Package the C++/CUDA engine with the Rust CLI into one user-facing Linux executable where the link strategy permits.
- [ ] Add process restart, metrics, auth, failure injection, and soak tests.
- [x] Stop and drain an abandoned internal generation; interrupt an active generation during shutdown.
- [ ] Capture the 1×256K baseline, then implement and validate 2×256K and 1×512K.
- [ ] Evaluate speculation, KAR, and Value-Only only under the charter's separate quality gates.