leleka_tokenizer::LiteralMarks swaps every special literal (GGUF token type 3 and 4) in a client string for a plane-15 private-use mark before the chat template runs (a forged mark is escaped); Tokenizer::encode_marked parses the template's own literals as special tokens and encodes each mark's literal as ordinary text. render_request marks instructions, message text, reasoning, call arguments, tool outputs and tool descriptions/schemas; the gateway's own tool markers stay literal. Generation and /input_tokens share the one encoding; the text contract carries the marked string and leleka-runtime reads it with encode_marked. Not covered: strata-desktop-core still renders unmarked text; live Codex session (gate L) not run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
776 lines
33 KiB
Rust
776 lines
33 KiB
Rust
//! The worker for a text-level engine: the whole `strata-next` API in front of anything that
|
|
//! implements [`leleka_backend_api::Backend`] (the Rust engine over gRPC, or a scripted engine in
|
|
//! tests).
|
|
//!
|
|
//! It is the second implementation of the worker seam. [`crate::worker::run_supervised`] feeds the
|
|
//! HTTP layer from a child process that speaks token ids on stdio; this module consumes the same
|
|
//! [`GenerationCommand`] channel, keeps the same [`WorkerStatus`] and answers the same [`Control`]
|
|
//! messages, but talks to the engine through the backend contract: a prompt string in, text deltas
|
|
//! and exactly one terminal event out. Nothing above this module changes.
|
|
//!
|
|
//! The conversions this edge must get right (all of them fail closed):
|
|
//!
|
|
//! * prompt: the ids the HTTP layer counted are decoded to text and must encode back to the same ids
|
|
//! (the engine encodes the string again with the same tokenizer); anything else is refused;
|
|
//! * output: every delta is re-encoded without special-token parsing and must decode to the same
|
|
//! bytes, so the bytes the client sees are the bytes the engine produced. The ids are not the
|
|
//! engine's sampled ids; usage comes from the engine's terminal report;
|
|
//! * stop: the literals `<|im_end|>` and `<|endoftext|>` end the text (the stdio engine reports them as
|
|
//! ids), the engine generation is cancelled and the result is `stop`;
|
|
//! * what the text contract cannot carry (images, reasoning-budget wrap-up, per-request engine tuning,
|
|
//! control-vector switching) is refused with a message instead of being dropped;
|
|
//! * a terminal event reaches the HTTP layer for every started generation: completed, failed,
|
|
//! cancelled, or an engine that vanished (the stream ended without one).
|
|
//!
|
|
//! The worker only attaches: [`Backend::load`] is expected to return the already loaded model (the
|
|
//! gRPC backend never issues a load RPC), so an HTTP request can never start a multi-gigabyte load.
|
|
|
|
use std::{
|
|
sync::{Arc, Mutex},
|
|
time::Duration,
|
|
};
|
|
|
|
use leleka_backend_api as api;
|
|
use tokio::{
|
|
sync::{RwLock, mpsc, watch},
|
|
time::Instant,
|
|
};
|
|
|
|
use crate::{
|
|
tokenizer::Tokenizer,
|
|
wire::{Done, Event, Finish, Generate},
|
|
worker::{
|
|
Control, GenerationCommand, LoadReply, WorkerState, WorkerStatus, deliver, finish,
|
|
send_failure, update,
|
|
},
|
|
};
|
|
|
|
/// Literals that end the text, as the ids `<|im_end|>` / `<|endoftext|>` do on the stdio wire.
|
|
const STOP_LITERALS: [&str; 2] = ["<|im_end|>", "<|endoftext|>"];
|
|
|
|
pub struct BackendWorkerConfig {
|
|
/// The tokenizer the HTTP layer counts with; the engine must use the same vocabulary.
|
|
pub tokenizer: Arc<Tokenizer>,
|
|
/// The model to attach to, exactly as the engine describes it.
|
|
pub model: api::ModelDescriptor,
|
|
pub runtime: api::RuntimeConfig,
|
|
/// The engine's context in tokens (`n + max_new + 8 <= max_context` is checked before a request).
|
|
pub max_context: usize,
|
|
/// The most output tokens one request may ask for (the runtime facade caps it). A request above
|
|
/// it is refused with a message; a default budget is clamped to it by the HTTP layer.
|
|
pub max_output_tokens: u32,
|
|
/// Wall-clock limit of one generation; the engine is cancelled when it expires.
|
|
pub generation_timeout: Option<Duration>,
|
|
/// No engine event for this long during a generation cancels it. Off by default: the text
|
|
/// contract has no progress events, so a long prefill is indistinguishable from a stall.
|
|
pub stall_timeout: Option<Duration>,
|
|
/// How long to wait between attempts to attach to an engine that is not there.
|
|
pub attach_retry: Duration,
|
|
/// How often an idle worker asks the engine whether the model is still loaded, so readiness
|
|
/// drops when the runtime restarts without waiting for a request to find out.
|
|
pub health_interval: Duration,
|
|
/// How long a cancelled generation may take to produce its terminal event before the engine
|
|
/// is treated as lost.
|
|
pub cancel_drain_timeout: Duration,
|
|
/// Where the engine's prefix-cache summary is copied (health tick and after every request); `None` = not shown.
|
|
pub prefix_view: Option<Arc<crate::prefix_view::PrefixView>>,
|
|
/// Where the engine's memory-governor report is copied (health tick and after every request); `None` = not shown, no gate.
|
|
pub memory_view: Option<Arc<crate::memory_view::MemoryView>>,
|
|
}
|
|
|
|
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
|
|
|
|
enum Served {
|
|
Done,
|
|
/// The engine is gone or violated the contract; attach again.
|
|
Lost(String),
|
|
Shutdown,
|
|
}
|
|
|
|
enum Cancel {
|
|
/// The HTTP client went away.
|
|
Client,
|
|
/// A stop literal was found in the text.
|
|
Marker,
|
|
/// The request must end as a failure with this message.
|
|
Failure(String),
|
|
}
|
|
|
|
/// The runtime gRPC contract names a request by UUID and refuses a repeated one.
|
|
fn request_id() -> String {
|
|
uuid::Uuid::new_v4().to_string()
|
|
}
|
|
|
|
/// Run a blocking backend call off the async threads. The backend is `Send` but not `Sync`, so
|
|
/// calls are serialised by the mutex; `start_generation` and `cancel` return quickly by contract.
|
|
async fn on_engine<T: Send + 'static>(
|
|
engine: &Engine,
|
|
call: impl FnOnce(&mut dyn api::Backend) -> T + Send + 'static,
|
|
) -> Result<T, String> {
|
|
let engine = Arc::clone(engine);
|
|
tokio::task::spawn_blocking(move || {
|
|
let mut guard = engine
|
|
.lock()
|
|
.map_err(|_| "engine state is poisoned".to_owned())?;
|
|
Ok(call(&mut **guard))
|
|
})
|
|
.await
|
|
.map_err(|error| format!("engine call failed: {error}"))?
|
|
}
|
|
|
|
/// The prompt as text, or why the engine would not see exactly these tokens.
|
|
fn prompt_text(tokenizer: &Tokenizer, ids: &[u32]) -> Result<String, String> {
|
|
let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?;
|
|
let text = String::from_utf8(bytes)
|
|
.map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
|
|
let again = tokenizer.encode(&text, true).map_err(|e| e.to_string())?;
|
|
if again != ids {
|
|
return Err(
|
|
"the prompt tokens are not the canonical encoding of their text, so a text-level engine \
|
|
would tokenize the prompt differently; refusing to serve different tokens than were counted"
|
|
.to_owned(),
|
|
);
|
|
}
|
|
Ok(text)
|
|
}
|
|
|
|
/// Token ids whose bytes are exactly `text`.
|
|
fn text_tokens(tokenizer: &Tokenizer, text: &str) -> Result<Vec<u32>, String> {
|
|
let ids = tokenizer.encode(text, false).map_err(|e| e.to_string())?;
|
|
let bytes = tokenizer.decode_bytes(&ids).map_err(|e| e.to_string())?;
|
|
if bytes != text.as_bytes() {
|
|
return Err("an engine text delta does not survive re-tokenization unchanged".to_owned());
|
|
}
|
|
Ok(ids)
|
|
}
|
|
|
|
/// Map an HTTP-layer request onto the engine contract, or say what cannot be carried.
|
|
async fn prepare(
|
|
config: &BackendWorkerConfig,
|
|
request: &Generate,
|
|
) -> Result<api::GenerationRequest, String> {
|
|
if request.embeddings.is_some() {
|
|
return Err("image input is not supported over the text-level engine contract".to_owned());
|
|
}
|
|
if request.reasoning.is_some() {
|
|
return Err("reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide".to_owned());
|
|
}
|
|
if request.tune.is_some() {
|
|
return Err(
|
|
"strata_tune is an engine-process setting and is not part of the engine contract"
|
|
.to_owned(),
|
|
);
|
|
}
|
|
if request.cvec.is_some() {
|
|
return Err(
|
|
"experimental_speed_projection (control vectors) is not part of the engine contract"
|
|
.to_owned(),
|
|
);
|
|
}
|
|
let fits = usize::try_from(request.max_new)
|
|
.ok()
|
|
.and_then(|new| request.token_ids.len().checked_add(new))
|
|
.and_then(|total| total.checked_add(8))
|
|
.is_some_and(|total| total <= config.max_context);
|
|
if !fits {
|
|
return Err("prompt, output budget, and 8-token margin exceed context".to_owned());
|
|
}
|
|
if request.token_ids.is_empty() || request.max_new == 0 {
|
|
return Err("a generation needs prompt tokens and a positive max_new".to_owned());
|
|
}
|
|
if request.max_new > config.max_output_tokens {
|
|
return Err(format!(
|
|
"max_output_tokens {} exceeds the runtime's limit of {}",
|
|
request.max_new, config.max_output_tokens
|
|
));
|
|
}
|
|
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
|
|
.map_err(|error| format!("sampling: {error}"))?;
|
|
let prompt_span = crate::stage_trace::span("worker_prompt_text");
|
|
let prompt = match &request.prompt_text {
|
|
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still decode to it
|
|
// (a table walk over the ids, well under a millisecond for a whole conversation).
|
|
Some(text) if config.tokenizer.decodes_to(&request.token_ids, text.as_bytes()) => {
|
|
text.to_string()
|
|
}
|
|
// Control-token text inside a message travels marked (`LiteralMarks`), and the engine reads the marks
|
|
// (`encode_marked`): the text is handed over if that encoding is exactly the ids that were counted.
|
|
// Anything else is decoded and must be the canonical encoding of its own text, or it is refused.
|
|
other => {
|
|
let tokenizer = Arc::clone(&config.tokenizer);
|
|
let ids = request.token_ids.clone();
|
|
let marked = other.clone();
|
|
tokio::task::spawn_blocking(move || match marked {
|
|
Some(text)
|
|
if tokenizer.marks().has_marks(&text)
|
|
&& tokenizer
|
|
.encode_marked(&text)
|
|
.is_ok_and(|encoded| encoded == ids) =>
|
|
{
|
|
Ok(text.to_string())
|
|
}
|
|
_ => prompt_text(&tokenizer, &ids),
|
|
})
|
|
.await
|
|
.map_err(|error| error.to_string())??
|
|
}
|
|
};
|
|
drop(prompt_span);
|
|
Ok(api::GenerationRequest {
|
|
request_id: request_id(),
|
|
prompt,
|
|
max_output_tokens: request.max_new,
|
|
temperature_milli: fixed.temperature_milli,
|
|
sampling: api::SamplingOptions {
|
|
top_p_micro: fixed.top_p_micro,
|
|
top_k: fixed.top_k,
|
|
min_p_micro: fixed.min_p_micro,
|
|
repetition_penalty_micro: fixed.repetition_penalty_micro,
|
|
frequency_penalty_micro: fixed.frequency_penalty_micro,
|
|
presence_penalty_micro: fixed.presence_penalty_micro,
|
|
penalty_last_n: fixed.penalty_last_n,
|
|
seed: fixed.seed,
|
|
},
|
|
})
|
|
}
|
|
|
|
pub async fn run_backend_worker(
|
|
backend: Box<dyn api::Backend>,
|
|
config: BackendWorkerConfig,
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
mut shutdown: watch::Receiver<bool>,
|
|
mut requests: mpsc::Receiver<GenerationCommand>,
|
|
mut control: mpsc::Receiver<Control>,
|
|
) {
|
|
let engine: Engine = Arc::new(Mutex::new(backend));
|
|
let mut waiting: Vec<LoadReply> = Vec::new();
|
|
let mut attached_before = false;
|
|
let mut requests_closed = false;
|
|
let mut control_closed = false;
|
|
'attach: loop {
|
|
update(
|
|
&status,
|
|
if attached_before {
|
|
WorkerState::Restarting
|
|
} else {
|
|
WorkerState::Starting
|
|
},
|
|
None,
|
|
)
|
|
.await;
|
|
// Fail what queued up while the engine was away; nothing is replayed.
|
|
while let Ok(command) = requests.try_recv() {
|
|
send_failure(
|
|
command.result,
|
|
"worker is restarting; request was not replayed".to_owned(),
|
|
)
|
|
.await;
|
|
}
|
|
let loaded = loop {
|
|
let model = config.model.clone();
|
|
let runtime = config.runtime.clone();
|
|
match on_engine(&engine, move |backend| backend.load(model, runtime)).await {
|
|
Ok(Ok(loaded))
|
|
if loaded
|
|
.validate_for_load(&config.model, &config.runtime)
|
|
.is_ok() =>
|
|
{
|
|
break loaded;
|
|
}
|
|
Ok(Ok(_)) => crate::elog!(
|
|
"the engine returned a load result that does not match the request"
|
|
),
|
|
Ok(Err(error)) => crate::elog!("waiting for the engine: {error}"),
|
|
Err(error) => crate::elog!("waiting for the engine: {error}"),
|
|
}
|
|
let retry = tokio::time::sleep(config.attach_retry);
|
|
tokio::pin!(retry);
|
|
loop {
|
|
tokio::select! {
|
|
biased;
|
|
_ = shutdown.changed() => {
|
|
update(&status, WorkerState::Stopping, None).await;
|
|
return;
|
|
}
|
|
_ = &mut retry => break,
|
|
message = control.recv(), if !control_closed => match message {
|
|
Some(Control::Load { reply }) => waiting.push(reply),
|
|
Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable(reply, "the worker is not attached to the engine"),
|
|
Some(Control::Unload { reply, .. }) => {
|
|
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
|
|
}
|
|
None => control_closed = true,
|
|
},
|
|
command = requests.recv(), if !requests_closed => match command {
|
|
Some(command) => send_failure(
|
|
command.result,
|
|
"worker is not attached to the engine; request was not replayed".to_owned(),
|
|
)
|
|
.await,
|
|
None => requests_closed = true,
|
|
},
|
|
}
|
|
}
|
|
};
|
|
attached_before = true;
|
|
update(&status, WorkerState::Ready, Some(config.max_context)).await;
|
|
status.write().await.output_cap = Some(config.max_output_tokens);
|
|
status.write().await.text_level_engine = true;
|
|
status.write().await.last_activity = Some(Instant::now());
|
|
for reply in waiting.drain(..) {
|
|
let _ = reply.send(Ok(()));
|
|
}
|
|
let mut health = tokio::time::interval(config.health_interval);
|
|
health.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
|
health.reset();
|
|
loop {
|
|
tokio::select! {
|
|
biased;
|
|
_ = shutdown.changed() => {
|
|
update(&status, WorkerState::Stopping, None).await;
|
|
return;
|
|
}
|
|
_ = health.tick() => {
|
|
let wanted = config.model.clone();
|
|
let present = on_engine(&engine, move |backend| backend.capabilities().supports(&wanted)).await;
|
|
if present != Ok(true) {
|
|
crate::elog!("engine lost: the runtime no longer reports the model as loaded");
|
|
update(&status, WorkerState::Failed, None).await;
|
|
continue 'attach;
|
|
}
|
|
refresh_prefix_view(&engine, &config).await;
|
|
}
|
|
message = control.recv(), if !control_closed => match message {
|
|
Some(Control::Load { reply }) => {
|
|
let _ = reply.send(Ok(()));
|
|
}
|
|
Some(Control::Reconfigure { settings, reply }) => {
|
|
// Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds.
|
|
let answer = match on_engine(&engine, move |backend| backend.reconfigure(&settings)).await {
|
|
Ok(Ok(effective)) => Ok(effective),
|
|
Ok(Err(error)) => Err((
|
|
match error.code {
|
|
api::ErrorCode::InvalidRequest => 400,
|
|
api::ErrorCode::UnsupportedModel => 501,
|
|
api::ErrorCode::ResourceExhausted => 409,
|
|
api::ErrorCode::BackendUnavailable => 503,
|
|
api::ErrorCode::Internal => 500,
|
|
},
|
|
error.message,
|
|
)),
|
|
Err(message) => Err((500, message)),
|
|
};
|
|
let _ = reply.send(answer);
|
|
refresh_prefix_view(&engine, &config).await;
|
|
}
|
|
Some(Control::Unload { reply, .. }) => {
|
|
// The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP.
|
|
let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported);
|
|
}
|
|
None => control_closed = true,
|
|
},
|
|
command = requests.recv(), if !requests_closed => {
|
|
let Some(mut command) = command else {
|
|
requests_closed = true;
|
|
continue;
|
|
};
|
|
if command.result.is_closed()
|
|
|| command.queue.take().is_some_and(|ticket| !ticket.claim())
|
|
{
|
|
continue;
|
|
}
|
|
status.write().await.last_activity = Some(Instant::now());
|
|
let _activity = command.activity.take();
|
|
match serve_one(&engine, &config, &status, &mut shutdown, &mut command, &loaded)
|
|
.await
|
|
{
|
|
Served::Done => {
|
|
status.write().await.last_activity = Some(Instant::now());
|
|
refresh_prefix_view(&engine, &config).await;
|
|
}
|
|
Served::Shutdown => {
|
|
update(&status, WorkerState::Stopping, None).await;
|
|
return;
|
|
}
|
|
Served::Lost(reason) => {
|
|
crate::elog!("engine lost: {reason}");
|
|
update(&status, WorkerState::Failed, None).await;
|
|
continue 'attach;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Copy the engine's prefix-cache summary into the view the status endpoint reads.
|
|
async fn refresh_prefix_view(engine: &Engine, config: &BackendWorkerConfig) {
|
|
if let Some(view) = &config.prefix_view {
|
|
let summary = on_engine(engine, |backend| backend.prefix_cache_summary()).await.ok().flatten();
|
|
view.set(summary);
|
|
}
|
|
if let Some(view) = &config.memory_view {
|
|
let report = on_engine(engine, |backend| backend.memory_report()).await.ok().flatten();
|
|
view.set(report);
|
|
let telemetry = on_engine(engine, |backend| backend.telemetry_report()).await.ok().flatten();
|
|
view.set_telemetry(telemetry);
|
|
}
|
|
}
|
|
|
|
async fn trigger_cancel(engine: &Engine, request_id: &str) {
|
|
let id = request_id.to_owned();
|
|
// The engine may already have finished; "not active" is not an error here.
|
|
let _ = on_engine(engine, move |backend| backend.cancel(&id)).await;
|
|
}
|
|
|
|
/// One generation, from the contract request to the terminal event the HTTP layer sees.
|
|
async fn serve_one(
|
|
engine: &Engine,
|
|
config: &BackendWorkerConfig,
|
|
status: &RwLock<WorkerStatus>,
|
|
shutdown: &mut watch::Receiver<bool>,
|
|
command: &mut GenerationCommand,
|
|
loaded: &api::LoadedModel,
|
|
) -> Served {
|
|
let request = match prepare(config, &command.request).await {
|
|
Ok(request) => request,
|
|
Err(message) => {
|
|
send_failure(command.result.take(), message).await;
|
|
return Served::Done;
|
|
}
|
|
};
|
|
let id = request.request_id.clone();
|
|
let counted_input = u64::try_from(command.request.token_ids.len()).unwrap_or(u64::MAX);
|
|
status.write().await.metrics.start();
|
|
// The line is written once the engine has the request (its time is taken now), so a slow log sink cannot delay the start.
|
|
let start_ms = crate::worker::unix_ms();
|
|
let max_new = request.max_output_tokens;
|
|
let started = Instant::now();
|
|
let start = {
|
|
let _span = crate::stage_trace::span("engine_start");
|
|
let model = loaded.clone();
|
|
on_engine(engine, move |backend| {
|
|
backend.start_generation(&model, request)
|
|
})
|
|
.await
|
|
};
|
|
crate::elog!(
|
|
"generation start: t_unix_ms={start_ms} prompt_tokens={counted_input} max_new={max_new}"
|
|
);
|
|
let stream = match start {
|
|
Ok(Ok(stream)) => stream,
|
|
Ok(Err(error)) => {
|
|
status.write().await.metrics.fail();
|
|
let message = format!("engine refused the generation: {error}");
|
|
send_failure(command.result.take(), message.clone()).await;
|
|
return if error.code == api::ErrorCode::BackendUnavailable {
|
|
Served::Lost(message)
|
|
} else {
|
|
Served::Done
|
|
};
|
|
}
|
|
Err(message) => {
|
|
status.write().await.metrics.fail();
|
|
send_failure(command.result.take(), message.clone()).await;
|
|
return Served::Lost(message);
|
|
}
|
|
};
|
|
|
|
// The contract stream blocks; a thread moves it onto an async channel. Dropping the receiver
|
|
// ends the thread, and dropping the stream tells the engine nobody is listening.
|
|
let (pump, mut events) = mpsc::channel::<Result<api::GenerationEvent, api::StreamError>>(16);
|
|
std::thread::spawn(move || {
|
|
let mut stream = stream;
|
|
loop {
|
|
match stream.recv() {
|
|
Ok(Some(event)) => {
|
|
let last = matches!(event, api::GenerationEvent::Terminal(_));
|
|
if pump.blocking_send(Ok(event)).is_err() || last {
|
|
return;
|
|
}
|
|
}
|
|
Ok(None) => return,
|
|
Err(error) => {
|
|
let _ = pump.blocking_send(Err(error));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
let mut stops = leleka_serving_policy::stop::LiteralStops::new(&STOP_LITERALS);
|
|
let mut buffered: Vec<Event> = Vec::new();
|
|
let mut usage: Option<api::Usage> = None;
|
|
let mut cancel: Option<Cancel> = None;
|
|
let mut first_delta: Option<Instant> = None;
|
|
let mut delivered: u64 = 0;
|
|
let mut last_progress = Instant::now();
|
|
let deadline = config.generation_timeout.map(|limit| started + limit);
|
|
let mut drain_deadline: Option<Instant> = None;
|
|
let mut ticker = tokio::time::interval(Duration::from_secs(1));
|
|
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
|
ticker.reset();
|
|
|
|
macro_rules! begin_cancel {
|
|
($cause:expr) => {{
|
|
cancel = Some($cause);
|
|
drain_deadline = Some(Instant::now() + config.cancel_drain_timeout);
|
|
trigger_cancel(engine, &id).await;
|
|
}};
|
|
}
|
|
|
|
loop {
|
|
let item = tokio::select! {
|
|
biased;
|
|
_ = shutdown.changed() => {
|
|
trigger_cancel(engine, &id).await;
|
|
return Served::Shutdown;
|
|
}
|
|
_ = tokio::time::sleep_until(drain_deadline.unwrap_or_else(Instant::now)), if drain_deadline.is_some() => {
|
|
status.write().await.metrics.fail();
|
|
let message = match cancel.take() {
|
|
Some(Cancel::Failure(message)) => message,
|
|
_ => "engine did not terminate the generation after it was cancelled".to_owned(),
|
|
};
|
|
send_failure(command.result.take(), message.clone()).await;
|
|
return Served::Lost(message);
|
|
}
|
|
_ = tokio::time::sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() && cancel.is_none() => {
|
|
begin_cancel!(Cancel::Failure(
|
|
"generation exceeded configured execution deadline".to_owned()
|
|
));
|
|
continue;
|
|
}
|
|
_ = command.result.closed(), if cancel.is_none() => {
|
|
begin_cancel!(Cancel::Client);
|
|
continue;
|
|
}
|
|
_ = ticker.tick(), if config.stall_timeout.is_some() && cancel.is_none() => {
|
|
if let Some(limit) = config.stall_timeout
|
|
&& last_progress.elapsed() >= limit
|
|
{
|
|
begin_cancel!(Cancel::Failure(format!(
|
|
"engine made no progress for {} s during a request (stall watchdog)",
|
|
last_progress.elapsed().as_secs()
|
|
)));
|
|
}
|
|
continue;
|
|
}
|
|
item = events.recv() => item,
|
|
};
|
|
last_progress = Instant::now();
|
|
let event = match item {
|
|
Some(Ok(event)) => event,
|
|
Some(Err(api::StreamError::MissingTerminal)) | None => {
|
|
status.write().await.metrics.fail();
|
|
let message = match cancel.take() {
|
|
Some(Cancel::Failure(message)) => message,
|
|
_ => "engine stream ended without a terminal event".to_owned(),
|
|
};
|
|
send_failure(command.result.take(), message.clone()).await;
|
|
return Served::Lost(message);
|
|
}
|
|
};
|
|
match event {
|
|
api::GenerationEvent::TextDelta { text } => {
|
|
if cancel.is_some() {
|
|
continue;
|
|
}
|
|
first_delta.get_or_insert_with(Instant::now);
|
|
let piece = stops.push(&text);
|
|
if !piece.emit.is_empty() {
|
|
let retokenize = crate::stage_trace::time("delta_retokenize", || {
|
|
text_tokens(&config.tokenizer, &piece.emit)
|
|
});
|
|
match retokenize {
|
|
Ok(ids) => {
|
|
for id in ids {
|
|
delivered += 1;
|
|
deliver(command, &mut buffered, Event::Token(id)).await;
|
|
}
|
|
}
|
|
Err(message) => {
|
|
begin_cancel!(Cancel::Failure(message));
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
if piece.stopped {
|
|
begin_cancel!(Cancel::Marker);
|
|
}
|
|
}
|
|
api::GenerationEvent::Usage(report) => usage = Some(report),
|
|
api::GenerationEvent::ToolCallDelta { .. } => {
|
|
if cancel.is_none() {
|
|
begin_cancel!(Cancel::Failure(
|
|
"the engine sent a tool-call delta although it advertises native tool calls as unsupported".to_owned()
|
|
));
|
|
}
|
|
}
|
|
api::GenerationEvent::Terminal(terminal) => {
|
|
return conclude(
|
|
command,
|
|
status,
|
|
buffered,
|
|
terminal,
|
|
Conclusion {
|
|
cancel,
|
|
stops: &mut stops,
|
|
usage,
|
|
delivered,
|
|
started,
|
|
first_delta,
|
|
counted_input,
|
|
tokenizer: &config.tokenizer,
|
|
},
|
|
)
|
|
.await;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
struct Conclusion<'a> {
|
|
cancel: Option<Cancel>,
|
|
stops: &'a mut leleka_serving_policy::stop::LiteralStops,
|
|
usage: Option<api::Usage>,
|
|
delivered: u64,
|
|
started: Instant,
|
|
first_delta: Option<Instant>,
|
|
counted_input: u64,
|
|
tokenizer: &'a Tokenizer,
|
|
}
|
|
|
|
/// The terminal event of the engine, turned into the single terminal event the HTTP layer needs.
|
|
async fn conclude(
|
|
command: &mut GenerationCommand,
|
|
status: &RwLock<WorkerStatus>,
|
|
mut buffered: Vec<Event>,
|
|
terminal: api::GenerationTerminal,
|
|
mut state: Conclusion<'_>,
|
|
) -> Served {
|
|
let ended = Instant::now();
|
|
let prompt_ms = state
|
|
.first_delta
|
|
.unwrap_or(ended)
|
|
.duration_since(state.started)
|
|
.as_secs_f64()
|
|
* 1000.0;
|
|
let decode_ms = state
|
|
.first_delta
|
|
.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
|
|
let make_done = |reported: Option<&api::Usage>, finish: Finish, delivered: u64| {
|
|
let fallback = state.usage.as_ref();
|
|
let generated = reported
|
|
.or(fallback)
|
|
.map_or(delivered, |usage| usage.output_tokens);
|
|
Done {
|
|
generated,
|
|
prompt_tokens: reported
|
|
.or(fallback)
|
|
.map_or(state.counted_input, |usage| usage.input_tokens),
|
|
prompt_ms,
|
|
decode_ms,
|
|
finish,
|
|
drafts_accepted: None,
|
|
drafts_offered: None,
|
|
reused: reported
|
|
.or(fallback)
|
|
.map(|usage| usage.reused_input_tokens.min(usage.input_tokens)),
|
|
expert_hits: None,
|
|
expert_lookups: None,
|
|
}
|
|
};
|
|
let disconnected = matches!(state.cancel, Some(Cancel::Client)) || command.result.is_closed();
|
|
match terminal {
|
|
api::GenerationTerminal::Completed { reason, usage } => {
|
|
match state.cancel.take() {
|
|
Some(Cancel::Failure(message)) => {
|
|
status.write().await.metrics.fail();
|
|
send_failure(command.result.take(), message).await;
|
|
return Served::Done;
|
|
}
|
|
Some(Cancel::Client) => {
|
|
let done = make_done(Some(&usage), Finish::Cancel, state.delivered);
|
|
let _ = finish(command, buffered, done, true, status).await;
|
|
return Served::Done;
|
|
}
|
|
Some(Cancel::Marker) => {
|
|
let done = make_done(Some(&usage), Finish::Stop, state.delivered);
|
|
let _ = finish(command, buffered, done, disconnected, status).await;
|
|
return Served::Done;
|
|
}
|
|
None => {}
|
|
}
|
|
// The text ended without a marker: whatever was held back was ordinary text.
|
|
let tail = state.stops.finish();
|
|
if !tail.is_empty() {
|
|
match text_tokens(state.tokenizer, &tail) {
|
|
Ok(ids) => {
|
|
for id in ids {
|
|
state.delivered += 1;
|
|
deliver(command, &mut buffered, Event::Token(id)).await;
|
|
}
|
|
}
|
|
Err(message) => {
|
|
status.write().await.metrics.fail();
|
|
send_failure(command.result.take(), message).await;
|
|
return Served::Done;
|
|
}
|
|
}
|
|
}
|
|
if usage.input_tokens != state.counted_input {
|
|
crate::elog!(
|
|
"the engine counted {} input tokens, the control plane {}",
|
|
usage.input_tokens,
|
|
state.counted_input
|
|
);
|
|
}
|
|
let finish_reason = match reason {
|
|
api::FinishReason::Length => Finish::Length,
|
|
// Tool calls are parsed from the text by this server, never taken from the engine.
|
|
api::FinishReason::Stop | api::FinishReason::ToolCalls => Finish::Stop,
|
|
};
|
|
let done = make_done(Some(&usage), finish_reason, state.delivered);
|
|
let _ = finish(command, buffered, done, disconnected, status).await;
|
|
Served::Done
|
|
}
|
|
api::GenerationTerminal::Cancelled => {
|
|
match state.cancel.take() {
|
|
Some(Cancel::Marker) => {
|
|
let done = make_done(None, Finish::Stop, state.delivered);
|
|
let _ = finish(command, buffered, done, disconnected, status).await;
|
|
}
|
|
Some(Cancel::Client) => {
|
|
let done = make_done(None, Finish::Cancel, state.delivered);
|
|
let _ = finish(command, buffered, done, true, status).await;
|
|
}
|
|
Some(Cancel::Failure(message)) => {
|
|
status.write().await.metrics.fail();
|
|
send_failure(command.result.take(), message).await;
|
|
}
|
|
None => {
|
|
status.write().await.metrics.fail();
|
|
send_failure(
|
|
command.result.take(),
|
|
"the engine cancelled the generation without a request".to_owned(),
|
|
)
|
|
.await;
|
|
}
|
|
}
|
|
Served::Done
|
|
}
|
|
api::GenerationTerminal::Failed { message, code, .. } => {
|
|
status.write().await.metrics.fail();
|
|
let message = if message.is_empty() {
|
|
format!("engine generation failed ({code:?})")
|
|
} else {
|
|
message
|
|
};
|
|
send_failure(command.result.take(), message).await;
|
|
Served::Done
|
|
}
|
|
}
|
|
}
|