Treat statusless bio and cyber policy errors as terminal (#62354)

## Why

When the Responses API sends a policy rejection in an `error` event
without an HTTP status, the SSE client can wait until its idle timeout
to report the failure.

## What changed

Recognize `bio_policy` and `cyber_policy` in the shared terminal error
parser so both SSE and WebSocket clients surface the corresponding
policy error. Preserve the provider's message and use a default when
it is missing or blank. End the SSE stream as soon as the error arrives.

## Testing

Add SSE tests for both error codes, including when the stream stays
open, and WebSocket cases that verify both errors surface without a
close handshake.

GitOrigin-RevId: 1b46b6557a39a61a1bb10bdd0d8ede48ecd6fa13
This commit is contained in:
Charlie Marsh
2026-11-18 20:17:25 +00:00
committed by copyberry
parent 097a8a7439
commit c5cff4335c
4 changed files with 74 additions and 22 deletions
+10
View File
@@ -139,6 +139,16 @@ pub(crate) fn parse_terminal_provider_error(
status,
})
}
("cyber_policy", None) => Some(ApiError::CyberPolicy {
message: message
.unwrap_or("This request has been flagged for possible cybersecurity risk.")
.to_owned(),
}),
("bio_policy", None) => Some(ApiError::BioPolicy {
message: message
.unwrap_or("This content was flagged for possible biological risk.")
.to_owned(),
}),
// HTTP 403s retain their request ID and headers in the API bridge.
("access_program_not_enabled", None) => Some(ApiError::AccessProgramNotEnabled {
message: message
+56
View File
@@ -714,6 +714,8 @@ async fn process_sse_with_treatment(
| ApiError::InferenceHookDenied { .. }
| ApiError::AccessProgramNotEnabled { .. }
| ApiError::ContentPolicyViolation { .. }
| ApiError::BioPolicy { .. }
| ApiError::CyberPolicy { .. }
| ApiError::ResponseIncomplete(_)
) {
let _ = tx_event.send(Err(error)).await;
@@ -1251,6 +1253,60 @@ mod tests {
assert_matches!(events[0], Err(ApiError::QuotaExceeded));
}
#[tokio::test]
async fn statusless_policy_error_events_are_terminal() {
for code in ["bio_policy", "cyber_policy"] {
let event = json!({
"type": "error",
"sequence_number": 0,
"error": {
"type": "invalid_request_error",
"code": code,
"message": "policy rejection",
},
});
let sse = format!("event: error\ndata: {event}\n\n");
let events = collect_events(&[sse.as_bytes()]).await;
match (code, events.as_slice()) {
("bio_policy", [Err(ApiError::BioPolicy { message })])
| ("cyber_policy", [Err(ApiError::CyberPolicy { message })]) => {
assert_eq!(message, "policy rejection");
}
other => panic!("unexpected policy error event: {other:?}"),
}
}
}
#[tokio::test(start_paused = true)]
async fn statusless_policy_errors_exit_before_sse_idle_timeout() {
for code in ["bio_policy", "cyber_policy"] {
let event = json!({
"type": "error",
"error": { "code": code, "message": "policy rejection" },
});
let sse = format!("event: error\ndata: {event}\n\n");
let stream = stream::iter([Ok(Bytes::from(sse))]).chain(stream::pending());
let (tx, mut rx) = mpsc::channel(1);
let started = tokio::time::Instant::now();
tokio::spawn(process_sse(
Box::pin(stream),
tx,
idle_timeout(),
/*telemetry*/ None,
));
let result = rx.recv().await.expect("expected a policy error");
match (code, result) {
("bio_policy", Err(ApiError::BioPolicy { message }))
| ("cyber_policy", Err(ApiError::CyberPolicy { message })) => {
assert_eq!(message, "policy rejection");
}
other => panic!("unexpected policy error: {other:?}"),
}
assert_eq!(started.elapsed(), Duration::ZERO);
}
}
#[tokio::test]
async fn cyber_policy_error_is_fatal() {
let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_fatal_cyber","object":"response","created_at":1759771626,"status":"failed","background":false,"error":{"code":"cyber_policy","message":"This request was flagged for cyber policy."},"incomplete_details":null}}"#;
@@ -47,18 +47,6 @@ pub(super) fn parse_failed_response(response: Option<Value>) -> ApiError {
match error.code.as_deref() {
Some("insufficient_quota" | "credit_balance_exhausted") => ApiError::QuotaExceeded,
Some("usage_not_included") => ApiError::UsageNotIncluded,
Some("cyber_policy") => ApiError::CyberPolicy {
message: cyber_policy_message(error.message),
},
Some("bio_policy") => {
let message = error
.message
.filter(|message| !message.trim().is_empty())
.unwrap_or_else(|| {
"This content was flagged for possible biological risk.".to_string()
});
ApiError::BioPolicy { message }
}
Some("misalignment_policy_violation") => {
let message = error
.message
@@ -121,16 +109,6 @@ fn try_parse_retry_delay(err: &Error) -> Option<Duration> {
None
}
fn cyber_policy_fallback_message() -> String {
"This request has been flagged for possible cybersecurity risk.".to_string()
}
fn cyber_policy_message(message: Option<String>) -> String {
message
.filter(|message| !message.trim().is_empty())
.unwrap_or_else(cyber_policy_fallback_message)
}
fn rate_limit_regex() -> &'static regex_lite::Regex {
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
#[expect(clippy::unwrap_used)]
@@ -2724,6 +2724,14 @@ async fn responses_websocket_v2_after_error_uses_full_create_without_previous_re
json!({"type": "error", "status": 400, "error": {"code": "budget_reached"}}),
CodexErrorInfo::SessionBudgetExceeded; "budget HTTP envelope"
)]
#[test_case::test_case(
json!({"type": "error", "sequence_number": 0, "error": {"code": "bio_policy", "message": "policy rejection"}}),
CodexErrorInfo::BioPolicy; "bio policy without status"
)]
#[test_case::test_case(
json!({"type": "error", "sequence_number": 0, "error": {"code": "cyber_policy", "message": "policy rejection"}}),
CodexErrorInfo::CyberPolicy; "cyber policy without status"
)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_websocket_v2_surfaces_terminal_error_without_close_handshake(
failure: serde_json::Value,