feat(api): bound queue waiting without expiring active work (#41)
* feat(api): add opt-in native queue deadline * fix(queue): reject claims made after queue deadline
This commit is contained in:
@@ -287,6 +287,8 @@ jobs:
|
||||
run: python3 scripts/smoke-signal-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: Native queue deadline without expiring active work
|
||||
run: python3 scripts/smoke-queue-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
|
||||
|
||||
@@ -19,6 +19,7 @@ use crate::{
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub queue_timeout: Option<std::time::Duration>,
|
||||
pub lifecycle: crate::lifecycle::Lifecycle,
|
||||
pub api_key: Option<Arc<crate::auth::ApiKey>>,
|
||||
pub model: Option<String>,
|
||||
@@ -31,6 +32,7 @@ pub struct AppState {
|
||||
impl Default for AppState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
queue_timeout: None,
|
||||
lifecycle: Default::default(),
|
||||
api_key: None,
|
||||
model: None,
|
||||
@@ -373,6 +375,7 @@ mod tests {
|
||||
let (result, _rx) = tokio::sync::oneshot::channel();
|
||||
sender
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: crate::wire::Generate {
|
||||
token_ids: vec![10],
|
||||
|
||||
@@ -12,6 +12,7 @@ use serde::Deserialize;
|
||||
use crate::worker::WorkerConfig;
|
||||
|
||||
pub struct Config {
|
||||
pub queue_timeout: Option<Duration>,
|
||||
pub response_history_dir: Option<PathBuf>,
|
||||
pub mtp_pack: Option<PathBuf>,
|
||||
pub assets: Vec<crate::asset_bundle::AssetBundle>,
|
||||
@@ -32,6 +33,7 @@ pub struct Config {
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileConfig {
|
||||
queue_timeout_s: Option<u64>,
|
||||
mtp_pack: Option<PathBuf>,
|
||||
response_history_dir: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
@@ -95,6 +97,14 @@ impl Config {
|
||||
.unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS);
|
||||
crate::lifecycle::validate_capacity(max_in_flight_requests)?;
|
||||
|
||||
let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")?
|
||||
.map(|value| value.parse::<u64>())
|
||||
.transpose()?
|
||||
.or(file.queue_timeout_s);
|
||||
if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) {
|
||||
return Err("queue_timeout_s must be between 1 and 86400 when configured".into());
|
||||
}
|
||||
|
||||
let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")?
|
||||
.map(|value| value.parse::<u64>())
|
||||
.transpose()?
|
||||
@@ -257,6 +267,7 @@ impl Config {
|
||||
host_checked: false,
|
||||
engine_probe: file.engine_probe,
|
||||
shutdown_grace: Duration::from_secs(shutdown_grace_s),
|
||||
queue_timeout: queue_timeout_s.map(Duration::from_secs),
|
||||
max_in_flight_requests,
|
||||
api_key,
|
||||
bind,
|
||||
|
||||
@@ -59,3 +59,5 @@ mod native_events;
|
||||
pub mod cuda_memory;
|
||||
|
||||
pub mod service_switch;
|
||||
|
||||
pub mod queue;
|
||||
|
||||
@@ -823,6 +823,7 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Err
|
||||
config.provision().await?;
|
||||
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
||||
let mut state = app::AppState {
|
||||
queue_timeout: config.queue_timeout,
|
||||
lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?,
|
||||
response_history: Arc::new(tokio::sync::RwLock::new(response_history)),
|
||||
api_key: config.api_key.clone(),
|
||||
|
||||
@@ -41,6 +41,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,
|
||||
"queue_timeout_s": config.queue_timeout.map(|duration| duration.as_secs()),
|
||||
"shutdown_grace_s": config.shutdown_grace.as_secs(),
|
||||
"generation_timeout_s": config.worker.as_ref().and_then(|worker| worker.generation_timeout.map(|duration| duration.as_secs())),
|
||||
"model": config.model,
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Optional queue deadline. Claim and expiration have one atomic winner.
|
||||
use crate::worker::GenerationCommand;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::{
|
||||
sync::{mpsc, oneshot},
|
||||
time::{Instant, timeout_at},
|
||||
};
|
||||
|
||||
const QUEUED: u8 = 0;
|
||||
const CLAIMED: u8 = 1;
|
||||
const EXPIRED: u8 = 2;
|
||||
|
||||
pub struct Ticket {
|
||||
deadline: Instant,
|
||||
state: Arc<AtomicU8>,
|
||||
started: oneshot::Sender<()>,
|
||||
}
|
||||
impl Ticket {
|
||||
pub(crate) fn claim(self) -> bool {
|
||||
if self
|
||||
.state
|
||||
.compare_exchange(QUEUED, CLAIMED, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// Check after the CAS: a thread may have been preempted across the
|
||||
// deadline before claiming. The requester waits for acknowledgment
|
||||
// after losing its expiry CAS, so a late claimant can still refuse.
|
||||
if Instant::now() >= self.deadline {
|
||||
self.state.store(EXPIRED, Ordering::Release);
|
||||
return false;
|
||||
}
|
||||
// A requester that disappeared before acknowledgment must not start work.
|
||||
self.started.send(()).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Expired,
|
||||
Closed,
|
||||
}
|
||||
|
||||
pub async fn enqueue(
|
||||
sender: &mpsc::Sender<GenerationCommand>,
|
||||
mut command: GenerationCommand,
|
||||
budget: Option<Duration>,
|
||||
) -> Result<(), Error> {
|
||||
let Some(budget) = budget else {
|
||||
return sender.send(command).await.map_err(|_| Error::Closed);
|
||||
};
|
||||
let deadline = Instant::now() + budget;
|
||||
let state = Arc::new(AtomicU8::new(QUEUED));
|
||||
let (started, mut received) = oneshot::channel();
|
||||
command.queue = Some(Ticket {
|
||||
deadline,
|
||||
state: state.clone(),
|
||||
started,
|
||||
});
|
||||
match timeout_at(deadline, sender.send(command)).await {
|
||||
Err(_) => return Err(Error::Expired),
|
||||
Ok(Err(_)) => return Err(Error::Closed),
|
||||
Ok(Ok(())) => (),
|
||||
}
|
||||
let acknowledged = tokio::select! {
|
||||
biased;
|
||||
result = &mut received => result,
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
if state.compare_exchange(QUEUED, EXPIRED, Ordering::AcqRel, Ordering::Acquire).is_ok() {
|
||||
return Err(Error::Expired);
|
||||
}
|
||||
// The worker won the claim race. Its synchronous acknowledgment or
|
||||
// channel closure resolves this wait; the queue clock no longer applies.
|
||||
received.await
|
||||
}
|
||||
};
|
||||
acknowledged.map_err(|_| {
|
||||
if state.load(Ordering::Acquire) == EXPIRED {
|
||||
Error::Expired
|
||||
} else {
|
||||
Error::Closed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{wire::Generate, worker::GenerationResult};
|
||||
fn command() -> (
|
||||
GenerationCommand,
|
||||
oneshot::Receiver<Result<Vec<crate::wire::Event>, String>>,
|
||||
) {
|
||||
let (result, received) = oneshot::channel();
|
||||
(
|
||||
GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![65],
|
||||
max_new: 1,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
},
|
||||
result: GenerationResult::Buffered(result),
|
||||
},
|
||||
received,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn full_channel_and_unclaimed_jobs_expire_without_claim() {
|
||||
let (sender, mut pending) = mpsc::channel(1);
|
||||
let (first, _first_result) = command();
|
||||
sender.send(first).await.unwrap();
|
||||
let (second, _second_result) = command();
|
||||
assert_eq!(
|
||||
enqueue(&sender, second, Some(Duration::from_millis(10))).await,
|
||||
Err(Error::Expired)
|
||||
);
|
||||
drop(pending.recv().await.unwrap());
|
||||
assert!(
|
||||
pending.try_recv().is_err(),
|
||||
"channel-timeout job was never queued"
|
||||
);
|
||||
let (third, _third_result) = command();
|
||||
assert_eq!(
|
||||
enqueue(&sender, third, Some(Duration::from_millis(10))).await,
|
||||
Err(Error::Expired)
|
||||
);
|
||||
assert!(!pending.recv().await.unwrap().queue.unwrap().claim());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn claim_removes_queue_deadline_and_closed_queue_is_distinct() {
|
||||
let (sender, mut pending) = mpsc::channel(1);
|
||||
let (job, _result) = command();
|
||||
let submit =
|
||||
tokio::spawn(async move { enqueue(&sender, job, Some(Duration::from_secs(1))).await });
|
||||
let mut job = pending.recv().await.unwrap();
|
||||
assert!(job.queue.take().unwrap().claim());
|
||||
assert_eq!(submit.await.unwrap(), Ok(()));
|
||||
// A claimed job has no remaining ticket/timer attached to execution.
|
||||
assert!(job.queue.is_none());
|
||||
let (sender, pending) = mpsc::channel(1);
|
||||
drop(pending);
|
||||
let (job, _result) = command();
|
||||
assert_eq!(
|
||||
enqueue(&sender, job, Some(Duration::from_secs(1))).await,
|
||||
Err(Error::Closed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_claim_rejects_late_expired_and_abandoned_tickets() {
|
||||
for (deadline, initial, abandoned) in [
|
||||
(Instant::now() - Duration::from_secs(1), QUEUED, false),
|
||||
(Instant::now() + Duration::from_secs(10), EXPIRED, false),
|
||||
(Instant::now() + Duration::from_secs(10), QUEUED, true),
|
||||
] {
|
||||
let (started, received) = oneshot::channel();
|
||||
let state = Arc::new(AtomicU8::new(initial));
|
||||
if abandoned {
|
||||
drop(received);
|
||||
}
|
||||
assert!(
|
||||
!Ticket {
|
||||
deadline,
|
||||
state,
|
||||
started
|
||||
}
|
||||
.claim()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -883,6 +883,25 @@ pub async fn count_input_tokens(
|
||||
}
|
||||
}
|
||||
|
||||
fn queue_error(error: crate::queue::Error) -> Response {
|
||||
match error {
|
||||
crate::queue::Error::Expired => api_error(
|
||||
StatusCode::GATEWAY_TIMEOUT,
|
||||
"server_error",
|
||||
"queue_timeout",
|
||||
None,
|
||||
"request exceeded the configured queue deadline before worker claim; generation was not started",
|
||||
),
|
||||
crate::queue::Error::Closed => api_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"worker_not_ready",
|
||||
None,
|
||||
"the Strata worker command queue closed before request claim",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
body: Result<Json<Value>, JsonRejection>,
|
||||
@@ -943,22 +962,19 @@ pub async fn create(
|
||||
};
|
||||
if request.stream {
|
||||
let (events, received) = mpsc::channel(16);
|
||||
if generation
|
||||
.send(GenerationCommand {
|
||||
if let Err(error) = crate::queue::enqueue(
|
||||
generation,
|
||||
GenerationCommand {
|
||||
queue: None,
|
||||
activity: Some(state.lifecycle.generation()),
|
||||
request: generate,
|
||||
result: GenerationResult::Streaming(events),
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
},
|
||||
state.queue_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return api_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"worker_not_ready",
|
||||
None,
|
||||
"the Strata worker command queue is closed",
|
||||
);
|
||||
return queue_error(error);
|
||||
}
|
||||
return stream_live_text(
|
||||
request,
|
||||
@@ -969,18 +985,13 @@ pub async fn create(
|
||||
}
|
||||
let (result, received) = oneshot::channel();
|
||||
let command = GenerationCommand {
|
||||
queue: None,
|
||||
activity: Some(state.lifecycle.generation()),
|
||||
request: generate,
|
||||
result: GenerationResult::Buffered(result),
|
||||
};
|
||||
if generation.send(command).await.is_err() {
|
||||
return api_error(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"server_error",
|
||||
"worker_not_ready",
|
||||
None,
|
||||
"the Strata worker command queue is closed",
|
||||
);
|
||||
if let Err(error) = crate::queue::enqueue(generation, command, state.queue_timeout).await {
|
||||
return queue_error(error);
|
||||
}
|
||||
let events = match received.await {
|
||||
Ok(Ok(events)) => events,
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::wire::{self, Event, Generate};
|
||||
const STOP_DRAIN_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
pub struct GenerationCommand {
|
||||
pub queue: Option<crate::queue::Ticket>,
|
||||
pub activity: Option<crate::lifecycle::Guard>,
|
||||
pub request: Generate,
|
||||
pub result: GenerationResult,
|
||||
@@ -274,6 +275,9 @@ async fn run_session(
|
||||
command = requests.recv(), if !requests_closed => {
|
||||
match command {
|
||||
Some(mut command) => {
|
||||
if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) {
|
||||
continue;
|
||||
}
|
||||
// Retain the command activity until protocol cleanup,
|
||||
// including STOP/QUIT and failed-process termination.
|
||||
let _activity = command.activity.take();
|
||||
@@ -517,6 +521,7 @@ mod tests {
|
||||
let (result, received) = oneshot::channel();
|
||||
requests
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10000; 200000],
|
||||
@@ -560,6 +565,7 @@ mod tests {
|
||||
let (events, mut received) = mpsc::channel(1);
|
||||
requests
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: Some(lifecycle.generation()),
|
||||
request: Generate {
|
||||
token_ids: vec![10],
|
||||
@@ -638,6 +644,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -672,6 +679,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -732,6 +740,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -755,6 +764,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![99],
|
||||
@@ -807,6 +817,7 @@ mod tests {
|
||||
let (events_tx, mut events_rx) = mpsc::channel(2);
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -830,6 +841,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![99],
|
||||
@@ -883,6 +895,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -934,6 +947,7 @@ mod tests {
|
||||
let (events_tx, mut events_rx) = mpsc::channel(1);
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
@@ -965,6 +979,7 @@ mod tests {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids: vec![99],
|
||||
@@ -1017,6 +1032,7 @@ mod tests {
|
||||
let (sender, receiver) = oneshot::channel();
|
||||
(
|
||||
GenerationCommand {
|
||||
queue: None,
|
||||
activity: None,
|
||||
request: Generate {
|
||||
token_ids,
|
||||
@@ -1148,6 +1164,7 @@ mod tests {
|
||||
let (events_tx, mut events_rx) = mpsc::channel(2);
|
||||
commands_tx
|
||||
.send(GenerationCommand {
|
||||
queue: None,
|
||||
activity: Some(lifecycle.generation()),
|
||||
request: Generate {
|
||||
token_ids: vec![10, 20],
|
||||
|
||||
@@ -23,6 +23,24 @@ 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).
|
||||
|
||||
Top-level `queue_timeout_s` (or `STRATA_QUEUE_TIMEOUT_S`, 1–86400 seconds) optionally
|
||||
bounds waiting for a worker to claim an inference command. It is disabled by
|
||||
default; environment overrides the config file. The clock starts after request
|
||||
validation, prompt rendering and tokenization, and includes command-channel
|
||||
admission and waiting behind active work. `check-config` reports seconds or null.
|
||||
Responses, Chat and Messages use the same queue. An expired unclaimed request
|
||||
returns HTTP 504 with a JSON error before any SSE headers; Responses/Chat use
|
||||
`queue_timeout`, while Messages retains its own error envelope.
|
||||
|
||||
Worker claim and expiry have one atomic winner. Expired commands are skipped
|
||||
without sending `GEN`; there is no retry or replay. Once claimed, only the
|
||||
existing active-generation deadline applies, so a long prefill is not cut short
|
||||
by the queue setting. A canceled queued command retains its generation activity
|
||||
guard until the worker dequeues it or the queue closes, allowing drain to account
|
||||
for outstanding cleanup. Queue time does not include upload or tokenization and
|
||||
is not a total request deadline. Default behavior is unchanged. Tests cover an
|
||||
isolated CPU worker and exact output A, not real-model performance.
|
||||
|
||||
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
|
||||
|
||||
@@ -67,6 +67,17 @@ def main():
|
||||
assert result['tokenizer_validated']
|
||||
assert result['max_in_flight_requests'] == 2
|
||||
assert result['generation_timeout_s'] is None
|
||||
assert result['queue_timeout_s'] is None
|
||||
for seconds in [1, 86400]:
|
||||
assert run({'STRATA_QUEUE_TIMEOUT_S': str(seconds)})['queue_timeout_s'] == seconds
|
||||
for seconds in ['0', '-1', '86401', '1.5', 'bad']:
|
||||
run({'STRATA_QUEUE_TIMEOUT_S': seconds}, success=False)
|
||||
config.write_text(json.dumps({**base, 'queue_timeout_s': 12}))
|
||||
assert run()['queue_timeout_s'] == 12
|
||||
assert run({'STRATA_QUEUE_TIMEOUT_S': '3'})['queue_timeout_s'] == 3
|
||||
config.write_text(json.dumps({**base, 'queue_timeout_s': 0}))
|
||||
run(success=False)
|
||||
config.write_text(json.dumps(base))
|
||||
assert result['shutdown_grace_s'] == 0
|
||||
for seconds in [0, 20]:
|
||||
assert run({'STRATA_SHUTDOWN_GRACE_S': str(seconds)})['shutdown_grace_s'] == seconds
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated CPU worker: queued API expiry never sends GEN; active work survives."""
|
||||
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 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)
|
||||
with tempfile.TemporaryDirectory(prefix='strata-queue-') as directory:
|
||||
root = Path(directory)
|
||||
fixture.tokenizer(root)
|
||||
engine = root / 'engine.sh'
|
||||
engine.write_text("""#!/bin/sh
|
||||
printf 'READY 262144 stop\n'
|
||||
while IFS= read -r line; do
|
||||
case "$line" in
|
||||
'GEN '*)
|
||||
printf 'GEN\n' >> "$2/requests"
|
||||
if [ ! -e "$2/active" ]; then
|
||||
: > "$2/active"
|
||||
while [ ! -e "$2/release" ]; do sleep 0.01; done
|
||||
fi
|
||||
printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;;
|
||||
QUIT) exit 0 ;;
|
||||
*) exit 4 ;;
|
||||
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_STARTUP_TIMEOUT_S': '5',
|
||||
'STRATA_MAX_WORKER_RESTARTS': '0', 'STRATA_QUEUE_TIMEOUT_S': '1'}
|
||||
|
||||
def request(path, payload=None):
|
||||
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=15)
|
||||
try:
|
||||
connection.request('POST' if payload is not None else 'GET', path,
|
||||
json.dumps(payload) if payload is not None else None,
|
||||
{'Content-Type': 'application/json', 'anthropic-version': '2023-06-01'})
|
||||
response = connection.getresponse()
|
||||
return response.status, response.getheader('Content-Type'), response.read()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
response_payload = {'model': 'strata-local', 'input': 'Hello', 'reasoning': {'effort': 'none'}}
|
||||
with tempfile.TemporaryFile() as logs:
|
||||
runtime = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
|
||||
try:
|
||||
deadline = time.monotonic() + 8
|
||||
while True:
|
||||
try:
|
||||
if request('/ready')[0] == 200:
|
||||
break
|
||||
except (OSError, http.client.HTTPException):
|
||||
pass
|
||||
assert time.monotonic() < deadline, 'runtime not ready'
|
||||
time.sleep(0.03)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
active = pool.submit(request, '/v1/responses', response_payload)
|
||||
try:
|
||||
while not (root / 'active').exists():
|
||||
assert time.monotonic() < deadline, 'first GEN missing'
|
||||
time.sleep(0.01)
|
||||
for path, payload in [
|
||||
('/v1/responses', response_payload),
|
||||
('/v1/chat/completions', {'model': 'strata-local', 'messages': [{'role':'user','content':'Hello'}]}),
|
||||
('/v1/messages', {'model': 'strata-local', 'max_tokens': 16, 'messages': [{'role':'user','content':'Hello'}]}),
|
||||
]:
|
||||
for stream in [False, True]:
|
||||
start = time.monotonic()
|
||||
status, content_type, body = request(path, {**payload, 'stream': stream})
|
||||
elapsed = time.monotonic() - start
|
||||
assert status == 504 and 'application/json' in content_type, (path, status, body)
|
||||
error = json.loads(body)['error']
|
||||
assert 'queue deadline' in error['message'], error
|
||||
if path != '/v1/messages':
|
||||
assert error['code'] == 'queue_timeout', error
|
||||
assert 0.7 <= elapsed < 5, elapsed
|
||||
assert (root / 'requests').read_text().splitlines() == ['GEN']
|
||||
assert not active.done(), 'active generation expired under queue deadline'
|
||||
assert request('/ready')[0] == 200
|
||||
finally:
|
||||
(root / 'release').touch()
|
||||
status, _, body = active.result(timeout=5)
|
||||
assert status == 200 and json.loads(body)['output'][0]['content'][0]['text'] == 'A'
|
||||
# All expired jobs must be skipped before the next live GEN.
|
||||
for stream in [False, True]:
|
||||
status, content_type, body = request('/v1/responses', {**response_payload, 'stream': stream})
|
||||
assert status == 200, body
|
||||
if stream:
|
||||
events = [json.loads(line[6:]) for line in body.decode().splitlines() if line.startswith('data: ')]
|
||||
assert events[-1]['type'] == 'response.completed'
|
||||
final = events[-1]['response']
|
||||
else:
|
||||
final = json.loads(body)
|
||||
assert final['output'][0]['content'][0]['text'] == 'A'
|
||||
assert (root / 'requests').read_text().splitlines() == ['GEN'] * 3
|
||||
lifecycle = json.loads(request('/admin/lifecycle')[2])
|
||||
assert lifecycle['generation_jobs'] == 0, lifecycle
|
||||
print('Queue deadline passed: 6 JSON/SSE Responses/Chat/Messages expirations, no queued GEN, active preserved, next JSON/SSE exact A, zero generation jobs')
|
||||
finally:
|
||||
if runtime.poll() is None:
|
||||
runtime.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
runtime.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(runtime.pid, signal.SIGKILL)
|
||||
runtime.wait(timeout=5)
|
||||
if runtime.returncode != 0:
|
||||
logs.seek(0)
|
||||
raise AssertionError(logs.read().decode()[-3000:])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user