Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions docs/usage-telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ keep the existing model/operation/transport/status dimensions; user, key,
request and response IDs remain confined to logs and traces.

The clock starts when a validated HTTP inference enters the execution path,
before concurrency acquisition and upstream setup/retries. For WebSocket it
before the concurrency check and upstream setup/retries. For WebSocket it
starts separately for each generating `response.create`, after request parsing
and before forwarding. HTTP body upload, validation and WebSocket handshake
time are excluded.
Expand Down Expand Up @@ -119,7 +119,7 @@ The HTTP request ID identifies that HTTP record and span; it is independent of
inference usage IDs. Supplied W3C trace context is honored for both.

The clock starts at the outer request middleware, before authorization,
body reading/decompression, validation, concurrency waiting and upstream
body reading/decompression, validation, the concurrency check and upstream
setup/retries. It excludes time before the HTTP server dispatches the request
(connection acceptance, TLS and header parsing). TTFB ends when the application
has the response headers ready, including for an SSE stream that has not
Expand All @@ -145,9 +145,20 @@ lifetime is excluded. WebSocket inference continues to use per-turn TTFT/TPS.

Histogram dimensions are limited to method (unknown methods use `_OTHER`),
matched route template (fallback paths use `unmatched`), HTTP status when known,
and outcome. Raw paths, query strings, user/key/request IDs and response content
are never metric dimensions. HTTP telemetry does not add synthetic token
measurements to endpoints without upstream usage.
and outcome. HTTP Responses that reach the inference response path also carry
the `codex_api.http.response_mode` attribute (`sse` or `buffered`) and the
`response_mode` JSON log field. Raw paths, query strings, user/key/request IDs
and response content are never metric dimensions. HTTP telemetry does not add
synthetic token measurements to endpoints without upstream usage.

Compare TTFB percentiles for `sse` and `buffered` separately. A buffered
response waits for the terminal event before its headers can be sent. For SSE,
the gateway returns headers once upstream accepts the request and forwards
events as they arrive. Low SSE TTFB with high proxy-observed TTFT points to
the interval before the first content delta, which can include upstream
queuing, prompt processing and reasoning. If gateway timings are low but
the client is slow, compare the same streaming request directly against the
gateway and through its ingress to locate buffering or delivery delays.

The Talos configuration routes OTLP through Alloy to Mimir, Tempo and Loki.
The provisioned `codex-api-usage` Grafana dashboard uses Loki usage events for
Expand Down
48 changes: 26 additions & 22 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ use codex_api::{
ApiError, Compression, ReqwestTransport, ResponsesApiRequest, ResponsesClient, ResponsesOptions,
};
use codex_http_client::{ClientRouteClass, HttpClientFactory};
use codex_login::{AuthManager, default_client::create_client_for_route};
use codex_login::{
AuthManager,
default_client::{
ClientRedirectPolicy, create_client_for_route, create_transport_for_routes_async,
},
};
use codex_model_provider::SharedModelProvider;
use codex_protocol::protocol::SessionSource;
use futures::StreamExt;
use std::sync::{Arc, OnceLock};
use tokio::sync::{mpsc, oneshot};
use tokio::sync::{OnceCell, mpsc, oneshot};

