Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
42 changes: 36 additions & 6 deletions helios/src/server/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,15 +415,31 @@ pub(super) async fn generate(
let mut raw_tokens = Vec::new();
let mut timestamps = Vec::new();
let mut reused_total = 0;
// Prompt cached usage reads each prompt's first choice (`step_by(choices)`).
// Track only representative first choices whose `first_token` is still pending.
let mut pending_cached: Vec<usize> = if continuous_usage {
(0..size)
.step_by(decoded.request.choices)
.filter(|&i| generations[i].is_some())
.collect()
} else {
Vec::new()
};
if streaming && protocol == Protocol::Chat {
// Chat has one choice and rejects streamed prompt logprobs, so no
// output queue needs draining before the first raw token is ready.
if let Some(generation) = generations[0].as_mut()
&& let Err(error) = generation.wait_for_first_token().await
{
let frame = encoder.failure(&error);
yield Delivery::Failed(error, frame);
return;
if let Some(generation) = generations[0].as_mut() {
match generation.wait_for_first_token().await {
Ok(reused_prompt_tokens) => {
encoder.report_cached_tokens(0, reused_prompt_tokens);
pending_cached.clear();
}
Err(error) => {
let frame = encoder.failure(&error);
yield Delivery::Failed(error, frame);
return;
}
}
}
}
for mut frame in encoder.start() {
Expand Down Expand Up @@ -505,6 +521,20 @@ pub(super) async fn generate(
timestamp_ns,
} => {
if continuous_usage {
if !pending_cached.is_empty() {
pending_cached.retain(|&i| {
let Some(generation) = generations[i].as_mut() else {
return false;
};
match generation.take_reused_prompt_tokens() {
Some(reused) => {
encoder.report_cached_tokens(i, reused);
false
}
None => generation.has_pending_first_token(),
}
});
}
encoder.observe_generated_token(index);
encoder.report_reasoning_tokens(index, decoders[index].reasoning_tokens());
}
Expand Down
5 changes: 5 additions & 0 deletions helios/src/server/protocol/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,11 @@ impl Encoder {
pub fn observe_generated_token(&mut self, index: usize) {
self.usage[index].generated += 1;
}
/// Record the reused prompt tokens finalized when a choice produces its
/// first token so streaming usage reports cache hits before `finish`.
pub fn report_cached_tokens(&mut self, index: usize, cached: u64) {
self.usage[index].cached = cached;
}
/// Record how many of a choice's generated tokens the output pipeline
/// published as reasoning. The count is absolute, so streaming usage can
/// refresh it with the decoder's running total on every chunk.
Expand Down
108 changes: 108 additions & 0 deletions helios/src/server/protocol/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,114 @@ fn continuous_usage_sums_choices_without_counting_finished_choices_twice() {
assert_eq!(encoder.usage_value()["prompt_tokens"], 17);
}

#[test]
fn continuous_usage_reports_cached_tokens_before_finish() {
for protocol in [Protocol::Chat, Protocol::Completions] {
for cached in [0u64, 9] {
let mut encoder = Encoder::new(
protocol,
"c".into(),
"m".into(),
1,
1,
vec![PromptUsage {
tokens: 17,
image_tokens: 0,
}],
vec![],
ToolChoice::Auto,
true,
true,
json!({}),
);
encoder.set_continuous_usage(true);
encoder.report_cached_tokens(0, cached);
let start = encoder.start();
if protocol == Protocol::Chat {
assert_eq!(start.len(), 1);
assert_eq!(
start[0].data["usage"]["prompt_tokens_details"]["cached_tokens"],
cached
);
assert_eq!(start[0].data["usage"]["completion_tokens"], 0);
}
encoder.observe_generated_token(0);
let frames = encoder.apply(0, vec![Event::Content("hi".into())]).unwrap();
assert_eq!(frames.len(), 1);
assert_eq!(
frames[0].data["usage"]["prompt_tokens_details"]["cached_tokens"],
cached
);
assert_eq!(frames[0].data["usage"]["completion_tokens"], 1);
let terminal = encoder.finish(0, Termination::Eos, 1, cached, None).unwrap();
let usage_frames: Vec<_> = terminal
.iter()
.filter(|frame| frame.data["usage"].is_object())
.collect();
assert_eq!(usage_frames.len(), 2);
for frame in usage_frames {
assert_eq!(
frame.data["usage"]["prompt_tokens_details"]["cached_tokens"],
cached
);
assert_eq!(frame.data["usage"]["completion_tokens"], 1);
}
}
}
}

#[test]
fn continuous_usage_multi_choice_reports_first_choice_cached_tokens_per_prompt() {
let mut encoder = Encoder::new(
Protocol::Completions,
"c".into(),
"m".into(),
1,
2,
vec![
PromptUsage {
tokens: 10,
image_tokens: 0,
},
PromptUsage {
tokens: 12,
image_tokens: 0,
},
],
vec![],
ToolChoice::Auto,
true,
true,
json!({}),
);
encoder.set_continuous_usage(true);
for (choice, cached) in [(0, 5), (1, 9), (2, 3), (3, 7)] {
encoder.report_cached_tokens(choice, cached);
encoder.observe_generated_token(choice);
}
let frames = encoder
.apply(1, vec![Event::Content("sibling".into())])
.unwrap();
assert_eq!(
frames[0].data["usage"]["prompt_tokens_details"]["cached_tokens"],
8
);
for (choice, cached) in [(0, 5), (1, 9), (2, 3), (3, 7)] {
let terminal = encoder
.finish(choice, Termination::OutputLimit, 1, cached, None)
.unwrap();
for frame in terminal
.iter()
.filter(|frame| frame.data["usage"].is_object())
{
assert_eq!(
frame.data["usage"]["prompt_tokens_details"]["cached_tokens"],
8
);
}
}
}

#[test]
fn batch_stream_indices_echo_and_totals() {
let mut encoder = Encoder::new(
Expand Down
Loading