STRA-338 S23: the tool-call stream reads OutputEvent

responses/stream/tool_run.rs (the stream of a response whose request declares tools, no reasoning) takes the text and the
whole calls from a live OutputDecoder instead of draining UTF-8 and driving tool_output::Incremental itself;
ToolStream::event_item publishes an OutputEvent. The debug copy of a failed output and the notes log come from the
decoder. Proof: output_golden (132 captures) identical, strata-control lib tests 317 pass, gates green, 0 warnings.
This commit is contained in:
Pavlo Ratushnyi
2026-11-06 21:02:02 +01:00
parent eb003147a6
commit da6c080472
4 changed files with 48 additions and 51 deletions
+3 -2
View File
@@ -41,7 +41,7 @@ use crate::{
ports::{SharedClock, SharedResponseStore, response_store::InputItemsQuery},
response_tools::Catalog,
tokenizer::{LiteralMarks, Tokenizer},
tool_output::{self, Incremental, Segment},
tool_output,
wire::{Event, Finish, Generate},
worker::{GenerationCommand, GenerationResult, WorkerState},
};
@@ -99,7 +99,8 @@ pub use tool_recovery::set_tool_call_recovery;
use tool_recovery::{decode_generation, parse_output_items};
#[allow(unused_imports)]
use tool_recovery::{
decode_generation_with, decoded_items, log_tool_notes, parse_output_items_after, tool_options,
decode_generation_with, decoded_items, log_tool_notes, parse_output_items_after,
tool_call_recovery, tool_options,
};
// The pure part of the protocol lives in `leleka-gateway-domain`; the old paths stay.
+32 -43
View File
@@ -3,8 +3,9 @@
use super::tools::ToolStream;
use super::*;
use crate::wire::Done;
use leleka_gateway_domain::output::{LivePlan, OutputDecoder, OutputEvent, ReadPlan};
/// What the stream is doing between the worker's events: the published items, the pending bytes and the debug copy.
/// What the stream is doing between the worker's events: the published items and whether to keep the debug copy.
struct ToolsRun {
request: CreateRequest,
tokenizer: SharedCodec,
@@ -13,8 +14,7 @@ struct ToolsRun {
stream: ToolStream,
created_at: u64,
pending_response: Value,
debug_text: Option<String>,
pending_bytes: Vec<u8>,
keep_raw: bool,
}
pub(in crate::responses) fn stream_live_tools(
@@ -41,8 +41,7 @@ pub(in crate::responses) fn stream_live_tools(
items: Vec::new(),
},
created_at,
debug_text: debug_failed_output().then(String::new),
pending_bytes: Vec::new(),
keep_raw: debug_failed_output(),
};
tokio::spawn(run.run(initial.events));
sse_response(receiver)
@@ -68,25 +67,29 @@ impl ToolsRun {
};
self.stream.sequence = sent;
let catalog = Catalog::new(&self.request.tools).expect("validated tools");
let mut parser = Incremental::with_options(&catalog.flat, tool_options(false));
let Some(collected) = self.collect(&mut parser).await else {
let plan = LivePlan {
tools: Some(&catalog.flat),
recovery: tool_call_recovery(),
keep_raw: self.keep_raw,
};
let mut decoder = self.tokenizer.output_decoder(ReadPlan::Live(plan));
let Some(collected) = self.collect(&mut decoder).await else {
return;
};
let mut failure = collected.failure;
if let Some(done) = collected.done.filter(|done| done.finish != Finish::Cancel) {
match self.complete(&mut parser, &done).await {
match self.complete(&mut decoder, &done).await {
Flow::Finished => return,
Flow::Failed(message) => failure = Some(message),
}
}
self.fail(failure).await;
self.fail(failure, decoder.raw_text()).await;
}
/// Read the worker's events until DONE or a failure, publishing the text and calls the tokens complete.
/// `None`: the client is gone.
async fn collect(&mut self, parser: &mut Incremental<'_>) -> Option<Collected> {
async fn collect(&mut self, decoder: &mut OutputDecoder<'_>) -> Option<Collected> {
let terminal = self.tokenizer.terminal_ids();
let mut decoder = self.tokenizer.decoder();
let mut text_ended = false;
while let Some(result) = tokio::select! {
biased;
@@ -96,7 +99,7 @@ impl ToolsRun {
match classify(result, text_ended) {
Next::Token(token) if terminal.contains(&token) => text_ended = true,
Next::Token(token) => {
if let Err(error) = self.push_token(decoder.as_mut(), parser, token).await {
if let Err(error) = self.push_token(decoder, token).await {
return Some(Collected::failed(error));
}
}
@@ -107,49 +110,35 @@ impl ToolsRun {
Some(Collected::default())
}
/// Decode one token and publish the segments the text it completes makes whole.
/// Decode one token and publish the text and calls it makes whole.
async fn push_token(
&mut self,
decoder: DecoderRef<'_>,
parser: &mut Incremental<'_>,
decoder: &mut OutputDecoder<'_>,
token: u32,
) -> Result<(), String> {
let bytes = decoder.push(token)?;
self.pending_bytes.extend_from_slice(&bytes);
let delta = drain_utf8(&mut self.pending_bytes, false);
if delta.is_empty() {
return Ok(());
}
if let Some(text) = self.debug_text.as_mut() {
text.push_str(&delta);
}
let segments = parser.feed(&delta)?;
self.send_segments(segments).await
let events = decoder.push(token).map_err(|error| error.to_string())?;
self.send_events(events).await
}
async fn send_segments(&mut self, segments: Vec<Segment>) -> Result<(), String> {
for segment in segments {
async fn send_events(&mut self, events: Vec<OutputEvent>) -> Result<(), String> {
for event in events {
self.stream
.segment(&self.request, segment, self.created_at)
.event_item(&self.request, event, self.created_at)
.await?;
}
Ok(())
}
/// The worker is done: publish what is left, close the items, store the response and send the terminal event.
async fn complete(&mut self, parser: &mut Incremental<'_>, done: &Done) -> Flow {
let remaining = drain_utf8(&mut self.pending_bytes, true);
let parsed = parser.feed(&remaining).and_then(|mut segments| {
segments.extend(parser.finish_after(done.finish != Finish::Length)?);
Ok(segments)
});
log_tool_notes(parser.notes());
async fn complete(&mut self, decoder: &mut OutputDecoder<'_>, done: &Done) -> Flow {
let parsed = decoder.finish(done.finish);
log_tool_notes(decoder.notes());
let closed = match parsed {
Ok(segments) => {
self.close_items(segments, done.finish == Finish::Length)
Ok(events) => {
self.close_items(events, done.finish == Finish::Length)
.await
}
Err(error) => Err(error),
Err(error) => Err(error.to_string()),
};
match closed {
Ok(()) => self.publish(done).await,
@@ -159,10 +148,10 @@ impl ToolsRun {
async fn close_items(
&mut self,
segments: Vec<Segment>,
events: Vec<OutputEvent>,
incomplete: bool,
) -> Result<(), String> {
self.send_segments(segments).await?;
self.send_events(events).await?;
if self.stream.items.is_empty() {
self.stream.text(String::new()).await?;
}
@@ -194,10 +183,10 @@ impl ToolsRun {
Flow::Finished
}
async fn fail(mut self, failure: Option<String>) {
async fn fail(mut self, failure: Option<String>, raw_text: Option<&str>) {
let message = failure_message(failure);
log_generation_failure(&message);
if let Some(text) = &self.debug_text {
if let Some(text) = raw_text {
crate::elog!("failed output (STRATA_DEBUG_FAILED_OUTPUT): {text:?}");
}
let error = json!({"code": crate::memory_view::failure_code(&message), "message": message});
+7 -5
View File
@@ -1,6 +1,7 @@
//! Streaming of tool calls (moved from responses.rs, STRA-338 S6).
use super::*;
use leleka_gateway_domain::output::OutputEvent;
pub(super) struct ToolStream {
pub(super) sender: mpsc::Sender<Value>,
@@ -89,18 +90,19 @@ impl ToolStream {
self.event("response.output_item.done", fields).await
}
pub(super) async fn segment(
pub(super) async fn event_item(
&mut self,
request: &CreateRequest,
segment: Segment,
event: OutputEvent,
created_at: u64,
) -> Result<(), String> {
match segment {
Segment::Text(text) => self.text(text).await,
Segment::Call { name, arguments } => {
match event {
OutputEvent::Text(text) => self.text(text).await,
OutputEvent::Call { name, arguments } => {
self.call(request, name, arguments.to_string(), created_at)
.await
}
OutputEvent::ReasoningDelta(_) | OutputEvent::Reasoned { .. } => Ok(()),
}
}
+6 -1
View File
@@ -14,11 +14,16 @@ pub fn set_tool_call_recovery(on: bool) {
TOOL_CALL_RECOVERY.store(on, Ordering::Relaxed);
}
/// Whether the experimental recovery of drifted tool-call forms is on.
pub(super) fn tool_call_recovery() -> bool {
TOOL_CALL_RECOVERY.load(Ordering::Relaxed)
}
/// How tool calls are read: `natural_stop` as the generation ended, recovery as configured.
pub(super) fn tool_options(natural_stop: bool) -> tool_output::Options {
tool_output::Options {
natural_stop,
recovery: TOOL_CALL_RECOVERY.load(Ordering::Relaxed),
recovery: tool_call_recovery(),
}
}