fix(websockets) ignore metadata for incremental requests (#30770)

## Summary
The Responses API may or may not send back metadata on response items.
So when comparing request data to the last response, we should discard
it and only consider the content. This change results in a higher
success rate of incremental requests.

Notably, there is one subtle change to the behavior here - we are
now ignoring metadata when comparing the previous request items to the
new request items as well. This should be fine, since the metadata is
explicitly out of scope for the comparison, regardless of whether the
item is an item from the request or response.

## Testing
- [x] Added unit test coverage for both cases of metadata existence and
absence.
This commit is contained in:
Dylan Hurd
2026-07-02 13:33:28 -07:00
committed by GitHub
parent 0ccb676dd0
commit b35d4b6b9d
2 changed files with 89 additions and 32 deletions
+26 -20
View File
@@ -1123,42 +1123,48 @@ impl ModelClientSession {
}
}
/// Checks whether the current request is an incremental extension of the previous request.
/// We only reuse an incremental input delta when non-input request fields are unchanged and
/// `input` is a strict extension of the previous known input. Server-returned output items
/// are treated as part of the baseline so we do not resend them.
fn get_incremental_items(
&self,
request: &ResponsesApiRequest,
last_response: Option<&LastResponse>,
allow_empty_delta: bool,
) -> Option<Vec<ResponseItem>> {
// Checks whether the current request is an incremental extension of the previous request.
// We only reuse an incremental input delta when non-input request fields are unchanged and
// `input` is a strict
// extension of the previous known input. Server-returned output items are treated as part
// of the baseline so we do not resend them.
let previous_request = self.websocket_session.last_request.as_ref()?;
if !responses_request_properties_match(previous_request, request) {
trace!("incremental request failed, websocket reuse properties didn't match");
return None;
}
let Some(after_previous_input) = request
.input
.strip_prefix(previous_request.input.as_slice())
else {
trace!("incremental request failed, items didn't match");
return None;
};
let mut response_items =
last_response.map_or_else(Vec::new, |response| response.items_added.clone());
if !self.client.state.provider.info().is_openai() {
response_items
.iter_mut()
.for_each(ResponseItem::clear_internal_chat_message_metadata_passthrough);
// To compare the inputs, we concatenate the previous request items with the response items,
// then compare that against the equivalent slice of request items, ignoring metadata. If
// they match, we can consider the remaining items the incremental request.
let mut previous_items = previous_request.input.clone();
if let Some(response) = last_response {
previous_items.extend_from_slice(&response.items_added);
}
let Some(incremental_items) = after_previous_input.strip_prefix(response_items.as_slice())
previous_items
.iter_mut()
.for_each(ResponseItem::clear_internal_chat_message_metadata_passthrough);
let Some((request_items_to_compare, incremental_items)) =
request.input.split_at_checked(previous_items.len())
else {
trace!("incremental request failed, items didn't match");
trace!("incremental request failed, incompatible request length");
return None;
};
let mut request_prefix = request_items_to_compare.to_vec();
request_prefix
.iter_mut()
.for_each(ResponseItem::clear_internal_chat_message_metadata_passthrough);
if previous_items != request_prefix {
trace!("incremental request failed, items didn't match");
return None;
}
if !allow_empty_delta && incremental_items.is_empty() {
return None;
}
+63 -12
View File
@@ -966,35 +966,77 @@ async fn responses_websocket_v2_requests_use_v2_when_provider_supports_websocket
async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() {
skip_if_no_network!();
let mut assistant_output_with_turn_id = ev_assistant_message("msg-1", "assistant output");
assistant_output_with_turn_id["item"]["internal_chat_message_metadata_passthrough"] =
json!({ "turn_id": "turn-1" });
let assistant_output_without_turn_id = ev_assistant_message("msg-2", "second assistant output");
let server = start_websocket_server(vec![vec![
vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "assistant output"),
assistant_output_with_turn_id,
ev_completed("resp-1"),
],
vec![ev_response_created("resp-2"), ev_completed("resp-2")],
vec![
ev_response_created("resp-2"),
assistant_output_without_turn_id,
ev_completed("resp-2"),
],
vec![ev_response_created("resp-3"), ev_completed("resp-3")],
]])
.await;
let harness = websocket_harness_with_options(&server, /*runtime_metrics_enabled*/ false).await;
let prompt_one = prompt_with_input(vec![message_item("hello")]);
let prompt_two = prompt_with_input(vec![
message_item("hello"),
assistant_message_item("msg-1", "assistant output"),
message_item("second"),
]);
// use OpenAI provider to check metadata logic
let mut provider = websocket_provider(&server);
provider.name = ModelProviderInfo::create_openai_provider(/*base_url*/ None).name;
let harness =
websocket_harness_with_provider_options(provider, /*runtime_metrics_enabled*/ false).await;
// Turn one: initiate
let prompt_one = prompt_with_input(vec![message_item("hello")]);
{
let mut client_session = harness.client.new_session();
stream_until_complete(&mut client_session, &harness, &prompt_one).await;
}
let mut client_session = harness.client.new_session();
stream_until_complete(&mut client_session, &harness, &prompt_two).await;
// Turn two: the response and reconstructed history have matching metadata.
let mut first_assistant_output = assistant_message_item("msg-1", "assistant output");
first_assistant_output.set_turn_id_if_missing("turn-1");
let prompt_two = prompt_with_input(vec![
message_item("hello"),
first_assistant_output.clone(),
message_item("second"),
]);
{
let mut client_session = harness.client.new_session();
stream_until_complete(&mut client_session, &harness, &prompt_two).await;
}
// Turn three: the reconstructed history has metadata that the response omitted.
let mut second_assistant_output = assistant_message_item("msg-2", "second assistant output");
second_assistant_output.set_turn_id_if_missing("turn-2");
let prompt_three = prompt_with_input(vec![
message_item("hello"),
first_assistant_output,
message_item("second"),
second_assistant_output,
message_item("third"),
]);
{
let mut client_session = harness.client.new_session();
stream_until_complete(&mut client_session, &harness, &prompt_three).await;
}
assert_eq!(server.handshakes().len(), 1);
let connection = server.single_connection();
assert_eq!(connection.len(), 2);
assert_eq!(connection.len(), 3);
// validate second turn
let second = connection.get(1).expect("missing request").body_json();
assert_eq!(second["type"].as_str(), Some("response.create"));
assert_eq!(second["previous_response_id"].as_str(), Some("resp-1"));
@@ -1003,6 +1045,15 @@ async fn responses_websocket_v2_incremental_requests_are_reused_across_turns() {
serde_json::to_value(&prompt_two.input[2..]).unwrap()
);
// validate third turn
let third = connection.get(2).expect("missing request").body_json();
assert_eq!(third["type"].as_str(), Some("response.create"));
assert_eq!(third["previous_response_id"].as_str(), Some("resp-2"));
assert_eq!(
third["input"],
serde_json::to_value(&prompt_three.input[4..]).unwrap()
);
server.shutdown().await;
}