pub struct Backend {
pub provider: SharedModelProvider,
pub auth: Arc<AuthManager>,
pub factory: HttpClientFactory,
pub api_transport: OnceCell<ReqwestTransport>,
pub chatgpt_base_url: String,
pub platform_base_url: String,
pub auth_base_url: String,
Expand All @@ -38,6 +44,19 @@ impl Drop for RunningResponse {
}

impl Backend {
async fn api_transport(&self) -> Result<&ReqwestTransport, GatewayError> {
self.api_transport
.get_or_try_init(|| {
create_transport_for_routes_async(
self.factory.clone(),
ClientRouteClass::Api,
ClientRedirectPolicy::Default,
)
})
.await
.map_err(GatewayError::internal)
}

pub async fn start(
&self,
request: ResponsesApiRequest,
Expand Down Expand Up @@ -182,22 +201,12 @@ impl Backend {
.await
.map_err(GatewayError::internal)?
.auth;
let transport = self.api_transport().await?;
if *changes.borrow() != revision {
continue;
}
let url = codex_api::ModelsClient::<ReqwestTransport>::request_url(&resolved, version);
let http = create_client_for_route(
&self.factory,
&url,
ClientRouteClass::Api,
codex_login::default_client::ClientRedirectPolicy::Default,
)
.map_err(GatewayError::internal)?;
let client = codex_api::ModelsClient::new(
ReqwestTransport::from_http_client(http),
resolved,
api_auth,
);
let client = codex_api::ModelsClient::new(transport.clone(), resolved, api_auth);
match client
.list_models_raw(url, headers.clone(), Some(16 * 1024 * 1024))
.await
Expand Down Expand Up @@ -336,21 +345,16 @@ impl Backend {
.await
.map_err(GatewayError::internal)?
.auth;
// Share connection pools across requests while resolving credentials per attempt.
let http = self.api_transport().await?;
if *auth_changes.borrow() != revision {
continue;
}
let http = create_client_for_route(
&self.factory,
&resolved.url_for_path("/responses"),
ClientRouteClass::Api,
codex_login::default_client::ClientRedirectPolicy::Default,
)
.map_err(GatewayError::internal)?;
let (sender, receiver) = mpsc::channel(8);
let response_headers = Arc::new(OnceLock::new());
let transport = TapTransport {
response_headers: response_headers.clone(),
inner: ReqwestTransport::from_http_client(http),
inner: http.clone(),
sender,
};
let client = ResponsesClient::new(transport, resolved, api_auth);
Expand Down
6 changes: 6 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::{Context, bail};
use axum::serve::ListenerExt;
use clap::Parser;
use codex_api_gateway::{
server::{Gateway, router},
Expand Down Expand Up @@ -90,6 +91,11 @@ async fn main() -> anyhow::Result<()> {
};
let listener = tokio::net::TcpListener::bind(args.listen).await?;
tracing::info!(listen=%listener.local_addr()?, allow_restricted_api=args.restricted_api, "Codex Responses gateway ready");
let listener = listener.tap_io(|socket| {
if let Err(error) = socket.set_nodelay(true) {
tracing::debug!(%error, "Could not enable TCP_NODELAY on accepted socket");
}
});
axum::serve(listener, router(gateway))
.with_graceful_shutdown(async {
#[cfg(unix)]
Expand Down
9 changes: 8 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,9 @@ async fn respond(
response
.headers_mut()
.insert("x-accel-buffering", "no".parse().unwrap());
response
.extensions_mut()
.insert(crate::telemetry::HttpResponseMode::Sse);
Ok(response)
} else {
let _permit = permit;
Expand Down Expand Up @@ -562,7 +565,11 @@ async fn respond(
.get("response")
.filter(|v| v.is_object())
.ok_or_else(|| GatewayError::internal("terminal response missing object"))?;
Ok(Json(response.clone()).into_response())
let mut response = Json(response.clone()).into_response();
response
.extensions_mut()
.insert(crate::telemetry::HttpResponseMode::Buffered);
Ok(response)
}
}
pub(crate) fn timeout_error() -> GatewayError {
Expand Down
1 change: 1 addition & 0 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ async fn load_backend_inner(codex_home: PathBuf, device_login: bool) -> anyhow::
provider,
auth,
factory,
api_transport: Default::default(),
chatgpt_base_url,
platform_base_url: "https://api.openai.com/v1".into(),
auth_base_url: "https://auth.openai.com".into(),
Expand Down
22 changes: 22 additions & 0 deletions src/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,12 @@ impl Telemetry {
}
}

#[derive(Clone, Copy)]
pub(crate) enum HttpResponseMode {
Sse,
Buffered,
}

/// Measures HTTP handling independently of inference, including rejected requests.
pub(crate) struct HttpRequestGuard {
telemetry: Arc<Telemetry>,
Expand All @@ -197,6 +203,7 @@ pub(crate) struct HttpRequestGuard {
method: String,
route: String,
status: Option<u16>,
response_mode: Option<&'static str>,
ttfb: Option<Duration>,
exported: bool,
}
Expand All @@ -223,6 +230,7 @@ impl HttpRequestGuard {
.map(|path| path.as_str().to_owned())
.unwrap_or_else(|| "unmatched".into()),
status: None,
response_mode: None,
ttfb: None,
exported: false,
}
Expand All @@ -232,6 +240,14 @@ impl HttpRequestGuard {
use axum::body::HttpBody;
self.ttfb = Some(self.clock.elapsed());
self.status = Some(response.status().as_u16());
self.response_mode =
response
.extensions()
.get::<HttpResponseMode>()
.map(|mode| match mode {
HttpResponseMode::Sse => "sse",
HttpResponseMode::Buffered => "buffered",
});
if response.status() == http::StatusCode::SWITCHING_PROTOCOLS {
// The upgraded socket outlives this HTTP body.
self.finish("upgraded");
Expand Down Expand Up @@ -270,6 +286,9 @@ impl HttpRequestGuard {
i64::from(status),
));
}
if let Some(mode) = self.response_mode {
attributes.push(KeyValue::new("codex_api.http.response_mode", mode));
}
telemetry
.http_duration
.record(elapsed.as_secs_f64(), &attributes);
Expand Down Expand Up @@ -315,6 +334,9 @@ impl HttpRequestGuard {
if let Some(ttfb) = self.ttfb {
body["ttfb_ms"] = json!(ttfb.as_secs_f64() * 1000.);
}
if let Some(mode) = self.response_mode {
body["response_mode"] = json!(mode);
}
let logger = telemetry.logs.logger("codex-api.http");
let mut log = logger.create_log_record();
log.set_event_name("codex_api.http.request");
Expand Down
46 changes: 46 additions & 0 deletions tests/cases/performance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,42 @@ use opentelemetry_sdk::{
};
use std::collections::HashMap;

#[tokio::test]
async fn responses_reuse_upstream_connection_and_send_headers_before_events() {
let h = Harness::new(events(), StatusCode::OK, false, Duration::from_secs(10)).await;
let client = reqwest::Client::new();
let models = client
.get(format!("{}/codex/models", h.url))
.bearer_auth("client-key")
.send()
.await
.unwrap();
assert_eq!(models.status(), StatusCode::OK);
models.bytes().await.unwrap();

for path in ["/v1/responses", "/codex/responses"] {
let (release, gate) = tokio::sync::oneshot::channel();
*h.fake.http_event_gate.lock().unwrap() = Some(gate);
let response = tokio::time::timeout(
Duration::from_secs(5),
client
.post(format!("{}{path}", h.url))
.bearer_auth("client-key")
.json(&json!({"model":h.model,"input":"hello","stream":true}))
.send(),
)
.await
.expect("response headers must arrive while upstream events are held")
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/event-stream");
release.send(()).unwrap();
let events = parse_sse(&response.text().await.unwrap());
assert_eq!(events.last().unwrap()["type"], "response.completed");
}
assert_eq!(h.capture.connection_count(), 1);
}

#[tokio::test]
async fn http_timings_include_body_upload_rejections_and_head() {
let logs = InMemoryLogExporter::default();
Expand Down Expand Up @@ -101,6 +137,7 @@ async fn http_timings_include_body_upload_rejections_and_head() {
.collect();
assert_eq!(bodies.len(), 6);
assert!(bodies[0]["ttfb_ms"].as_f64().unwrap() >= 100.);
assert_eq!(bodies[0]["response_mode"], "buffered");
assert!(bodies.iter().all(|body| {
body["outcome"] == "completed"
&& body["total_duration_ms"].as_f64().unwrap() >= body["ttfb_ms"].as_f64().unwrap()
Expand Down Expand Up @@ -200,6 +237,7 @@ async fn inference_timings_reach_exporters_for_http_sse_and_websocket_aliases()
let records = logs.get_emitted_logs().unwrap();
assert_eq!(records.len(), 14);
let mut transports = HashMap::new();
let mut response_modes = HashMap::new();
let mut http_count = 0;
for record in &records {
let Some(AnyValue::String(body)) = record.record.body() else {
Expand All @@ -213,10 +251,14 @@ async fn inference_timings_reach_exporters_for_http_sse_and_websocket_aliases()
if body["status_code"] == 101 {
assert_eq!(body["method"], "GET");
assert_eq!(body["outcome"], "upgraded");
assert!(body.get("response_mode").is_none());
} else {
assert_eq!(body["method"], "POST");
assert_eq!(body["status_code"], 200);
assert_eq!(body["outcome"], "completed");
*response_modes
.entry(body["response_mode"].as_str().unwrap().to_owned())
.or_insert(0) += 1;
}
http_count += 1;
continue;
Expand All @@ -235,5 +277,9 @@ async fn inference_timings_reach_exporters_for_http_sse_and_websocket_aliases()
assert_eq!(transports["http"], 4);
assert_eq!(transports["websocket"], 3);
assert_eq!(http_count, 7);
assert_eq!(
response_modes,
HashMap::from([("buffered".into(), 1), ("sse".into(), 3)])
);
assert_eq!(spans.get_finished_spans().unwrap().len(), 14);
}
1 change: 1 addition & 0 deletions tests/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ async fn backend(app: Router) -> (Backend, tokio::task::JoinHandle<()>) {
),
auth,
factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
api_transport: Default::default(),
chatgpt_base_url: url.clone(),
platform_base_url: url.clone(),
auth_base_url: url,
Expand Down
5 changes: 5 additions & 0 deletions tests/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use tokio::sync::Semaphore;
struct Fake {
received: Arc<Mutex<Vec<(HeaderMap, Value)>>>,
events: Vec<Value>,
http_event_gate: Arc<Mutex<Option<tokio::sync::oneshot::Receiver<()>>>>,
status: StatusCode,
hang: bool,
ws_frames: Arc<Mutex<Vec<String>>>,
Expand Down Expand Up @@ -101,7 +102,9 @@ async fn upstream(State(fake): State<Fake>, headers: HeaderMap, bytes: Bytes) ->
.chunks(7)
.map(Bytes::copy_from_slice)
.collect();
let gate = fake.http_event_gate.lock().unwrap().take();
let stream = async_stream::stream! {
if let Some(gate) = gate { let _ = gate.await; }
for chunk in chunks { yield Ok::<_, std::io::Error>(chunk); }
if fake.hang { std::future::pending::<()>().await; }
};
Expand Down Expand Up @@ -256,6 +259,7 @@ impl Harness {
let fake = Fake {
received: Default::default(),
events,
http_event_gate: Default::default(),
status,
hang,
ws_frames: Default::default(),
Expand Down Expand Up @@ -332,6 +336,7 @@ impl Harness {
),
auth,
factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
api_transport: Default::default(),
chatgpt_base_url: upstream_url.clone(),
platform_base_url: upstream_url.clone(),
auth_base_url: upstream_url.clone(),
Expand Down
3 changes: 3 additions & 0 deletions tests/support/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ impl Capture {
task,
}
}
pub fn connection_count(&self) -> usize {
self.connections.lock().unwrap().len()
}
pub fn save(&self, name: &str) -> std::path::PathBuf {
let directory = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("artifacts/protocol")
Expand Down
Loading