env-read 14 -> 0 outside src/env_settings.rs (config/process_env.rs removed; typed text/number/path/mode accessors), glob-super-import 9 -> 0, allow-unused-imports 48 -> 0, 38 modules renamed by responsibility (worker_entry, serve_generation, file_download, pack_outputs, request_context, status_routes, ...). The hot-path code (admission, streaming, gRPC client) is untouched here. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
176 lines
7.2 KiB
Rust
176 lines
7.2 KiB
Rust
//! The edge between the HTTP layer's token ids and the text-level engine contract: request UUIDs, running blocking
|
|
//! engine calls off the async threads, the prompt and delta re-tokenization checks, and the refusal of requests the
|
|
//! text contract cannot carry. Every check fails closed so the engine never sees different tokens than were counted.
|
|
|
|
use super::{Arc, BackendWorkerConfig, Engine, Generate, Tokenizer, api};
|
|
|
|
/// The runtime gRPC contract names a request by UUID and refuses a repeated one.
|
|
pub(super) 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.
|
|
pub(super) 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.
|
|
pub(super) 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`.
|
|
pub(super) 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)
|
|
}
|
|
|
|
/// What the text-level engine contract cannot carry is refused with a message instead of being dropped.
|
|
fn refuse_unsupported(request: &Generate) -> Result<(), 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(concat!(
|
|
"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(),
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The prompt and the output budget must fit the engine's context and the runtime's limit.
|
|
fn check_budget(config: &BackendWorkerConfig, request: &Generate) -> Result<(), String> {
|
|
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
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The prompt text of a request whose ids carry control-token marks, or the canonical decoding of its ids.
|
|
async fn marked_or_decoded_prompt(
|
|
config: &BackendWorkerConfig,
|
|
request: &Generate,
|
|
marked: Option<std::sync::Arc<str>>,
|
|
) -> Result<String, String> {
|
|
let tokenizer = Arc::clone(&config.tokenizer);
|
|
let ids = request.token_ids.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())?
|
|
}
|
|
|
|
/// The text the engine is given for the ids the HTTP layer counted.
|
|
async fn engine_prompt(config: &BackendWorkerConfig, request: &Generate) -> Result<String, String> {
|
|
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 => marked_or_decoded_prompt(config, request, other.clone()).await?,
|
|
};
|
|
drop(prompt_span);
|
|
Ok(prompt)
|
|
}
|
|
|
|
/// Map an HTTP-layer request onto the engine contract, or say what cannot be carried.
|
|
pub(super) async fn prepare(
|
|
config: &BackendWorkerConfig,
|
|
request: &Generate,
|
|
) -> Result<api::GenerationRequest, String> {
|
|
refuse_unsupported(request)?;
|
|
check_budget(config, request)?;
|
|
let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling)
|
|
.map_err(|error| format!("sampling: {error}"))?;
|
|
let prompt = engine_prompt(config, request).await?;
|
|
Ok(api::GenerationRequest {
|
|
request_id: request.obs.id().unwrap_or_else(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,
|
|
},
|
|
})
|
|
}
|