Report token budget exhaustion as incomplete Responses

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 04:19:14 +02:00
parent c0556922b6
commit 0bb8aeb764
2 changed files with 130 additions and 8 deletions
+129 -8
View File
@@ -311,7 +311,7 @@ pub async fn create(
"the Strata worker did not report DONE",
);
};
if done.finish != Finish::Stop {
if done.finish == Finish::Cancel {
return api_error(
StatusCode::BAD_GATEWAY,
"server_error",
@@ -378,7 +378,7 @@ pub async fn create(
reasoning_tokens: 0,
cached_tokens: done.reused.unwrap_or(0),
};
match ResponseTrace::build(
match ResponseTrace::build_with_terminal(
&request,
&[OutputItem::Text {
deltas: vec![output],
@@ -387,6 +387,7 @@ pub async fn create(
&id,
now.as_secs(),
now.as_secs(),
done.finish == Finish::Length,
) {
Ok(trace) => Json(trace.response).into_response(),
Err(message) => api_error(
@@ -483,7 +484,7 @@ fn stream_live_text(
_ => {}
}
}
if let Some(value) = done.filter(|value| value.finish == Finish::Stop) {
if let Some(value) = done.filter(|value| value.finish != Finish::Cancel) {
let delta = drain_utf8(&mut pending_bytes, true);
if !delta.is_empty() {
output.push_str(&delta);
@@ -499,7 +500,7 @@ fn stream_live_text(
reasoning_tokens: 0,
cached_tokens: value.reused.unwrap_or(0),
};
match ResponseTrace::build(
match ResponseTrace::build_with_terminal(
&request,
&[OutputItem::Text {
deltas: vec![output],
@@ -508,6 +509,7 @@ fn stream_live_text(
&id,
created_at,
completed_at,
value.finish == Finish::Length,
) {
Ok(trace) => {
for mut event in trace.events.into_iter().skip(5) {
@@ -702,6 +704,18 @@ impl ResponseTrace {
id: &str,
created_at: u64,
completed_at: u64,
) -> Result<Self, String> {
Self::build_with_terminal(request, items, usage, id, created_at, completed_at, false)
}
fn build_with_terminal(
request: &CreateRequest,
items: &[OutputItem],
usage: Usage,
id: &str,
created_at: u64,
completed_at: u64,
incomplete: bool,
) -> Result<Self, String> {
request
.validate()
@@ -786,7 +800,12 @@ impl ResponseTrace {
all_text.push_str(&whole);
emitter.push("response.output_text.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "text": whole, "logprobs": []}));
emitter.push("response.content_part.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part(&whole)}));
let done = json!({"id": item_id, "type": "message", "status": "completed", "role": "assistant", "content": [text_part(&whole)]});
let item_status = if incomplete {
"incomplete"
} else {
"completed"
};
let done = json!({"id": item_id, "type": "message", "status": item_status, "role": "assistant", "content": [text_part(&whole)]});
emitter.push(
"response.output_item.done",
json!({"response_id": id, "output_index": index, "item": done}),
@@ -842,8 +861,16 @@ impl ResponseTrace {
.checked_add(usage.output_tokens)
.ok_or("total token count overflows u64")?;
response["status"] = json!("completed");
response["completed_at"] = json!(completed_at);
response["status"] = json!(if incomplete {
"incomplete"
} else {
"completed"
});
if incomplete {
response["incomplete_details"] = json!({"reason": "max_output_tokens"});
} else {
response["completed_at"] = json!(completed_at);
}
response["output"] = json!(output);
response["usage"] = json!({
"input_tokens": usage.input_tokens,
@@ -852,7 +879,14 @@ impl ResponseTrace {
"output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens},
"total_tokens": total_tokens,
});
emitter.push("response.completed", json!({"response": response}));
emitter.push(
if incomplete {
"response.incomplete"
} else {
"response.completed"
},
json!({"response": response}),
);
Ok(Self {
response,
events: emitter.events,
@@ -1090,6 +1124,30 @@ mod tests {
);
}
#[test]
fn token_budget_creates_incomplete_terminal_response() {
let request = make_request(json!({}));
let trace = ResponseTrace::build_with_terminal(
&request,
&[OutputItem::Text {
deltas: vec!["partial".into()],
}],
usage(),
"resp_limited",
1,
2,
true,
)
.unwrap();
assert_eq!(trace.response["status"], "incomplete");
assert_eq!(
trace.response["incomplete_details"]["reason"],
"max_output_tokens"
);
assert_eq!(trace.response["output"][0]["status"], "incomplete");
assert_eq!(trace.events.last().unwrap()["type"], "response.incomplete");
}
#[test]
fn malformed_tool_calls_never_produce_a_completed_trace() {
let request = make_request(json!({"tools": [{"type": "function", "name": "lookup"}]}));
@@ -1289,6 +1347,69 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn worker_error_terminates_stream_as_failed() {
let (tokenizer, root) = test_tokenizer();
let (engine_events, source) = mpsc::channel(2);
let request = make_request(json!({"reasoning": {"effort": "none"}}));
let mut body = stream_live_text(request, tokenizer, source).into_body();
engine_events
.send(Err("mock worker failure".to_owned()))
.await
.unwrap();
drop(engine_events);
let mut events = Vec::new();
while let Some(frame) = body.frame().await {
events.push(parse_sse(&frame.unwrap().into_data().unwrap()));
}
assert_eq!(events.len(), 5);
assert_eq!(events[4]["type"], "response.failed");
assert_eq!(events[4]["response"]["status"], "failed");
assert_eq!(
events[4]["response"]["error"]["message"],
"mock worker failure"
);
assert_eq!(events[4]["sequence_number"], 4);
fs::remove_dir_all(root).unwrap();
}
#[tokio::test]
async fn token_budget_terminates_live_stream_as_incomplete() {
let (tokenizer, root) = test_tokenizer();
let (engine_events, source) = mpsc::channel(2);
let request = make_request(json!({"reasoning": {"effort": "none"}}));
let mut body = stream_live_text(request, tokenizer, source).into_body();
engine_events.send(Ok(Event::Token(79))).await.unwrap();
engine_events
.send(Ok(Event::Done(Done {
generated: 1,
prompt_tokens: 4,
prompt_ms: 1.0,
decode_ms: 2.0,
finish: Finish::Length,
drafts_accepted: None,
drafts_offered: None,
reused: None,
expert_hits: None,
expert_lookups: None,
})))
.await
.unwrap();
drop(engine_events);
let mut last = None;
while let Some(frame) = body.frame().await {
last = Some(parse_sse(&frame.unwrap().into_data().unwrap()));
}
let last = last.unwrap();
assert_eq!(last["type"], "response.incomplete");
assert_eq!(
last["response"]["incomplete_details"]["reason"],
"max_output_tokens"
);
assert_eq!(last["response"]["output"][0]["content"][0]["text"], "O");
fs::remove_dir_all(root).unwrap();
}
fn parse_sse(bytes: &[u8]) -> Value {
let text = std::str::from_utf8(bytes).unwrap();
let data = text
+1
View File
@@ -150,3 +150,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- The restricted `/v1/responses` text path now forwards worker token events through bounded channels as live SSE deltas. It emits `response.created`, `response.in_progress`, output item/content part events, UTF-8-safe text deltas, and a `response.completed` terminal event with continuous sequence numbers. A worker failure emits `response.failed`; dropping the client stream closes its worker receiver so the supervisor sends `STOP` and drains the current generation.
- A synthetic HTTP test received the first text delta before any `DONE` event, then checked the final text and event ordering. A resident mock worker accepted another request after its streaming receiver was dropped. A UTF-8 test checked tokens that split a multi-byte character. All 70 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. This validates the local protocol path only; no real model, Linux GPU, Codex tool call, or end-to-end throughput was tested.
- Follow-up terminal tests checked that worker errors produce `response.failed` and output-token exhaustion produces `response.incomplete` with `incomplete_details.reason=max_output_tokens`, in both the response trace and live SSE path. A length-limited response is no longer misreported as an HTTP gateway failure. All 73 Rust tests and Clippy with warnings denied passed locally.