Route Guardian requests through /responses with identifying headers (#45736)

## What changed

- Replace dedicated Guardian endpoints with `/responses`, sending `x-codex-guardian: reviewer` or `x-codex-guardian: classifier` for eligible Codex backend requests over HTTP and WebSocket.
- Add model-scoped thread headers, recheck backend authentication on each request attempt, and reconnect WebSockets when the applicable headers change.
- Retain `features.guardianv2.free_guardian` for configuration compatibility while removing its routing gate; the backend now controls Guardian billing.

## Testing

Update tests for reviewer and classifier headers, model and authentication scoping, HTTP fallback, WebSocket reuse, and parent-response metadata across retries.

GitOrigin-RevId: 1c2b3c458ab77fb40aae4ee6784f6d827c60e76c
This commit is contained in:
jif authored and copyberry committed 2026-09-15 17:09:11 +00:00
1 parent d4e11a9b97
commit eeded5ba1a
22 files changed
+246 -286

No files matched your search

@@ -52,8 +52,6 @@ pub struct LunaSamplerConfig {
pub thread_id: String,
/// Optional host-resolved request originator.
pub originator: Option<String>,
/// Whether this thread may use the unmetered Guardian classifier endpoint.
pub free_guardian: bool,
/// Optional inference service tier.
pub service_tier: Option<String>,
/// Luna model's host-resolved encrypted-compaction compatibility hash.
@@ -13,7 +13,6 @@ use codex_api::ReqwestTransport;
use codex_api::ResponseStream;
use codex_api::ResponsesApiRequest;
use codex_api::ResponsesClient;
use codex_api::ResponsesEndpoint;
use codex_api::ResponsesOptions;
use codex_api::ResponsesWebsocketClient;
use codex_api::ResponsesWebsocketConnection;
@@ -44,6 +43,12 @@ const CONNECT_COOLDOWN: Duration = Duration::from_secs(5 * 60);
const MAX_WEBSOCKET_AGE: Duration = Duration::from_secs(55 * 60);
const RESPONSES_WEBSOCKETS_BETA: &str = "responses_websockets=2026-02-06";
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RequestMode {
Regular,
GuardianClassifier,
}
pub(super) struct ConnectionPool {
config: Arc<LunaSamplerConfig>,
pub(super) idle_connections: Mutex<Vec<PooledConnection>>,
@@ -57,7 +62,7 @@ pub(super) struct ConnectionPool {
pub(super) struct PooledConnection {
connection: ResponsesWebsocketConnection,
endpoint: ResponsesEndpoint,
request_kind: RequestMode,
// The bridge routes by thread ID, so each socket needs its own identity.
thread_id: String,
pub(super) expires_at: Instant,
@@ -72,7 +77,7 @@ enum Connection {
pub(super) struct ConnectionLease {
pub(super) thread_id: String,
pub(super) endpoint: ResponsesEndpoint,
pub(super) request_kind: RequestMode,
connection: Connection,
pool: Arc<ConnectionPool>,
_permit: OwnedSemaphorePermit,
@@ -177,19 +182,19 @@ impl ConnectionPool {
None => break None,
}
};
let (connection, thread_id, endpoint) = match connection {
let (connection, thread_id, request_kind) = match connection {
Some(connection) => {
let thread_id = connection.thread_id.clone();
let endpoint = connection.endpoint;
(Connection::Websocket(connection), thread_id, endpoint)
let request_kind = connection.request_kind;
(Connection::Websocket(connection), thread_id, request_kind)
}
None => {
self.replenish();
let (mut provider, auth) = self.client_setup().await?;
// Sampling owns the retry budget across both transports.
provider.retry.max_attempts = 0;
let endpoint = self.responses_endpoint().await;
let url = provider.url_for_path(endpoint.path());
let request_kind = self.responses_request_kind().await;
let url = provider.url_for_path("/responses");
let transport = {
let mut cached = self
.http_transport
@@ -222,18 +227,17 @@ impl ConnectionPool {
})
.await?
.clone();
let client =
ResponsesClient::new(transport, provider, auth).with_endpoint(endpoint);
let client = ResponsesClient::new(transport, provider, auth);
(
Connection::Http(client),
ThreadId::new().to_string(),
endpoint,
request_kind,
)
}
};
Ok(ConnectionLease {
thread_id,
endpoint,
request_kind,
connection,
pool: Arc::clone(self),
_permit: permit,
@@ -261,11 +265,18 @@ impl ConnectionPool {
Ok((provider, auth))
}
fn headers(&self, thread_id: &str) -> Result<HeaderMap, LunaSamplerError> {
fn headers(
&self,
thread_id: &str,
request_kind: RequestMode,
) -> Result<HeaderMap, LunaSamplerError> {
let mut headers = build_session_headers(
Some(self.config.session_id.clone()),
Some(thread_id.to_owned()),
);
if request_kind == RequestMode::GuardianClassifier {
headers.insert("x-codex-guardian", HeaderValue::from_static("classifier"));
}
headers.insert("x-openai-subagent", HeaderValue::from_static("guardian"));
headers.insert(
"x-codex-window-id",
@@ -287,16 +298,15 @@ impl ConnectionPool {
}
Ok(headers)
}
async fn responses_endpoint(&self) -> ResponsesEndpoint {
async fn responses_request_kind(&self) -> RequestMode {
let provider = self.config.provider.info();
if self.config.free_guardian
&& self
.config
.provider
.auth()
.await
.as_ref()
.is_some_and(CodexAuth::uses_codex_backend)
if self
.config
.provider
.auth()
.await
.as_ref()
.is_some_and(CodexAuth::uses_codex_backend)
&& provider.supports_codex_backend_routes()
&& provider.requires_openai_auth
&& provider.env_key.is_none()
@@ -304,9 +314,9 @@ impl ConnectionPool {
&& provider.auth.is_none()
&& provider.aws.is_none()
{
ResponsesEndpoint::GuardianClassifier
RequestMode::GuardianClassifier
} else {
ResponsesEndpoint::Responses
RequestMode::Regular
}
}
@@ -318,15 +328,15 @@ impl ConnectionPool {
let auth_changes = auth_manager.map(|manager| manager.auth_change_receiver());
let (provider, auth) = self.client_setup().await?;
let thread_id = ThreadId::new().to_string();
let mut headers = self.headers(&thread_id)?;
let request_kind = self.responses_request_kind().await;
let mut headers = self.headers(&thread_id, request_kind)?;
headers.insert(
"openai-beta",
HeaderValue::from_static(RESPONSES_WEBSOCKETS_BETA),
);
let provider_info = self.config.provider.info();
let endpoint = self.responses_endpoint().await;
let client = ResponsesWebsocketClient::new(provider, auth).with_endpoint(endpoint);
let client = ResponsesWebsocketClient::new(provider, auth);
let connect = client.connect(
&self.config.http_client_factory,
headers,
@@ -341,7 +351,7 @@ impl ConnectionPool {
.and_then(|result| result.map_err(LunaSamplerError::Api));
if let Some(metrics) = self.config.metrics.as_deref() {
let outcome = if result.is_ok() { "success" } else { "failure" };
let mut tags = vec![("endpoint", endpoint.path()), ("outcome", outcome)];
let mut tags = vec![("endpoint", "/responses"), ("outcome", outcome)];
if let Err(error) = &result {
tags.push(("failure_reason", sampler_failure_reason(error)));
}
@@ -363,7 +373,7 @@ impl ConnectionPool {
Ok(PooledConnection {
connection,
endpoint,
request_kind,
thread_id,
expires_at: Instant::now() + MAX_WEBSOCKET_AGE,
auth_changes,
@@ -399,7 +409,7 @@ impl ConnectionLease {
thread_id: Some(self.thread_id.clone()),
extra_headers: self
.pool
.headers(&self.thread_id)
.headers(&self.thread_id, self.request_kind)
.map_err(|error| ApiError::Stream(error.to_string()))?,
..Default::default()
},
@@ -81,7 +81,7 @@ impl Drop for Gateway {
#[tokio::test]
async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown() -> Result<()> {
skip_if_no_network!(Ok(()));
for free_guardian in [false, true] {
for uses_codex_backend in [false, true] {
let http = responses::start_mock_server().await;
let events = vec![
responses::ev_output_text_delta("low"),
@@ -93,7 +93,7 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
connections.push(vec![events.clone()]);
let ws = responses::start_websocket_server(connections).await;
let gateway = Gateway::new(&http.uri(), ws.uri()).await?;
let base_path = if free_guardian {
let base_path = if uses_codex_backend {
"/backend-api/codex"
} else {
"/v1"
@@ -102,13 +102,12 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
let mut config = sampler_config(base_url.clone());
config.provider = create_model_provider(
ModelProviderInfo::create_openai_provider(Some(base_url)),
Some(AuthManager::from_auth_for_testing(if free_guardian {
Some(AuthManager::from_auth_for_testing(if uses_codex_backend {
CodexAuth::create_dummy_chatgpt_auth_for_testing()
} else {
CodexAuth::from_api_key("test-api-key")
})),
);
config.free_guardian = free_guardian;
config.service_tier = Some("priority".to_owned());
let sampler = LunaSampler::new(config);
let opener = sampler.connections.replenish().unwrap();
@@ -145,17 +144,21 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
let requests = http_mock.requests();
let first = &requests[0];
let expected_path = if free_guardian {
"/backend-api/codex/guardian-classifier"
let expected_path = if uses_codex_backend {
"/backend-api/codex/responses"
} else {
"/v1/responses"
};
assert_eq!(first.path(), expected_path);
assert_eq!(
first.header("x-codex-guardian").as_deref(),
uses_codex_backend.then_some("classifier")
);
assert!(first.header("authorization").is_some());
let body = first.body_json();
assert_eq!(
body["service_tier"].as_str(),
if free_guardian {
if uses_codex_backend {
None
} else {
Some("priority")
@@ -163,7 +166,7 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
);
assert_eq!(
body["client_metadata"]["parent_response_id"].as_str(),
free_guardian.then_some("resp-parent")
uses_codex_backend.then_some("resp-parent")
);
gateway.allowed_opens.store(usize::MAX, Ordering::SeqCst);
@@ -6,10 +6,10 @@ use super::ConnectionPool;
use super::LunaSamplerConfig;
use super::LunaSamplerError;
use super::MAX_OUTPUT_BYTES;
use super::connection_pool::RequestMode;
use codex_api::ApiError;
use codex_api::ResponseEvent;
use codex_api::ResponsesApiRequest;
use codex_api::ResponsesEndpoint;
use codex_api::TransportError;
use codex_extension_api::ExtensionMetrics;
use codex_login::UnauthorizedRecovery;
@@ -127,7 +127,7 @@ impl SamplingExecution {
return Err(error);
}
};
self.request.service_tier = if lease.endpoint == ResponsesEndpoint::GuardianClassifier {
self.request.service_tier = if lease.request_kind == RequestMode::GuardianClassifier {
None
} else {
self.config.service_tier.clone()
@@ -157,7 +157,7 @@ impl SamplingExecution {
turn_metadata["root_turn_id"] = json!(root_turn_id);
}
client_metadata.insert(TURN_METADATA_KEY.to_owned(), turn_metadata.to_string());
if lease.endpoint == ResponsesEndpoint::GuardianClassifier
if lease.request_kind == RequestMode::GuardianClassifier
&& let Some(parent_response_id) = &self.parent_response_id
{
client_metadata.insert("parent_response_id".to_owned(), parent_response_id.clone());
@@ -206,7 +206,7 @@ pub(super) fn sampler_config(base_url: String) -> LunaSamplerConfig {
session_id: "session-1".to_owned(),
thread_id: "thread-1".to_owned(),
originator: Some("guardian-v2-test".to_owned()),
free_guardian: false,
service_tier: None,
luna_compaction_hash: None,
max_input_tokens: codex_guardian_context::DEFAULT_MAX_INPUT_TOKENS,
@@ -363,36 +363,26 @@ impl ExternalAuth for RefreshableAuth {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn classifier_uses_free_endpoint_only_with_codex_backend_auth() -> Result<()> {
async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Result<()> {
skip_if_no_network!(Ok(()));
for (auth, base_path, free_guardian, expected_path, expected_service_tier) in [
for (auth, base_path, expected_header, expected_service_tier) in [
(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
"/backend-api/codex",
false,
"/backend-api/codex/responses",
Some("priority"),
),
(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
"/backend-api/codex",
true,
"/backend-api/codex/guardian-classifier",
Some("classifier"),
None,
),
(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
"/v1",
true,
"/v1/responses",
None,
Some("priority"),
),
(
CodexAuth::from_api_key("test-api-key"),
"/v1",
true,
"/v1/responses",
None,
Some("priority"),
),
] {
@@ -412,13 +402,16 @@ async fn classifier_uses_free_endpoint_only_with_codex_backend_auth() -> Result<
ModelProviderInfo::create_openai_provider(Some(base_url)),
Some(AuthManager::from_auth_for_testing(auth)),
);
config.free_guardian = free_guardian;
config.service_tier = Some("priority".to_owned());
let sampler = connect_sampler(config).await?;
assert_eq!(sampler.sample(sample_request("turn-1")).await?, "low");
for handshake in server.handshakes() {
assert_eq!(handshake.uri(), expected_path);
assert_eq!(handshake.uri(), format!("{base_path}/responses"));
assert_eq!(
handshake.header("x-codex-guardian").as_deref(),
expected_header
);
assert_eq!(handshake.header("x-codex-routing-hint"), None);
}
let request = server
@@ -489,7 +482,7 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
session_id: "session-1".to_owned(),
thread_id: "thread-1".to_owned(),
originator: Some("guardian-v2-test".to_owned()),
free_guardian: false,
service_tier: None,
luna_compaction_hash: None,
max_input_tokens: codex_guardian_context::DEFAULT_MAX_INPUT_TOKENS,
@@ -733,7 +726,7 @@ async fn sampler_returns_classification_token_before_terminal_response_events()
session_id: "session-1".to_owned(),
thread_id: "thread-1".to_owned(),
originator: None,
free_guardian: false,
service_tier: None,
luna_compaction_hash: None,
max_input_tokens: codex_guardian_context::DEFAULT_MAX_INPUT_TOKENS,
@@ -1144,7 +1137,7 @@ async fn sampler_limits_transient_recovery_attempts() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parent_response_id_survives_classifier_transport_retry() -> Result<()> {
skip_if_no_network!(Ok(()));
for free_guardian in [false, true] {
for uses_codex_backend in [false, true] {
let healthy = responses::start_websocket_server(vec![vec![vec![
ev_assistant_message("resp-review", "low"),
ev_completed("resp-review"),
@@ -1156,8 +1149,7 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
})]]]).await;
let base_url = proxy_websocket_servers(&[&healthy, &expired]).await?;
let mut config = sampler_config(base_url.clone());
if free_guardian {
config.free_guardian = true;
if uses_codex_backend {
config.provider = create_model_provider(
ModelProviderInfo::create_openai_provider(Some(format!(
"{}/backend-api/codex",
@@ -1182,7 +1174,7 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
body["client_metadata"].get("parent_response_id").cloned(),
body["client_metadata"].get("guardian_credits_requested"),
),
(free_guardian.then(|| json!(parent_response_id)), None)
(uses_codex_backend.then(|| json!(parent_response_id)), None)
);
assert!(!body["input"].to_string().contains(parent_response_id));
}
@@ -56,7 +56,6 @@ pub(super) async fn sampler_config(
.thread_store
.get::<ThreadOriginator>()
.map(|originator| originator.0.clone()),
free_guardian: input.config.free_guardian_enabled(),
service_tier: input.config.service_tier.clone(),
luna_compaction_hash,
max_input_tokens,
@@ -5,6 +5,7 @@
use std::sync::Arc;
use std::sync::Weak;
use codex_core::CodexResponsesHeaders;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::config::Constrained;
@@ -85,6 +86,19 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
options.session_source =
Some(SessionSource::Internal(InternalSessionSource::Guardian));
options.thread_source = Some(ThreadSource::GuardianReview);
// This is the backend reviewer model, independent of current login.
// Core checks the selected model and auth on each request attempt.
let provider = codex_model_provider::create_model_provider(
options.config.model_provider.clone(),
/*auth_manager*/ None,
);
options.thread_extension_init.insert(CodexResponsesHeaders {
model: provider.approval_review_preferred_model().to_owned(),
headers: http::HeaderMap::from_iter([(
http::HeaderName::from_static("x-codex-guardian"),
http::HeaderValue::from_static("reviewer"),
)]),
});
options
.thread_extension_init
.insert(SessionIsolation::Isolated);