Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

pa-ai/pa-core/pa-telemetry: retry silently dropped provider streams (#3197)

kt75c1fd01c4ca
diff --git a/crates/pa-ai/src/providers/openai_completions/stream.rs b/crates/pa-ai/src/providers/openai_completions/stream.rs
index 45a6f68083..03fd96a615 100644
--- a/crates/pa-ai/src/providers/openai_completions/stream.rs
+++ b/crates/pa-ai/src/providers/openai_completions/stream.rs
@@ -31,7 +31,9 @@ use crate::utils_inner::json_parse::{
parse_json_with_repair, parse_streaming_json, StreamingJsonAccumulator,
};
use crate::utils_inner::sse::{ServerSentEvent, SseDecoder};
-use crate::utils_inner::stream_failure::{record_stream_failure, ProviderError};
+use crate::utils_inner::stream_failure::{
+ record_stream_failure, stream_drop_failure, OpenStreamBlock, ProviderError,
+};
struct StreamingState {
output: AssistantMessage,
@@ -44,6 +46,10 @@ struct StreamingState {
next_reasoning_details_index: u64,
reasoning_details_block: Option<usize>,
response_service_tier: Option<String>,
+ /// The stop signal arrived in a chunk (`choices[0].finish_reason`).
+ saw_finish_reason: bool,
+ /// The SSE terminal marker (`data: [DONE]`) arrived.
+ saw_done_marker: bool,
}
impl StreamingState {
@@ -59,6 +65,8 @@ impl StreamingState {
next_reasoning_details_index: 0,
reasoning_details_block: None,
response_service_tier: None,
+ saw_finish_reason: false,
+ saw_done_marker: false,
}
}
@@ -246,6 +254,7 @@ fn handle_chunk(
}
if let Some(finish_reason) = choice.get("finish_reason").and_then(|value| value.as_str()) {
+ state.saw_finish_reason = true;
let (stop_reason, error_message) = map_stop_reason(finish_reason);
state.output.stop_reason = stop_reason;
if error_message.is_some() {
@@ -648,12 +657,18 @@ async fn run_stream(
};
let events = decoder.push_text(&chunk);
for event in &events {
+ if mark_done_marker(event, &mut state) {
+ continue;
+ }
if let Some(chunk) = parse_sse_event_data(event) {
handle_chunk(&chunk, model, cache_write_cost, &mut state, writer);
}
}
}
for event in decoder.finish() {
+ if mark_done_marker(&event, &mut state) {
+ continue;
+ }
if let Some(chunk) = parse_sse_event_data(&event) {
handle_chunk(&chunk, model, cache_write_cost, &mut state, writer);
}
@@ -690,15 +705,53 @@ async fn run_stream(
.unwrap_or_else(|| "Provider returned an error stop reason".to_string()),
));
}
+ // The drop: the provider ended the stream without its terminal marker —
+ // no stop signal (`finish_reason`), no `[DONE]`, no error frame. A
+ // healthy completion always carries one; an end without one means the
+ // response was cut off mid-flight, so the turn must not settle as a
+ // completed (partial or empty) message. Classified as the retryable
+ // `stream_drop` failure: the auto-retry arms re-issue the same request,
+ // and the exhaustion discloses instead of the silent empty turn.
+ if !state.saw_finish_reason && !state.saw_done_marker {
+ return Err(ProviderError::StreamFailure(stream_drop_failure(
+ open_stream_block(output),
+ )));
+ }
Ok(())
}
+/// Record the SSE terminal marker (`data: [DONE]`); `true` when the event
+/// carried it.
+fn mark_done_marker(event: &ServerSentEvent, state: &mut StreamingState) -> bool {
+ if event.data.trim() == "[DONE]" {
+ state.saw_done_marker = true;
+ true
+ } else {
+ false
+ }
+}
+
+/// The block a dropped stream was inside when the connection ended.
+fn open_stream_block(output: &AssistantMessage) -> OpenStreamBlock {
+ match output.content.last() {
+ Some(AssistantContent::Thinking(_)) => OpenStreamBlock::Thinking,
+ Some(AssistantContent::Text(_)) => OpenStreamBlock::Text,
+ Some(AssistantContent::ToolCall(_)) => OpenStreamBlock::ToolCall,
+ None => OpenStreamBlock::None,
+ }
+}
+
/// Parse the JSON payload of an SSE event; `None` for `[DONE]` and comments.
#[cfg(test)]
#[path = "stream_bench.rs"]
mod stream_bench;
+/// The stream-drop pins (the SSE fixtures that end without a stop signal).
+#[cfg(test)]
+#[path = "stream_drop.rs"]
+mod stream_drop;
+
fn parse_sse_event_data(event: &ServerSentEvent) -> Option<Value> {
if event.data.trim() == "[DONE]" {
return None;
diff --git a/crates/pa-ai/src/providers/openai_completions/stream_drop.rs b/crates/pa-ai/src/providers/openai_completions/stream_drop.rs
new file mode 100644
index 0000000000..1847425349
--- /dev/null
+++ b/crates/pa-ai/src/providers/openai_completions/stream_drop.rs
@@ -0,0 +1,212 @@
+//! The stream-drop pins: the SSE fixtures whose response body ends without
+//! the protocol's terminal marker, and the healthy shapes that must never
+//! classify as drops.
+//!
+//! The silent lane-death class: the provider (the internal glm-5.3 route)
+//! ends the response stream mid-block — no stop signal (`finish_reason`),
+//! no `[DONE]` marker, no error frame — and the turn must not settle as a
+//! completed message. Each dropped shape pins the retryable `stream_drop`
+//! failure; each healthy shape pins no drop.
+
+use super::*;
+use crate::event_stream::AssistantMessageEventExt;
+use serde_json::Value;
+use std::net::SocketAddr;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+/// Serve one SSE response body for the provider's POST and return the
+/// bound address (one connection per spawned server).
+async fn serve_sse(body: String) -> SocketAddr {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = vec![0u8; 8192];
+ let _ = socket.read(&mut request).await.unwrap();
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+ addr
+}
+
+/// Run the provider stream against the SSE body and return the terminal
+/// event plus the full event-type sequence.
+async fn stream_events(body: String) -> (Vec<&'static str>, AssistantMessageEvent) {
+ let addr = serve_sse(body).await;
+ let model: Model = serde_json::from_value(json!({
+ "id": "glm-test", "name": "GLM test", "api": "openai-completions",
+ "provider": "prime-inference", "baseUrl": format!("http://{addr}"),
+ "reasoning": true, "input": ["text"],
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
+ "contextWindow": 131_072, "maxTokens": 8192,
+ }))
+ .expect("test model");
+ let options = OpenAICompletionsOptions::from_base(crate::types::StreamOptions {
+ api_key: Some("test".into()),
+ ..Default::default()
+ });
+ let mut reader = stream_openai_completions(
+ &model,
+ &Context {
+ system_prompt: None,
+ messages: vec![],
+ tools: None,
+ },
+ Some(&options),
+ );
+ let mut event_types = Vec::new();
+ loop {
+ let Some(event) = reader.next_event().await else {
+ panic!("stream ended without a terminal event");
+ };
+ if event.is_terminal() {
+ return (event_types, event);
+ }
+ event_types.push(event.event_type());
+ }
+}
+
+/// The `provider_stream_failure` diagnostic's `details.kind` of a terminal
+/// error message, if any.
+fn failure_kind(message: &AssistantMessage) -> Option<String> {
+ message
+ .diagnostics
+ .as_ref()?
+ .iter()
+ .find(|diagnostic| diagnostic.type_ == "provider_stream_failure")
+ .and_then(|diagnostic| diagnostic.details.as_ref())
+ .and_then(|details| details.get("kind"))
+ .and_then(Value::as_str)
+ .map(str::to_string)
+}
+
+fn thinking_text(message: &AssistantMessage) -> Option<String> {
+ match message.content.first() {
+ Some(AssistantContent::Thinking(ThinkingContent { thinking, .. })) => {
+ Some(thinking.clone())
+ }
+ _ => None,
+ }
+}
+
+/// A thinking delta chunk (`finish_reason` still null — the stream is
+/// mid-block).
+const THINKING_DELTA: &str = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{\"reasoning_content\":\"Let me work through this step by step. First I\"},\"finish_reason\":null}]}\n\n";
+
+/// A text delta chunk (mid-block, no stop signal yet).
+const TEXT_DELTA: &str = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"Here is the first half of\"},\"finish_reason\":null}]}\n\n";
+
+/// The stop signal: the final chunk carries `finish_reason: "stop"`.
+const FINISH: &str = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n";
+
+/// The SSE terminal marker.
+const DONE: &str = "data: [DONE]\n\n";
+
+/// The dropped-mid-thinking fixture: the body ends inside a thinking block
+/// with no stop signal and no `[DONE]` — the fleet's death signature (the
+/// fresh spawn's first thinking block). The terminal event is the
+/// retryable `stream_drop` failure, never a completed message.
+#[tokio::test]
+async fn a_stream_dropped_mid_thinking_classifies_as_stream_drop() {
+ let (event_types, terminal) = stream_events(THINKING_DELTA.to_string()).await;
+ let AssistantMessageEvent::Error { error, .. } = terminal else {
+ panic!("a dropped stream must terminate with an error event");
+ };
+ assert_eq!(
+ error.stop_reason,
+ StopReason::Error,
+ "events: {event_types:?}"
+ );
+ let error_message = error.error_message.as_deref().unwrap_or_default();
+ assert!(error_message.contains("stream_drop"), "{error_message}");
+ assert!(error_message.contains("thinking block"), "{error_message}");
+ assert_eq!(failure_kind(&error).as_deref(), Some("stream_drop"));
+ // The partial thinking rides the failed message (the retry arm drops
+ // it from the context before re-issuing).
+ assert_eq!(
+ thinking_text(&error).as_deref(),
+ Some("Let me work through this step by step. First I"),
+ "the partial thinking block rides the failure"
+ );
+}
+
+/// A stream dropped mid-text classifies the same way.
+#[tokio::test]
+async fn a_stream_dropped_mid_text_classifies_as_stream_drop() {
+ let (_, terminal) = stream_events(TEXT_DELTA.to_string()).await;
+ let AssistantMessageEvent::Error { error, .. } = terminal else {
+ panic!("a dropped stream must terminate with an error event");
+ };
+ assert_eq!(error.stop_reason, StopReason::Error);
+ assert!(error
+ .error_message
+ .as_deref()
+ .unwrap_or_default()
+ .contains("text block"));
+ assert_eq!(failure_kind(&error).as_deref(), Some("stream_drop"));
+}
+
+/// A body that ends before any content (no block, no marker) is the same
+/// drop class — the silent empty turn the daemon used to complete.
+#[tokio::test]
+async fn an_empty_body_is_a_stream_drop_not_an_empty_turn() {
+ let (_, terminal) = stream_events(String::new()).await;
+ let AssistantMessageEvent::Error { error, .. } = terminal else {
+ panic!("an empty body must terminate with an error event");
+ };
+ assert_eq!(error.stop_reason, StopReason::Error);
+ assert!(error
+ .error_message
+ .as_deref()
+ .unwrap_or_default()
+ .contains("before any response content"));
+ assert_eq!(failure_kind(&error).as_deref(), Some("stream_drop"));
+}
+
+/// The healthy stream is unchanged: the stop signal (`finish_reason`) plus
+/// the `[DONE]` marker complete the turn with no error and no
+/// retryable classification.
+#[tokio::test]
+async fn a_healthy_stream_completes_without_a_drop() {
+ let body = format!("{THINKING_DELTA}{FINISH}{DONE}");
+ let (event_types, terminal) = stream_events(body).await;
+ let AssistantMessageEvent::Done { message, .. } = terminal else {
+ panic!("a healthy stream must complete: {event_types:?}");
+ };
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ assert_eq!(message.error_message, None);
+ assert!(message.diagnostics.is_none());
+ assert_eq!(
+ thinking_text(&message).as_deref(),
+ Some("Let me work through this step by step. First I")
+ );
+}
+
+/// The stop signal alone completes the turn: gateways that close without
+/// the `[DONE]` marker are completed streams, not drops.
+#[tokio::test]
+async fn a_finish_reason_without_done_marker_completes() {
+ let body = format!("{TEXT_DELTA}{FINISH}");
+ let (_, terminal) = stream_events(body).await;
+ let AssistantMessageEvent::Done { message, .. } = terminal else {
+ panic!("a finish_reason alone must complete the stream");
+ };
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ assert_eq!(message.error_message, None);
+}
+
+/// The `[DONE]` marker alone completes the turn: gateways that omit the
+/// final `finish_reason` chunk are completed streams, not drops.
+#[tokio::test]
+async fn a_done_marker_without_finish_reason_completes() {
+ let body = format!("{TEXT_DELTA}{DONE}");
+ let (_, terminal) = stream_events(body).await;
+ let AssistantMessageEvent::Done { message, .. } = terminal else {
+ panic!("a [DONE] alone must complete the stream");
+ };
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ assert_eq!(message.error_message, None);
+}
diff --git a/crates/pa-ai/src/utils_inner/stream_failure.rs b/crates/pa-ai/src/utils_inner/stream_failure.rs
index 76a7d91899..d3e74891c9 100644
--- a/crates/pa-ai/src/utils_inner/stream_failure.rs
+++ b/crates/pa-ai/src/utils_inner/stream_failure.rs
@@ -32,6 +32,10 @@ pub enum StreamFailureKind {
Permission,
InvalidRequest,
MalformedResponse,
+ /// The provider ended the response stream without its terminal marker:
+ /// mid-block, no stop signal, no error frame (the connection just
+ /// ends). Transient by nature — the same request can be re-issued.
+ StreamDrop,
Unknown,
}
@@ -524,6 +528,10 @@ const KIND_MESSAGES: &[(StreamFailureKind, &str)] = &[
StreamFailureKind::PaymentRequired,
"Provider requires payment",
),
+ (
+ StreamFailureKind::StreamDrop,
+ "Provider dropped the response stream",
+ ),
(StreamFailureKind::Unknown, "Provider stream failed"),
];
@@ -661,6 +669,49 @@ pub fn stream_failure_from_stop_reason(
StreamFailureError { message, info }
}
+/// Which content block a dropped stream was inside when the provider ended
+/// it (the disclosure detail names what the turn was mid-way through).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum OpenStreamBlock {
+ Thinking,
+ Text,
+ ToolCall,
+ /// No content block had opened yet (the stream died before any).
+ None,
+}
+
+/// Failure for a stream the provider ended without its terminal marker:
+/// the connection closed mid-block with no stop signal and no error frame
+/// (the silent drop class: the turn would otherwise settle as a completed
+/// message with no error anywhere). Retryable by nature — the auto-retry
+/// arms re-issue the same request — and disclosed as the `stream_drop`
+/// class when the retries exhaust.
+#[must_use]
+pub(crate) fn stream_drop_failure(open_block: OpenStreamBlock) -> StreamFailureError {
+ let detail = match open_block {
+ OpenStreamBlock::Thinking => {
+ "the stream ended inside a thinking block before the stop signal"
+ }
+ OpenStreamBlock::Text => "the stream ended inside a text block before the stop signal",
+ OpenStreamBlock::ToolCall => {
+ "the stream ended inside a tool-call block before the stop signal"
+ }
+ OpenStreamBlock::None => "the stream ended before any response content or stop signal",
+ };
+ let info = StreamFailureInfo {
+ kind: StreamFailureKind::StreamDrop,
+ provider_error_type: Some("stream_drop".to_string()),
+ status: None,
+ request_id: None,
+ retry_after_ms: None,
+ raw: None,
+ };
+ StreamFailureError {
+ message: stream_failure_message(&info, Some(detail)),
+ info,
+ }
+}
+
const MAX_RAW_LENGTH: usize = 2000;
#[must_use]
diff --git a/crates/pa-ai/src/utils_inner/stream_failure/tests.rs b/crates/pa-ai/src/utils_inner/stream_failure/tests.rs
index eea2a43011..0084677d3a 100644
--- a/crates/pa-ai/src/utils_inner/stream_failure/tests.rs
+++ b/crates/pa-ai/src/utils_inner/stream_failure/tests.rs
@@ -457,3 +457,41 @@ fn http_error_records_sdk_name() {
"Provider rejected the request (invalid_request_error, 400): bad"
);
}
+
+/// The stream-drop class: the failure names the class (the telemetry
+/// classifier's `stream_drop` token rides the message) and the detail
+/// names the block the stream was inside (the disclosure the silent
+/// drop class was missing).
+#[test]
+fn stream_drop_failures_disclose_the_class_and_block() {
+ let failure = stream_drop_failure(OpenStreamBlock::Thinking);
+ assert_eq!(failure.info.kind, StreamFailureKind::StreamDrop);
+ assert_eq!(
+ failure.info.provider_error_type.as_deref(),
+ Some("stream_drop")
+ );
+ assert_eq!(
+ failure.message,
+ "Provider dropped the response stream (stream_drop): the stream ended inside a thinking block before the stop signal"
+ );
+ assert_eq!(
+ format_stream_failure_message(&ProviderError::StreamFailure(failure.clone())),
+ failure.message
+ );
+ // The serialized kind is the telemetry/telemetry-classifier token.
+ let kind_json = serde_json::to_value(failure.info.kind).expect("kind serializes");
+ assert_eq!(kind_json, serde_json::json!("stream_drop"));
+
+ assert_eq!(
+ stream_drop_failure(OpenStreamBlock::Text).message,
+ "Provider dropped the response stream (stream_drop): the stream ended inside a text block before the stop signal"
+ );
+ assert_eq!(
+ stream_drop_failure(OpenStreamBlock::ToolCall).message,
+ "Provider dropped the response stream (stream_drop): the stream ended inside a tool-call block before the stop signal"
+ );
+ assert_eq!(
+ stream_drop_failure(OpenStreamBlock::None).message,
+ "Provider dropped the response stream (stream_drop): the stream ended before any response content or stop signal"
+ );
+}
diff --git a/crates/pa-core/src/session_engine/auto_retry.rs b/crates/pa-core/src/session_engine/auto_retry.rs
index 9d00afe583..3977bda958 100644
--- a/crates/pa-core/src/session_engine/auto_retry.rs
+++ b/crates/pa-core/src/session_engine/auto_retry.rs
@@ -263,742 +263,9 @@ fn with_stop_reason_aborted(mut message: AssistantMessage) -> AssistantMessage {
message
}
+// The inline unit battery moved to the child module at the same tree
+// position (session_engine::auto_retry::tests); its use-super glob keeps
+// resolving through this facade's bindings (the request-timing precedent,
+// #3084).
#[cfg(test)]
-mod tests {
- use super::super::provider_retry::UNBOUNDED_BACKOFF_MS;
- use super::*;
- use pa_agent::types::{AssistantContent, AssistantMessageDiagnostic, TextContent, Usage};
- use std::sync::Arc;
- use std::sync::Mutex;
-
- fn error_message(
- kind: Option<&str>,
- status: Option<u16>,
- retry_after_ms: Option<u64>,
- ) -> AssistantMessage {
- let details = serde_json::json!({
- "kind": kind,
- "status": status,
- "retryAfterMs": retry_after_ms,
- });
- AssistantMessage {
- content: vec![AssistantContent::Text(TextContent {
- text: String::new(),
- text_signature: None,
- })],
- api: String::new(),
- provider: "test".to_string(),
- model: "m".to_string(),
- response_model: None,
- response_id: None,
- diagnostics: Some(vec![AssistantMessageDiagnostic {
- kind: "provider_stream_failure".to_string(),
- timestamp: 0,
- error: None,
- details: Some(details),
- }]),
- usage: Usage::zero(),
- stop_reason: StopReason::Error,
- stop_reason_raw: None,
- error_message: Some("provider down".to_string()),
- timestamp: 0,
- }
- }
-
- fn ok_message() -> AssistantMessage {
- AssistantMessage {
- content: vec![AssistantContent::Text(TextContent {
- text: "done".to_string(),
- text_signature: None,
- })],
- api: String::new(),
- provider: "test".to_string(),
- model: "m".to_string(),
- response_model: None,
- response_id: None,
- diagnostics: None,
- usage: Usage::zero(),
- stop_reason: StopReason::Stop,
- stop_reason_raw: None,
- error_message: None,
- timestamp: 0,
- }
- }
-
- fn fast_policy() -> ProviderRetryPolicy {
- ProviderRetryPolicy {
- enabled: true,
- max_retries: 3,
- base_delay_ms: 5,
- max_retry_delay_ms: 50,
- max_delay_ms: UNBOUNDED_BACKOFF_MS,
- }
- }
-
- /// A `rate_limit` failure whose server-requested wait exceeds the cap
- /// parks the session when the park seam reports a park: the give-up
- /// status becomes the parked sentence (TS #2375).
- #[tokio::test]
- async fn quota_reset_beyond_cap_parks_through_the_seam() {
- let events = Arc::new(Mutex::new(Vec::new()));
- let parked_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events_for_emit = Arc::clone(&events);
- let parked_calls_for_seam = Arc::clone(&parked_calls);
- let mut seam = move |message: AssistantMessage, abort: &str| {
- let parked_calls = Arc::clone(&parked_calls_for_seam);
- let abort = abort.to_string();
- Box::pin(async move {
- parked_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- // The seam sees the failed message and the give-up
- // sentence; the park answers with the parked status.
- assert_eq!(message.stop_reason, StopReason::Error);
- assert!(abort.contains("Provider requested a 4363s wait"));
- Some(
- crate::session_engine::provider_park::ProviderParkOutcome {
- status_message: format!(
- "{abort}. Session parked until 2026-09-24T00:00:00.000Z and will resume automatically: {}",
- message.error_message.as_deref().unwrap_or("unknown error"),
- ),
- },
- )
- }) as crate::session_engine::provider_park::ParkFuture
- };
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || async { Ok(error_message(Some("rate_limit"), None, Some(4_363_000))) },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- Some(&mut seam),
- )
- .await
- .unwrap();
- assert_eq!(message.stop_reason, StopReason::Error);
- assert_eq!(
- parked_calls.load(std::sync::atomic::Ordering::SeqCst),
- 1,
- "the park seam runs exactly once at the give-up"
- );
- let events = events.lock().unwrap().clone();
- // One parked end, no retry starts.
- assert_eq!(events.len(), 1, "one parked end: {events:?}");
- let final_error = match events.as_slice() {
- [AutoRetryEvent::End {
- success: false,
- final_error: Some(final_error),
- ..
- }] => final_error.clone(),
- other => panic!("expected one parked end, got {other:?}"),
- };
- assert!(final_error.contains("Session parked until 2026-09-24T00:00:00.000Z"));
- }
-
- /// A park seam that declines keeps the give-up: the surfaced status
- /// stays the plain exceeds-cap sentence.
- #[tokio::test]
- async fn quota_reset_beyond_cap_keeps_the_give_up_when_the_seam_declines() {
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let mut seam = move |_message: AssistantMessage, _abort: &str| {
- Box::pin(async move { None }) as crate::session_engine::provider_park::ParkFuture
- };
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || async { Ok(error_message(Some("rate_limit"), None, Some(4_363_000))) },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- Some(&mut seam),
- )
- .await
- .unwrap();
- assert_eq!(message.stop_reason, StopReason::Error);
- let events = events.lock().unwrap().clone();
- let final_error = match events.as_slice() {
- [AutoRetryEvent::End {
- success: false,
- final_error: Some(final_error),
- ..
- }] => final_error.clone(),
- other => panic!("expected one give-up end, got {other:?}"),
- };
- assert!(final_error.contains("Provider requested a 4363s wait before retrying"));
- assert!(!final_error.contains("Session parked"));
- }
-
- /// The park seam is only consulted for quota failures: a
- /// server-requested wait on a non-quota failure keeps the give-up
- /// even when a park is armed (TS parks only from the usage path).
- #[tokio::test]
- async fn non_quota_exceeds_cap_never_consults_the_park_seam() {
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let seam_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let seam_ran_for_seam = Arc::clone(&seam_ran);
- let mut seam = move |_message: AssistantMessage, _abort: &str| {
- let seam_ran = Arc::clone(&seam_ran_for_seam);
- Box::pin(async move {
- seam_ran.store(true, std::sync::atomic::Ordering::SeqCst);
- None
- }) as crate::session_engine::provider_park::ParkFuture
- };
- let _ = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || async { Ok(error_message(Some("server_error"), None, Some(4_363_000))) },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- Some(&mut seam),
- )
- .await
- .unwrap();
- assert!(
- !seam_ran.load(std::sync::atomic::Ordering::SeqCst),
- "the park seam must not run for a non-quota failure"
- );
- }
-
- #[tokio::test]
- async fn transient_failure_is_retried_until_success_with_events() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
- if attempt < 3 {
- Ok(error_message(Some("server_error"), Some(500), None))
- } else {
- Ok(ok_message())
- }
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 3);
- assert_eq!(message.stop_reason, StopReason::Stop);
- // Two retry starts (one per retry) and one success end. The delays
- // sit in the jitter band around the 5ms/10ms ladder steps
- // (jittered: [4, 7] and [8, 14] with the ±20% rounding headroom).
- let events = events.lock().unwrap().clone();
- assert_eq!(events.len(), 3, "two starts + one end: {events:?}");
- let shape_matches = matches!(
- events.as_slice(),
- [
- AutoRetryEvent::Start {
- attempt: 1,
- max_attempts: 3,
- error_message: error_one,
- reason: RetryStartReason::Quick,
- ..
- },
- AutoRetryEvent::Start {
- attempt: 2,
- max_attempts: 3,
- error_message: error_two,
- reason: RetryStartReason::Quick,
- ..
- },
- AutoRetryEvent::End {
- success: true,
- attempt: 2,
- final_error: None,
- restored_model: None,
- },
- ] if error_one == "provider down" && error_two == "provider down"
- );
- assert!(shape_matches, "unexpected events: {events:?}");
- let delays: Vec<u64> = events
- .iter()
- .filter_map(|event| match event {
- AutoRetryEvent::Start { delay_ms, .. } => Some(*delay_ms),
- AutoRetryEvent::End { .. } => None,
- })
- .collect();
- assert_eq!(delays.len(), 2, "two retry starts: {events:?}");
- assert!(
- (4..=7).contains(&delays[0]) && (8..=14).contains(&delays[1]),
- "jittered delays {delays:?} outside the [4,7]/[8,14] bands"
- );
- }
-
- #[tokio::test]
- async fn exhausted_retries_surface_the_final_error() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("server_error"), None, None))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- // One initial attempt plus three retries.
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 4);
- assert_eq!(message.stop_reason, StopReason::Error);
- let events = events.lock().unwrap().clone();
- assert_eq!(
- events.last(),
- Some(&AutoRetryEvent::End {
- success: false,
- attempt: 3,
- final_error: Some("provider down".to_string()),
- restored_model: None,
- })
- );
- assert_eq!(events.len(), 4); // three starts + one end
- }
-
- /// SANCTIONED DIVERGENCE (the 402 diagnosis): a permanent provider
- /// failure on the first attempt still emits the failure-scoped
- /// `auto_retry_end` (attempt 0) — the disclosure row must fire for
- /// every provider failure, not only retry episodes.
- #[tokio::test]
- async fn permanent_failures_never_retry_but_disclose() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("invalid_request"), Some(400), None))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- // No retry happened, but the failure still discloses at attempt 0:
- // the outcome row is failure-scoped, not episode-scoped.
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some("provider down".to_string()),
- restored_model: None,
- }]
- );
- }
-
- /// THE 402 REGRESSION (the diagnosis's variant B): a wallet-drain 402
- /// (the `payment_required` kind, classified by status regardless of
- /// the body's `error.type` text) is permanent on the FIRST attempt —
- /// no retry ladder burns 13-15s on a dead wallet — and the
- /// failure-scoped disclosure still fires, so the turn never settles
- /// as a silent empty message.
- #[tokio::test]
- async fn payment_failures_settle_once_with_the_disclosure() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("payment_required"), Some(402), None))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some("provider down".to_string()),
- restored_model: None,
- }]
- );
- }
-
- /// TS #2472: a safety-filter failure (e.g. a `content_filter`
- /// rejection) is a deterministic rejection — one attempt, no retry
- /// loop — with the failure-scoped disclosure (attempt 0).
- #[tokio::test]
- async fn safety_failures_are_permanent_never_retry_but_disclose() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("safety"), Some(400), None))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(
- attempts.load(std::sync::atomic::Ordering::SeqCst),
- 1,
- "a safety rejection must not retry"
- );
- assert_eq!(message.stop_reason, StopReason::Error);
- // The failure-scoped disclosure still fires at attempt 0.
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some("provider down".to_string()),
- restored_model: None,
- }]
- );
- }
-
- /// A context overflow can never succeed unchanged (TS
- /// `_isRetryableError`'s overflow guard): the turn surfaces the error
- /// immediately so the compact-and-retry recovery owns it.
- #[tokio::test]
- async fn context_overflow_never_enters_the_retry_loop() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 200_000,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- let mut overflow = error_message(None, None, None);
- overflow.diagnostics = None;
- overflow.error_message =
- Some("prompt is too long: 213462 tokens > 200000 maximum".to_string());
- Ok(overflow)
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- assert!(events.lock().unwrap().is_empty());
- }
-
- #[tokio::test]
- async fn cancelled_wait_aborts_with_retry_cancelled() {
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let mut attempts = 0;
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- attempts += 1;
- async { Ok(error_message(Some("server_error"), None, None)) }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { false },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts, 1);
- assert_eq!(message.stop_reason, StopReason::Aborted);
- // TS `_retryAfterDelay`'s abort path closes the started retry.
- assert_eq!(
- events.lock().unwrap().last(),
- Some(&AutoRetryEvent::End {
- success: false,
- attempt: 1,
- final_error: Some("Retry cancelled".to_string()),
- restored_model: None,
- })
- );
- }
-
- #[tokio::test]
- async fn aborted_signal_racing_failure_stops_aborted() {
- let controller = pa_agent::abort::AbortController::new();
- controller.abort();
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- Some(&controller.signal()),
- || async { Ok(error_message(Some("server_error"), None, None)) },
- |_| async { Ok(()) },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(message.stop_reason, StopReason::Aborted);
- }
-
- #[tokio::test]
- async fn server_retry_after_over_cap_ends_the_loop() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("rate_limit"), Some(429), Some(500)))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- // The cap (50ms) rejects the server's 500ms wait on the first retry
- // request; the loop stops and reports the refused wait (TS
- // `exceeds-cap` end event, attempt 0 because no retry finished).
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some(
- "Provider requested a 1s wait before retrying (above retry.provider.maxRetryDelayMs=50ms): provider down"
- .to_string(),
- ),
- restored_model: None,
- }]
- );
- }
-
- /// A disabled retry policy never retries, but a provider failure
- /// still settles with the failure-scoped disclosure (attempt 0).
- #[tokio::test]
- async fn disabled_policy_never_retries_but_discloses() {
- let policy = ProviderRetryPolicy {
- enabled: false,
- ..fast_policy()
- };
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &policy,
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(error_message(Some("server_error"), None, None))
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some("provider down".to_string()),
- restored_model: None,
- }]
- );
- }
-
- #[tokio::test]
- async fn attempt_errors_propagate() {
- let error = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || async { Err(anyhow::anyhow!("turn crashed")) },
- |_| async { Ok(()) },
- |_| async { true },
- None,
- )
- .await
- .unwrap_err();
- assert_eq!(error.to_string(), "turn crashed");
- }
-
- /// The router's tool-use 404 ("No endpoints found that support tool
- /// use") is a permanent capability mismatch: the turn surfaces after
- /// one attempt with the failure-scoped disclosure (attempt 0), like
- /// the other non-retryable provider failures.
- #[tokio::test]
- async fn unsupported_tool_failures_surface_with_the_disclosure() {
- let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let events = Arc::new(Mutex::new(Vec::new()));
- let events_for_emit = Arc::clone(&events);
- let message = run_turn_with_auto_retry(
- &fast_policy(),
- 0,
- None,
- || {
- let attempts = Arc::clone(&attempts);
- async move {
- attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- let mut unsupported = error_message(Some("invalid_request"), Some(404), None);
- unsupported.error_message =
- Some("404 No endpoints found that support tool use.".to_string());
- Ok(unsupported)
- }
- },
- move |event| {
- let events = Arc::clone(&events_for_emit);
- async move {
- events.lock().unwrap().push(event);
- Ok(())
- }
- },
- |_| async { true },
- None,
- )
- .await
- .unwrap();
- assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert_eq!(message.stop_reason, StopReason::Error);
- // A provider rejection with a recorded stream failure discloses
- // even though no retry ran.
- assert_eq!(
- events.lock().unwrap().as_slice(),
- &[AutoRetryEvent::End {
- success: false,
- attempt: 0,
- final_error: Some("404 No endpoints found that support tool use.".to_string()),
- restored_model: None,
- }]
- );
- }
-}
+mod tests;
diff --git a/crates/pa-core/src/session_engine/auto_retry/tests.rs b/crates/pa-core/src/session_engine/auto_retry/tests.rs
new file mode 100644
index 0000000000..8a1ee22354
--- /dev/null
+++ b/crates/pa-core/src/session_engine/auto_retry/tests.rs
@@ -0,0 +1,884 @@
+//! The auto-retry unit battery: the retry-loop event surface, the
+//! park seam, and the stream-drop retry pins.
+use super::super::provider_retry::UNBOUNDED_BACKOFF_MS;
+use super::*;
+use pa_agent::types::{AssistantContent, AssistantMessageDiagnostic, TextContent, Usage};
+use std::sync::Arc;
+use std::sync::Mutex;
+
+fn error_message(
+ kind: Option<&str>,
+ status: Option<u16>,
+ retry_after_ms: Option<u64>,
+) -> AssistantMessage {
+ let details = serde_json::json!({
+ "kind": kind,
+ "status": status,
+ "retryAfterMs": retry_after_ms,
+ });
+ AssistantMessage {
+ content: vec![AssistantContent::Text(TextContent {
+ text: String::new(),
+ text_signature: None,
+ })],
+ api: String::new(),
+ provider: "test".to_string(),
+ model: "m".to_string(),
+ response_model: None,
+ response_id: None,
+ diagnostics: Some(vec![AssistantMessageDiagnostic {
+ kind: "provider_stream_failure".to_string(),
+ timestamp: 0,
+ error: None,
+ details: Some(details),
+ }]),
+ usage: Usage::zero(),
+ stop_reason: StopReason::Error,
+ stop_reason_raw: None,
+ error_message: Some("provider down".to_string()),
+ timestamp: 0,
+ }
+}
+
+fn ok_message() -> AssistantMessage {
+ AssistantMessage {
+ content: vec![AssistantContent::Text(TextContent {
+ text: "done".to_string(),
+ text_signature: None,
+ })],
+ api: String::new(),
+ provider: "test".to_string(),
+ model: "m".to_string(),
+ response_model: None,
+ response_id: None,
+ diagnostics: None,
+ usage: Usage::zero(),
+ stop_reason: StopReason::Stop,
+ stop_reason_raw: None,
+ error_message: None,
+ timestamp: 0,
+ }
+}
+
+fn fast_policy() -> ProviderRetryPolicy {
+ ProviderRetryPolicy {
+ enabled: true,
+ max_retries: 3,
+ base_delay_ms: 5,
+ max_retry_delay_ms: 50,
+ max_delay_ms: UNBOUNDED_BACKOFF_MS,
+ }
+}
+
+/// A `rate_limit` failure whose server-requested wait exceeds the cap
+/// parks the session when the park seam reports a park: the give-up
+/// status becomes the parked sentence (TS #2375).
+#[tokio::test]
+async fn quota_reset_beyond_cap_parks_through_the_seam() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let parked_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events_for_emit = Arc::clone(&events);
+ let parked_calls_for_seam = Arc::clone(&parked_calls);
+ let mut seam = move |message: AssistantMessage, abort: &str| {
+ let parked_calls = Arc::clone(&parked_calls_for_seam);
+ let abort = abort.to_string();
+ Box::pin(async move {
+ parked_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ // The seam sees the failed message and the give-up
+ // sentence; the park answers with the parked status.
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert!(abort.contains("Provider requested a 4363s wait"));
+ Some(
+ crate::session_engine::provider_park::ProviderParkOutcome {
+ status_message: format!(
+ "{abort}. Session parked until 2026-09-24T00:00:00.000Z and will resume automatically: {}",
+ message.error_message.as_deref().unwrap_or("unknown error"),
+ ),
+ },
+ )
+ }) as crate::session_engine::provider_park::ParkFuture
+ };
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || async { Ok(error_message(Some("rate_limit"), None, Some(4_363_000))) },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ Some(&mut seam),
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert_eq!(
+ parked_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the park seam runs exactly once at the give-up"
+ );
+ let events = events.lock().unwrap().clone();
+ // One parked end, no retry starts.
+ assert_eq!(events.len(), 1, "one parked end: {events:?}");
+ let final_error = match events.as_slice() {
+ [AutoRetryEvent::End {
+ success: false,
+ final_error: Some(final_error),
+ ..
+ }] => final_error.clone(),
+ other => panic!("expected one parked end, got {other:?}"),
+ };
+ assert!(final_error.contains("Session parked until 2026-09-24T00:00:00.000Z"));
+}
+
+/// A park seam that declines keeps the give-up: the surfaced status
+/// stays the plain exceeds-cap sentence.
+#[tokio::test]
+async fn quota_reset_beyond_cap_keeps_the_give_up_when_the_seam_declines() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let mut seam = move |_message: AssistantMessage, _abort: &str| {
+ Box::pin(async move { None }) as crate::session_engine::provider_park::ParkFuture
+ };
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || async { Ok(error_message(Some("rate_limit"), None, Some(4_363_000))) },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ Some(&mut seam),
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.stop_reason, StopReason::Error);
+ let events = events.lock().unwrap().clone();
+ let final_error = match events.as_slice() {
+ [AutoRetryEvent::End {
+ success: false,
+ final_error: Some(final_error),
+ ..
+ }] => final_error.clone(),
+ other => panic!("expected one give-up end, got {other:?}"),
+ };
+ assert!(final_error.contains("Provider requested a 4363s wait before retrying"));
+ assert!(!final_error.contains("Session parked"));
+}
+
+/// The park seam is only consulted for quota failures: a
+/// server-requested wait on a non-quota failure keeps the give-up
+/// even when a park is armed (TS parks only from the usage path).
+#[tokio::test]
+async fn non_quota_exceeds_cap_never_consults_the_park_seam() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let seam_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let seam_ran_for_seam = Arc::clone(&seam_ran);
+ let mut seam = move |_message: AssistantMessage, _abort: &str| {
+ let seam_ran = Arc::clone(&seam_ran_for_seam);
+ Box::pin(async move {
+ seam_ran.store(true, std::sync::atomic::Ordering::SeqCst);
+ None
+ }) as crate::session_engine::provider_park::ParkFuture
+ };
+ let _ = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || async { Ok(error_message(Some("server_error"), None, Some(4_363_000))) },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ Some(&mut seam),
+ )
+ .await
+ .unwrap();
+ assert!(
+ !seam_ran.load(std::sync::atomic::Ordering::SeqCst),
+ "the park seam must not run for a non-quota failure"
+ );
+}
+
+#[tokio::test]
+async fn transient_failure_is_retried_until_success_with_events() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
+ if attempt < 3 {
+ Ok(error_message(Some("server_error"), Some(500), None))
+ } else {
+ Ok(ok_message())
+ }
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 3);
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ // Two retry starts (one per retry) and one success end. The delays
+ // sit in the jitter band around the 5ms/10ms ladder steps
+ // (jittered: [4, 7] and [8, 14] with the ±20% rounding headroom).
+ let events = events.lock().unwrap().clone();
+ assert_eq!(events.len(), 3, "two starts + one end: {events:?}");
+ let shape_matches = matches!(
+ events.as_slice(),
+ [
+ AutoRetryEvent::Start {
+ attempt: 1,
+ max_attempts: 3,
+ error_message: error_one,
+ reason: RetryStartReason::Quick,
+ ..
+ },
+ AutoRetryEvent::Start {
+ attempt: 2,
+ max_attempts: 3,
+ error_message: error_two,
+ reason: RetryStartReason::Quick,
+ ..
+ },
+ AutoRetryEvent::End {
+ success: true,
+ attempt: 2,
+ final_error: None,
+ restored_model: None,
+ },
+ ] if error_one == "provider down" && error_two == "provider down"
+ );
+ assert!(shape_matches, "unexpected events: {events:?}");
+ let delays: Vec<u64> = events
+ .iter()
+ .filter_map(|event| match event {
+ AutoRetryEvent::Start { delay_ms, .. } => Some(*delay_ms),
+ AutoRetryEvent::End { .. } => None,
+ })
+ .collect();
+ assert_eq!(delays.len(), 2, "two retry starts: {events:?}");
+ assert!(
+ (4..=7).contains(&delays[0]) && (8..=14).contains(&delays[1]),
+ "jittered delays {delays:?} outside the [4,7]/[8,14] bands"
+ );
+}
+
+#[tokio::test]
+async fn exhausted_retries_surface_the_final_error() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("server_error"), None, None))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ // One initial attempt plus three retries.
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 4);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ let events = events.lock().unwrap().clone();
+ assert_eq!(
+ events.last(),
+ Some(&AutoRetryEvent::End {
+ success: false,
+ attempt: 3,
+ final_error: Some("provider down".to_string()),
+ restored_model: None,
+ })
+ );
+ assert_eq!(events.len(), 4); // three starts + one end
+}
+
+/// A failed turn carrying the `stream_drop` class (the provider ended
+/// the response stream mid-block without a stop signal).
+fn stream_drop_message() -> AssistantMessage {
+ let details = serde_json::json!({
+ "kind": "stream_drop",
+ "providerErrorType": "stream_drop",
+ });
+ AssistantMessage {
+ content: vec![AssistantContent::Text(TextContent {
+ text: String::new(),
+ text_signature: None,
+ })],
+ api: String::new(),
+ provider: "test".to_string(),
+ model: "m".to_string(),
+ response_model: None,
+ response_id: None,
+ diagnostics: Some(vec![AssistantMessageDiagnostic {
+ kind: "provider_stream_failure".to_string(),
+ timestamp: 0,
+ error: None,
+ details: Some(details),
+ }]),
+ usage: Usage::zero(),
+ stop_reason: StopReason::Error,
+ stop_reason_raw: None,
+ error_message: Some(
+ "Provider dropped the response stream (stream_drop): the stream ended inside a thinking block before the stop signal"
+ .to_string(),
+ ),
+ timestamp: 0,
+ }
+}
+
+/// The stream-drop pin (a): a provider that ends the stream mid-block
+/// (the retryable `stream_drop` class) is retried — the re-issued turn
+/// completes on the retry, never settling as the silent empty turn.
+#[tokio::test]
+async fn stream_drop_retries_until_the_turn_completes() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
+ if attempt < 2 {
+ Ok(stream_drop_message())
+ } else {
+ Ok(ok_message())
+ }
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ let events = events.lock().unwrap().clone();
+ // One retry start (naming the class), one success end.
+ assert!(
+ matches!(
+ events.as_slice(),
+ [
+ AutoRetryEvent::Start {
+ attempt: 1,
+ error_message,
+ ..
+ },
+ AutoRetryEvent::End {
+ success: true,
+ attempt: 1,
+ final_error: None,
+ restored_model: None,
+ }
+ ] if error_message.contains("stream_drop")
+ && error_message.contains("thinking block")
+ ),
+ "the retry fired for the drop: {events:?}"
+ );
+}
+
+/// The stream-drop pin (b): when the drop exhausts the retries, the
+/// failure row names the `stream_drop` class — never a silent empty
+/// turn.
+#[tokio::test]
+async fn stream_drop_exhausts_retries_surfacing_the_class() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(stream_drop_message())
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ // One initial attempt plus three retries.
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 4);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ let events = events.lock().unwrap().clone();
+ let final_error = match events.last() {
+ Some(AutoRetryEvent::End {
+ success: false,
+ attempt: 3,
+ final_error: Some(final_error),
+ restored_model: None,
+ }) => final_error.clone(),
+ other => panic!("the exhaustion must disclose the class: {other:?}"),
+ };
+ assert!(
+ final_error.contains("stream_drop") && final_error.contains("thinking block"),
+ "the failure row names the stream_drop class: {final_error}"
+ );
+ assert_eq!(events.len(), 4); // three starts + one end
+}
+
+/// SANCTIONED DIVERGENCE (the 402 diagnosis): a permanent provider
+/// failure on the first attempt still emits the failure-scoped
+/// `auto_retry_end` (attempt 0) — the disclosure row must fire for
+/// every provider failure, not only retry episodes.
+#[tokio::test]
+async fn permanent_failures_never_retry_but_disclose() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("invalid_request"), Some(400), None))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ // No retry happened, but the failure still discloses at attempt 0:
+ // the outcome row is failure-scoped, not episode-scoped.
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some("provider down".to_string()),
+ restored_model: None,
+ }]
+ );
+}
+
+/// THE 402 REGRESSION (the diagnosis's variant B): a wallet-drain 402
+/// (the `payment_required` kind, classified by status regardless of
+/// the body's `error.type` text) is permanent on the FIRST attempt —
+/// no retry ladder burns 13-15s on a dead wallet — and the
+/// failure-scoped disclosure still fires, so the turn never settles
+/// as a silent empty message.
+#[tokio::test]
+async fn payment_failures_settle_once_with_the_disclosure() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("payment_required"), Some(402), None))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some("provider down".to_string()),
+ restored_model: None,
+ }]
+ );
+}
+
+/// TS #2472: a safety-filter failure (e.g. a `content_filter`
+/// rejection) is a deterministic rejection — one attempt, no retry
+/// loop — with the failure-scoped disclosure (attempt 0).
+#[tokio::test]
+async fn safety_failures_are_permanent_never_retry_but_disclose() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("safety"), Some(400), None))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ attempts.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "a safety rejection must not retry"
+ );
+ assert_eq!(message.stop_reason, StopReason::Error);
+ // The failure-scoped disclosure still fires at attempt 0.
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some("provider down".to_string()),
+ restored_model: None,
+ }]
+ );
+}
+
+/// A context overflow can never succeed unchanged (TS
+/// `_isRetryableError`'s overflow guard): the turn surfaces the error
+/// immediately so the compact-and-retry recovery owns it.
+#[tokio::test]
+async fn context_overflow_never_enters_the_retry_loop() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 200_000,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let mut overflow = error_message(None, None, None);
+ overflow.diagnostics = None;
+ overflow.error_message =
+ Some("prompt is too long: 213462 tokens > 200000 maximum".to_string());
+ Ok(overflow)
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert!(events.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn cancelled_wait_aborts_with_retry_cancelled() {
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let mut attempts = 0;
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ attempts += 1;
+ async { Ok(error_message(Some("server_error"), None, None)) }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { false },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts, 1);
+ assert_eq!(message.stop_reason, StopReason::Aborted);
+ // TS `_retryAfterDelay`'s abort path closes the started retry.
+ assert_eq!(
+ events.lock().unwrap().last(),
+ Some(&AutoRetryEvent::End {
+ success: false,
+ attempt: 1,
+ final_error: Some("Retry cancelled".to_string()),
+ restored_model: None,
+ })
+ );
+}
+
+#[tokio::test]
+async fn aborted_signal_racing_failure_stops_aborted() {
+ let controller = pa_agent::abort::AbortController::new();
+ controller.abort();
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ Some(&controller.signal()),
+ || async { Ok(error_message(Some("server_error"), None, None)) },
+ |_| async { Ok(()) },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(message.stop_reason, StopReason::Aborted);
+}
+
+#[tokio::test]
+async fn server_retry_after_over_cap_ends_the_loop() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("rate_limit"), Some(429), Some(500)))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ // The cap (50ms) rejects the server's 500ms wait on the first retry
+ // request; the loop stops and reports the refused wait (TS
+ // `exceeds-cap` end event, attempt 0 because no retry finished).
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some(
+ "Provider requested a 1s wait before retrying (above retry.provider.maxRetryDelayMs=50ms): provider down"
+ .to_string(),
+ ),
+ restored_model: None,
+ }]
+ );
+}
+
+/// A disabled retry policy never retries, but a provider failure
+/// still settles with the failure-scoped disclosure (attempt 0).
+#[tokio::test]
+async fn disabled_policy_never_retries_but_discloses() {
+ let policy = ProviderRetryPolicy {
+ enabled: false,
+ ..fast_policy()
+ };
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &policy,
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(error_message(Some("server_error"), None, None))
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some("provider down".to_string()),
+ restored_model: None,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn attempt_errors_propagate() {
+ let error = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || async { Err(anyhow::anyhow!("turn crashed")) },
+ |_| async { Ok(()) },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "turn crashed");
+}
+
+/// The router's tool-use 404 ("No endpoints found that support tool
+/// use") is a permanent capability mismatch: the turn surfaces after
+/// one attempt with the failure-scoped disclosure (attempt 0), like
+/// the other non-retryable provider failures.
+#[tokio::test]
+async fn unsupported_tool_failures_surface_with_the_disclosure() {
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let events_for_emit = Arc::clone(&events);
+ let message = run_turn_with_auto_retry(
+ &fast_policy(),
+ 0,
+ None,
+ || {
+ let attempts = Arc::clone(&attempts);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let mut unsupported = error_message(Some("invalid_request"), Some(404), None);
+ unsupported.error_message =
+ Some("404 No endpoints found that support tool use.".to_string());
+ Ok(unsupported)
+ }
+ },
+ move |event| {
+ let events = Arc::clone(&events_for_emit);
+ async move {
+ events.lock().unwrap().push(event);
+ Ok(())
+ }
+ },
+ |_| async { true },
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert_eq!(message.stop_reason, StopReason::Error);
+ // A provider rejection with a recorded stream failure discloses
+ // even though no retry ran.
+ assert_eq!(
+ events.lock().unwrap().as_slice(),
+ &[AutoRetryEvent::End {
+ success: false,
+ attempt: 0,
+ final_error: Some("404 No endpoints found that support tool use.".to_string()),
+ restored_model: None,
+ }]
+ );
+}
diff --git a/crates/pa-core/src/session_engine/error_classify.rs b/crates/pa-core/src/session_engine/error_classify.rs
index 31a1b2a03d..9d3ad53591 100644
--- a/crates/pa-core/src/session_engine/error_classify.rs
+++ b/crates/pa-core/src/session_engine/error_classify.rs
@@ -55,6 +55,10 @@ pub const ERROR_DIAGNOSTICS: &[(&str, &str)] = &[
"malformed_response",
"Provider returned a malformed response.",
),
+ (
+ "stream_drop",
+ "The provider ended the response stream without a stop signal.",
+ ),
(
"context_limit",
"The request exceeded the model context limit.",
@@ -140,6 +144,7 @@ const CODE_SUBTYPES: &[(&str, &str)] = &[
("content_filter", "refusal"),
("safety", "refusal"),
("malformed_response", "malformed_response"),
+ ("stream_drop", "stream_drop"),
("context_length_exceeded", "context_limit"),
("context_window_exceeded", "context_limit"),
("ECONNRESET", "network_error"),
@@ -172,7 +177,7 @@ fn subtype_category(subtype: &str) -> &'static str {
| "credential_expired"
| "authentication_rejected" => "authentication",
"quota_exceeded" | "rate_limited" => "rate_limit",
- "network_error" => "network",
+ "network_error" | "stream_drop" => "network",
"timeout" => "timeout",
"provider_unavailable" => "provider_unavailable",
"context_limit" => "context_limit",
@@ -189,6 +194,7 @@ fn subtype_retryable(subtype: &str) -> bool {
"quota_exceeded"
| "rate_limited"
| "network_error"
+ | "stream_drop"
| "timeout"
| "provider_unavailable"
| "malformed_response"
@@ -404,6 +410,37 @@ mod tests {
assert_eq!(near_miss.subtype, "unknown");
}
+ #[test]
+ fn stream_drop_messages_classify_as_the_stream_drop_category() {
+ // The provider's drop disclosure (pa-ai `stream_drop_failure`):
+ // every block detail names the same class.
+ let classification = classify(
+ "Provider dropped the response stream (stream_drop): the stream ended inside a thinking block before the stop signal"
+ );
+ assert_eq!(classification.subtype, "stream_drop");
+ assert_eq!(classification.category, "network");
+ assert_eq!(classification.code, Some("stream_drop"));
+ assert_eq!(classification.classification_source, "typed_error");
+ assert!(classification.retryable);
+ // The raw message never uploads; the fixed diagnostic rides.
+ assert!(classification.safe_message.is_none());
+ assert_eq!(
+ classification.diagnostic,
+ "The provider ended the response stream without a stop signal."
+ );
+ assert!(pa_telemetry::ERROR_SUBTYPES.contains(&classification.subtype));
+ assert!(
+ pa_telemetry::ERROR_CODES.contains(&classification.code.unwrap()),
+ "the code token stays inside the catalog's safe vocabulary"
+ );
+ // The empty-stream variant classifies identically.
+ let empty = classify(
+ "Provider dropped the response stream (stream_drop): the stream ended before any response content or stop signal"
+ );
+ assert_eq!(empty.subtype, "stream_drop");
+ assert!(empty.retryable);
+ }
+
#[test]
fn unmatched_messages_get_the_generic_diagnostic() {
let classification = classify("Provider exploded with secret details about /home/user");
diff --git a/crates/pa-core/src/session_engine/provider_retry.rs b/crates/pa-core/src/session_engine/provider_retry.rs
index 5f84c090cc..3246d30094 100644
--- a/crates/pa-core/src/session_engine/provider_retry.rs
+++ b/crates/pa-core/src/session_engine/provider_retry.rs
@@ -500,9 +500,142 @@ mod tests {
0,
None
));
+ // A dropped stream is transient at every rung of the ladder: the
+ // provider ended the response mid-block without a stop signal, so
+ // re-issuing the same request can succeed.
+ for retries_performed in 0..3 {
+ assert!(
+ !is_permanent_provider_failure_kind(Some("stream_drop"), retries_performed, None),
+ "a stream_drop is retryable at rung {retries_performed}"
+ );
+ }
assert!(!is_permanent_provider_failure_kind(None, 0, None));
}
+ /// The stream-drop arc, end to end: the REAL provider against the
+ /// dropped-mid-thinking SSE fixture (no stop signal, no `[DONE]`),
+ /// through the real stream adapter and the retry driver — the retry
+ /// fires and the completion settles on the retry's healthy stream
+ /// (the fleet's death shape, replayed).
+ #[tokio::test]
+ async fn a_dropped_sse_stream_retries_and_completes_on_the_retry() {
+ use crate::session_engine::provider_adapter::{json_round_trip, real_stream_fn};
+ use pa_agent::stream::{LlmContext, StreamRequestOptions};
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ // The dropped body: a thinking delta, then the connection ends
+ // mid-block (no `finish_reason`, no `[DONE]`).
+ let dropped = "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{\"reasoning_content\":\"Let me work through\"},\"finish_reason\":null}]}\n\n";
+ // The healthy body the retry receives.
+ let healthy = "data: {\"id\":\"c2\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"Recovered on the retry.\"}}]}\n\ndata: {\"id\":\"c2\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-test\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n";
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ for body in [dropped, healthy] {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut request = vec![0u8; 8192];
+ let _ = socket.read(&mut request).await.unwrap();
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ socket.write_all(response.as_bytes()).await.unwrap();
+ }
+ });
+
+ let model: pa_types::ai::Model = serde_json::from_value(serde_json::json!({
+ "id": "glm-test", "name": "GLM test", "api": "openai-completions",
+ "provider": "prime-inference", "baseUrl": format!("http://{addr}"),
+ "reasoning": true, "input": ["text"],
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
+ "contextWindow": 131_072, "maxTokens": 8192,
+ }))
+ .unwrap();
+ let agent_model: pa_agent::types::Model = json_round_trip(&model).unwrap();
+ let stream_fn = real_stream_fn(Some("test".to_string()), model);
+
+ let policy = ProviderRetryPolicy {
+ enabled: true,
+ max_retries: 3,
+ base_delay_ms: 5,
+ max_retry_delay_ms: 50,
+ max_delay_ms: UNBOUNDED_BACKOFF_MS,
+ };
+ let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let attempts_for_attempt = std::sync::Arc::clone(&attempts);
+ let message = complete_with_provider_retry(
+ &policy,
+ None,
+ |_| async { true },
+ move || {
+ let stream_fn = std::sync::Arc::clone(&stream_fn);
+ let agent_model = agent_model.clone();
+ let attempts = std::sync::Arc::clone(&attempts_for_attempt);
+ async move {
+ attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let mut stream = stream_fn(
+ agent_model,
+ LlmContext::default(),
+ StreamRequestOptions::default(),
+ )
+ .await?;
+ stream.result().await
+ }
+ },
+ )
+ .await
+ .unwrap();
+ // The drop consumed one attempt; the retry completed the turn.
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ let AssistantContent::Text(text) = &message.content[0] else {
+ panic!("text content on the retried turn: {:?}", message.content);
+ };
+ assert_eq!(text.text, "Recovered on the retry.");
+ }
+
+ /// The one-shot completion arms (side questions, compaction,
+ /// refinement) take the `stream_drop` class through the same retry
+ /// ladder: a dropped stream retries and the completion settles on the
+ /// retry.
+ #[tokio::test]
+ async fn stream_drop_failures_retry_in_the_one_shot_arms() {
+ let policy = ProviderRetryPolicy {
+ enabled: true,
+ max_retries: 3,
+ base_delay_ms: 5,
+ max_retry_delay_ms: 50,
+ max_delay_ms: UNBOUNDED_BACKOFF_MS,
+ };
+ let attempts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let attempts_for_attempt = std::sync::Arc::clone(&attempts);
+ let message = complete_with_provider_retry(
+ &policy,
+ None,
+ |_| async { true },
+ move || {
+ let attempts = std::sync::Arc::clone(&attempts_for_attempt);
+ async move {
+ let attempt = attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
+ if attempt < 2 {
+ Ok(error_message(Some("stream_drop"), None, None))
+ } else {
+ Ok(ok_message())
+ }
+ }
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);
+ assert_eq!(message.stop_reason, StopReason::Stop);
+ let AssistantContent::Text(text) = &message.content[0] else {
+ panic!("text content");
+ };
+ assert_eq!(text.text, "done");
+ }
+
#[tokio::test]
async fn transient_failure_is_retried_until_success() {
let policy = ProviderRetryPolicy {
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index 6ce4474eca..dcf78ba504 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -32,7 +32,8 @@ pub const SCHEMA_VERSION: u64 = 2;
pub const ERROR_MESSAGE_POLICY_REVISION: u64 = 1;
/// The error-classifier revision (`classifier_revision` on `agent error`).
-pub const ERROR_CLASSIFIER_REVISION: u64 = 1;
+/// Bumped to 2 when the `stream_drop` subtype/code joined the vocabulary.
+pub const ERROR_CLASSIFIER_REVISION: u64 = 2;
// ---------------------------------------------------------------------------
// Rule kinds
@@ -210,6 +211,7 @@ pub const ERROR_SUBTYPES: &[&str] = &[
"provider_unavailable",
"refusal",
"malformed_response",
+ "stream_drop",
"context_limit",
"configuration_error",
"filesystem_error",
@@ -251,6 +253,7 @@ pub const ERROR_CODES: &[&str] = &[
"content_filter",
"safety",
"malformed_response",
+ "stream_drop",
"context_length_exceeded",
"context_window_exceeded",
"ENOENT",
diff --git a/crates/pa-telemetry/src/events.rs b/crates/pa-telemetry/src/events.rs
index e3bf3518c5..729745de32 100644
--- a/crates/pa-telemetry/src/events.rs
+++ b/crates/pa-telemetry/src/events.rs
@@ -641,7 +641,7 @@ mod tests {
serde_json::json!("rate_limit")
);
assert_eq!(properties["http_status"], serde_json::json!(429));
- assert_eq!(properties["classifier_revision"], serde_json::json!(1));
+ assert_eq!(properties["classifier_revision"], serde_json::json!(2));
assert!(!properties.contains_key("error_message"), "no raw message");
}
@@ -686,8 +686,10 @@ mod tests {
assert!(TOOL_CATEGORIES.contains(category));
}
assert!(ERROR_SUBTYPES.contains(&"rate_limited"));
+ assert!(ERROR_SUBTYPES.contains(&"stream_drop"));
assert!(ERROR_CATEGORIES.contains(&"rate_limit"));
assert!(ERROR_CODES.contains(&"unknown"));
+ assert!(ERROR_CODES.contains(&"stream_drop"));
assert!(CLASSIFICATION_SOURCES.contains(&"http_status"));
assert!(ERROR_COMPONENTS.contains(&"provider"));
assert!(ERROR_OPERATIONS.contains(&"stream"));