Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 71 additions & 10 deletions lib/bindings/python/rust/llm/kv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,72 @@ where
rt.block_on(selection::run_server(config.port, service))
}

#[cfg(feature = "select-service")]
use prompt_request::depythonize_prompt_request;

#[cfg(feature = "select-service")]
mod prompt_request {
use super::*;
use dynamo_kv_router::services::selection::PromptRequest;

/// Selection requests whose prompt `token_ids` the binding extracts itself.
pub(super) trait PromptRequestBody {
fn prompt_mut(&mut self) -> &mut PromptRequest;
}

macro_rules! impl_prompt_request_body {
($($ty:ty),*) => {
$(impl PromptRequestBody for $ty {
fn prompt_mut(&mut self) -> &mut PromptRequest {
&mut self.prompt
}
})*
};
}

impl_prompt_request_body!(
SelectRequest,
SelectAndReserveRequest,
ReservationRequest,
PotentialLoadsRequest,
OverlapScoresRequest
);

/// Depythonize a prompt-carrying request dict. `token_ids` is extracted with pyo3's typed
/// list conversion: pythonize's per-element serde path costs several times more per token,
/// all of it on the calling thread under the GIL.
pub(super) fn depythonize_prompt_request<T>(request: &Bound<'_, PyAny>) -> PyResult<T>
where
T: PromptRequestBody + for<'de> Deserialize<'de>,
{
let dict = request.downcast::<pyo3::types::PyDict>().ok();
let token_ids = match dict {
Some(dict) => match dict.get_item("token_ids")? {
Some(tokens) if !tokens.is_none() => Some(
tokens
.extract::<Vec<u32>>()
.map_err(|e| PyValueError::new_err(format!("token_ids: {e}")))?,
),
_ => None,
},
None => None,
};
let parsed: Result<T, _> = match (dict, token_ids.is_some()) {
(Some(dict), true) => {
let rest = dict.copy()?;
rest.del_item("token_ids")?;
depythonize(rest.as_any())
}
_ => depythonize(request),
};
let mut req = parsed.map_err(|e| PyValueError::new_err(e.to_string()))?;
if token_ids.is_some() {
req.prompt_mut().token_ids = token_ids;
}
Ok(req)
}
}

/// Map a [`SelectionError`] to a Python exception: invalid input becomes a
/// `ValueError`, anything else a `SelectionServiceError` carrying `kind` and
/// `status_code`.
Expand Down Expand Up @@ -793,8 +859,7 @@ impl SelectionService {

/// Per-worker KV-overlap scores for a prompt (dict, see `OverlapScoresRequest`).
fn overlap_scores<'p>(&self, py: Python<'p>, request: PyObject) -> PyResult<Bound<'p, PyAny>> {
let req: OverlapScoresRequest =
depythonize(request.bind(py)).map_err(|e| PyValueError::new_err(e.to_string()))?;
let req: OverlapScoresRequest = depythonize_prompt_request(request.bind(py))?;
let core = self.inner.clone();
crate::future_into_py(py, async move {
let resp = core.overlap_scores(req).await.map_err(selection_to_pyerr)?;
Expand All @@ -804,8 +869,7 @@ impl SelectionService {

/// Select the best worker by KV-overlap + load, no booking (dict, see `SelectRequest`).
fn select<'p>(&self, py: Python<'p>, request: PyObject) -> PyResult<Bound<'p, PyAny>> {
let req: SelectRequest =
depythonize(request.bind(py)).map_err(|e| PyValueError::new_err(e.to_string()))?;
let req: SelectRequest = depythonize_prompt_request(request.bind(py))?;
let core = self.inner.clone();
crate::future_into_py(py, async move {
let resp = core.select(req).await.map_err(selection_to_pyerr)?;
Expand All @@ -819,8 +883,7 @@ impl SelectionService {
py: Python<'p>,
request: PyObject,
) -> PyResult<Bound<'p, PyAny>> {
let req: SelectAndReserveRequest =
depythonize(request.bind(py)).map_err(|e| PyValueError::new_err(e.to_string()))?;
let req: SelectAndReserveRequest = depythonize_prompt_request(request.bind(py))?;
let core = self.inner.clone();
crate::future_into_py(py, async move {
let resp = core
Expand All @@ -838,8 +901,7 @@ impl SelectionService {
py: Python<'p>,
request: PyObject,
) -> PyResult<Bound<'p, PyAny>> {
let req: ReservationRequest =
depythonize(request.bind(py)).map_err(|e| PyValueError::new_err(e.to_string()))?;
let req: ReservationRequest = depythonize_prompt_request(request.bind(py))?;
let core = self.inner.clone();
crate::future_into_py(py, async move {
let resp = core
Expand Down Expand Up @@ -904,8 +966,7 @@ impl SelectionService {

/// Per-worker potential loads for a prompt, without booking (dict, see `PotentialLoadsRequest`).
fn potential_loads<'p>(&self, py: Python<'p>, request: PyObject) -> PyResult<Bound<'p, PyAny>> {
let req: PotentialLoadsRequest =
depythonize(request.bind(py)).map_err(|e| PyValueError::new_err(e.to_string()))?;
let req: PotentialLoadsRequest = depythonize_prompt_request(request.bind(py))?;
let core = self.inner.clone();
crate::future_into_py(py, async move {
let resp = core
Expand Down
87 changes: 60 additions & 27 deletions lib/kv-router/src/services/selection/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@

use std::sync::Arc;

use axum::body::Bytes;
use axum::extract::rejection::JsonRejection;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::extract::{FromRequest, Path, Query, Request, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, patch, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use tokio::net::TcpListener;

use crate::protocols::WorkerId;
Expand Down Expand Up @@ -85,12 +87,8 @@ async fn list_workers(
async fn select(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
payload: Result<Json<SelectRequest>, JsonRejection>,
PromptJson(req): PromptJson<SelectRequest>,
) -> Response {
let Json(req) = match payload {
Ok(payload) => payload,
Err(error) => return json_rejection(error),
};
match state
.service
.select_with_policy_class(req, policy_class_from_headers(&headers))
Expand All @@ -104,12 +102,8 @@ async fn select(
async fn select_and_reserve(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
payload: Result<Json<SelectAndReserveRequest>, JsonRejection>,
PromptJson(req): PromptJson<SelectAndReserveRequest>,
) -> Response {
let Json(req) = match payload {
Ok(payload) => payload,
Err(error) => return json_rejection(error),
};
match state
.service
.select_and_reserve_with_policy_class(req, policy_class_from_headers(&headers))
Expand All @@ -122,12 +116,8 @@ async fn select_and_reserve(

async fn create_reservation(
State(state): State<Arc<AppState>>,
payload: Result<Json<ReservationRequest>, JsonRejection>,
PromptJson(req): PromptJson<ReservationRequest>,
) -> Response {
let Json(req) = match payload {
Ok(payload) => payload,
Err(error) => return json_rejection(error),
};
match state.service.create_reservation(req).await {
Ok(response) => (StatusCode::CREATED, Json(response)).into_response(),
Err(error) => error.into_response(),
Expand Down Expand Up @@ -195,12 +185,8 @@ async fn loads(State(state): State<Arc<AppState>>, Query(params): Query<FilterQu

async fn potential_loads(
State(state): State<Arc<AppState>>,
payload: Result<Json<PotentialLoadsRequest>, JsonRejection>,
PromptJson(req): PromptJson<PotentialLoadsRequest>,
) -> Response {
let Json(req) = match payload {
Ok(payload) => payload,
Err(error) => return json_rejection(error),
};
match state.service.potential_loads(req).await {
Ok(response) => Json(response).into_response(),
Err(error) => error.into_response(),
Expand All @@ -209,12 +195,8 @@ async fn potential_loads(

async fn overlap_scores(
State(state): State<Arc<AppState>>,
payload: Result<Json<OverlapScoresRequest>, JsonRejection>,
PromptJson(req): PromptJson<OverlapScoresRequest>,
) -> Response {
let Json(req) = match payload {
Ok(payload) => payload,
Err(error) => return json_rejection(error),
};
match state.service.overlap_scores(req).await {
Ok(response) => Json(response).into_response(),
Err(error) => error.into_response(),
Expand All @@ -225,6 +207,57 @@ async fn dump_events(State(state): State<Arc<AppState>>) -> Response {
Json(state.service.indexer_snapshot().await).into_response()
}

/// axum's `Json` for prompt-carrying bodies, without `serde_path_to_error`: `Json`
/// tracks the path of every element it deserializes, which dominates parsing a large
/// `token_ids` array. Rejections keep `Json`'s statuses: 415 for a missing or non-JSON
/// `Content-Type`, 400 for malformed JSON, 422 for a body of the wrong shape.
struct PromptJson<T>(T);

impl<S: Send + Sync, T: DeserializeOwned> FromRequest<S> for PromptJson<T> {
type Rejection = Response;

async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
if !has_json_content_type(req.headers()) {
return Err(json_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"Expected request with `Content-Type: application/json`",
));
}
let body = Bytes::from_request(req, state)
.await
.map_err(|rejection| json_error(rejection.status(), rejection.body_text()))?;
serde_json::from_slice(&body).map(Self).map_err(|error| {
if error.is_data() {
json_error(
StatusCode::UNPROCESSABLE_ENTITY,
format!("Failed to deserialize the JSON body into the target type: {error}"),
)
} else {
json_error(
StatusCode::BAD_REQUEST,
format!("Failed to parse the request body as JSON: {error}"),
)
}
})
}
}

/// `application/json` or an `application/*+json` subtype, as axum's `Json` accepts.
fn has_json_content_type(headers: &HeaderMap) -> bool {
let Some(content_type) = headers
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
else {
return false;
};
let essence = content_type.split(';').next().unwrap_or_default().trim();
let Some((kind, subtype)) = essence.split_once('/') else {
return false;
};
kind.eq_ignore_ascii_case("application")
&& (subtype.eq_ignore_ascii_case("json") || subtype.to_ascii_lowercase().ends_with("+json"))
}

async fn not_found() -> Response {
json_error(StatusCode::NOT_FOUND, "route not found")
}
Expand Down
50 changes: 50 additions & 0 deletions lib/kv-router/src/services/selection/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,56 @@ fn prompt_request_cache_salt_changes_normalized_hashes() {
assert_ne!(salted.sequence_hashes, unsalted.sequence_hashes);
}

#[test]
fn prompt_carrying_requests_read_top_level_prompt_fields() {
let body = serde_json::json!({
"selection_id": "sel-1",
"worker_id": 7,
"token_ids": [1, 2, 3],
"cache_salt": "tenant-a",
});
let assert_prompt = |prompt: &PromptRequest| {
assert_eq!(prompt.token_ids.as_deref(), Some(&[1, 2, 3][..]));
assert_eq!(prompt.cache_namespace.as_deref(), Some("tenant-a"));
};

let select: SelectRequest = serde_json::from_value(body.clone()).unwrap();
assert_prompt(&select.prompt);
assert_eq!(select.selection_id.as_deref(), Some("sel-1"));
assert_eq!(select.model_name, DEFAULT_MODEL_NAME);
let reserve: SelectAndReserveRequest = serde_json::from_value(body.clone()).unwrap();
assert_prompt(&reserve.prompt);
let booking: ReservationRequest = serde_json::from_value(body.clone()).unwrap();
assert_prompt(&booking.prompt);
assert_eq!(booking.worker_id, Some(7));
let loads: PotentialLoadsRequest = serde_json::from_value(body.clone()).unwrap();
assert_prompt(&loads.prompt);
let scores: OverlapScoresRequest = serde_json::from_value(body).unwrap();
assert_prompt(&scores.prompt);
}

#[tokio::test]
async fn prompt_routes_keep_json_rejection_statuses() {
let untyped = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/select")
.body(Body::from(r#"{"token_ids":[1]}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(untyped.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);

let malformed = post(app(), "/select", "{").await;
assert_eq!(malformed.status(), StatusCode::BAD_REQUEST);

let wrong_shape = post(app(), "/select", r#"{"token_ids":"oops"}"#).await;
assert_eq!(wrong_shape.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert!(response_json(wrong_shape).await["error"].is_string());
}

#[test]
fn keyed_prompt_tracking_leaves_indexer_hashes_public() {
let mut key_file = NamedTempFile::new().unwrap();
Expand Down
Loading
Loading