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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ clap = { version = "4", features = ["derive", "env"] }
eventsource-stream = "0.2.3"
futures = "0.3"
http = "1"
http-body = "1"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value"] }
serde_ignored = "=0.1.14"
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ limit; see [the request contract](docs/responses.md).
- [OAuth audio transcription](docs/platform.md#oauth-audio-transcription)
- [Image generation](docs/images-generations.md) and [editing](docs/images-edits.md)
- [Authentication and limits](docs/common.md)
- [OTLP usage, TTFB, TTFT, TPS and request duration](docs/usage-telemetry.md)

## Test

Expand Down
119 changes: 118 additions & 1 deletion docs/usage-telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Internal routes overwrite the user with
without trusted identity a request is attributed to `unknown`. These headers
are never forwarded to the model provider.

Each HTTP inference (including streaming and compact requests) and each
Each Responses HTTP inference (including streaming, native aliases and compact requests) and each
WebSocket response.create generates an OTLP usage log and correlated span.
Logs include user/key IDs, request/response IDs, requested and returned model,
start time, duration, outcome, input/output/total tokens and cache/reasoning
Expand All @@ -32,6 +32,123 @@ Metrics use the development GenAI inference conventions:
metric dimensions. `codex_api.usage.missing` counts requests without usage.
See the [upstream convention](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/client-inference.md).

## Per-request performance

The same OTLP pipeline also exports these gateway-specific histograms. These
names are custom extensions, separate from the development GenAI conventions
above. No additional configuration or telemetry endpoint is needed.

| Metric | Unit | Definition |
| --- | --- | --- |
| `codex_api.inference.time_to_first_token` | `s` | Time from inference start to the first non-empty generated content delta (proxy-observed TTFT) |
| `codex_api.inference.output_tokens_per_second` | `{token}/s` | Upstream-reported `output_tokens` divided by inference duration (overall TPS, including initial waiting time) |
| `codex_api.inference.duration` | `s` | Time from inference start to observation of the terminal response event |

Each usage JSON log includes `inference_duration_ms`, and, when available,
`ttft_ms` and `tps`. The correlated span and log attributes also include the
three metric names above with values in seconds and tokens/second. Histograms
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
starts separately for each generating `response.create`, after request parsing
and before forwarding. HTTP body upload, validation and WebSocket handshake
time are excluded.

TTFT ignores `response.created`, item creation, empty deltas and other metadata.
It recognizes text, refusal, visible reasoning/reasoning-summary, function-call
argument and custom-tool-input deltas. This measures the first observable model
content at the gateway, not server-internal token generation or the time the
caller receives it. Hidden reasoning before any visible delta is included in
the wait. A response with no recognized delta has no TTFT sample, even if it
reports output tokens in its terminal response.

TPS uses the terminal response's reported token count, including reasoning
tokens already contained in `output_tokens`. It never estimates tokens from
text length, event counts or chunk counts. Only completed, successful responses
with a positive output count and positive inference duration have a TPS sample.
Failed, incomplete, cancelled, missing-usage and zero-token responses omit TPS;
an observed TTFT can still be reported for them.

TPS is an **overall request rate**, not a decode-only model benchmark. For
example, 100 output tokens and a 5-second inference duration yield 20 tokens/s.
The denominator is not reduced by TTFT, because a delta can contain multiple
tokens and the reported count can include earlier hidden reasoning.

HTTP event timestamps are captured while reading upstream SSE, before internal
channel delivery. Timing freezes at the first terminal event, so later parser
completion, telemetry export and response-body draining do not extend inference
duration or lower TPS. Existing `duration_ms` and
`gen_ai.client.inference.duration` still measure the full guard lifetime and can
include downstream drain time. Upstream reads can themselves be delayed by
network or downstream backpressure; this is gateway-observed performance, not
isolated model execution time. Requests without a terminal event use their
lifetime for inference duration and never report TPS.

WebSocket timing is per response, including multiple turns on one connection.
Deltas are matched using response IDs, known output item IDs or an unambiguous
stream lane. Ambiguous multiplexed deltas are ignored instead of assigned to
another request. Deltas referring to unknown items also remain unattributed
unless they identify an active response explicitly. Terminal duplicates do not
produce duplicate records. Output
item routing is bounded and cleared as responses finish.

Performance metrics currently cover Responses and compact inference through
these instrumented paths. Generic native proxies, standalone images/search,
audio and Realtime are not given synthetic TTFT or TPS samples.

## HTTP ingress and response lifetime

All HTTP requests handled by the gateway router additionally produce a
`codex_api.http.request` JSON log and a correlated server span through the same
OTLP pipeline. This includes authentication/validation failures, disabled
endpoints, health/model requests, and streaming and buffered responses.

| Metric | Unit | Definition |
| --- | --- | --- |
| `codex_api.http.time_to_first_byte` | `s` | Request middleware entry to response headers ready (application-observed TTFB) |
| `codex_api.http.request.duration` | `s` | Request middleware entry to response-body end, body error, or cancellation |

The HTTP JSON log includes `ttfb_ms` when headers became ready,
`total_duration_ms`, `method`, a matched route template, `status_code`, a
generated request ID and `outcome`. Both timing values are also exported as
numeric span/log attributes using the metric names above. HTTP records are
separate from `codex_api.usage` records: filter by `event` when querying logs.
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
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
produced any content yet. It does not wait for the first body chunk or model
token. Actual socket writes, network delivery and client-observed TTFB require
measurement at the transport or client.

Total duration follows the response body until the final frame or EOF, including
time waiting for later stream chunks and downstream consumption as observed by
the application. Returning response headers does not end this timer. Body
frames, trailers, size hints and backpressure are preserved. An empty body
or HEAD response completes at headers. Kernel/proxy buffers and delivery to
the client's application are outside this measurement.

`outcome` is `completed` for a normally exhausted body, `body_error` for a
body read error, or `cancelled` if handling/body consumption is dropped early.
Cancellation duration stops at that drop and must not be treated as a
successfully completed response duration. A cancellation before headers has
no TTFB or status code. HTTP error responses with a fully consumed body have
`completed` outcome and their actual HTTP error status. A `101` upgrade has
`upgraded` outcome and measures the HTTP handshake only; the upgraded socket's
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.

The Talos configuration routes OTLP through Alloy to Mimir, Tempo and Loki.
The provisioned `codex-api-usage` Grafana dashboard uses Loki usage events for
user/model filters, token totals and per-request details, and Mimir for rates
Expand Down
19 changes: 17 additions & 2 deletions scripts/smoke-container.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,26 @@ def encode(value):
raise AssertionError(f'Unauthenticated request accepted: {endpoint}')
except urllib.error.HTTPError as error:
assert error.code == 401, (endpoint, error.code)
request.add_header('Authorization', 'Bearer container-test-key')
try:
urllib.request.urlopen(request, timeout=2)
raise AssertionError(f'Restricted endpoint accepted: {endpoint}')
except urllib.error.HTTPError as error:
assert error.code == 403, (endpoint, error.code)
assert json.load(error)['error']['code'] == 'endpoint_disabled'
try:
urllib.request.urlopen(base + '/transfers/unknown-handle', timeout=2)
raise AssertionError('Unknown transfer handle accepted')
except urllib.error.HTTPError as error:
assert error.code == 404
print(f'Container startup, health, auth, model catalog, tools, native routes and transfers passed; {config["Size"] / 1024**2:.1f} MiB')
assert error.code == 401
request = urllib.request.Request(base + '/transfers/unknown-handle', headers={
'Authorization': 'Bearer container-test-key'})
try:
urllib.request.urlopen(request, timeout=2)
raise AssertionError('Restricted transfer endpoint accepted')
except urllib.error.HTTPError as error:
assert error.code == 403
assert json.load(error)['error']['code'] == 'endpoint_disabled'
print(f'Container startup, health, auth, model catalog, tools and restricted routes passed; {config["Size"] / 1024**2:.1f} MiB')
finally:
docker('rm', '-f', container)
18 changes: 16 additions & 2 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,23 @@ pub fn router(gateway: Gateway) -> Router {
.fallback(crate::native::handle)
.layer(DefaultBodyLimit::max(max_request_bytes))
.layer(middleware::from_fn_with_state(gateway.clone(), restricted_api_policy))
.layer(middleware::from_fn_with_state(gateway.clone(), request_timing))
.with_state(gateway)
}

async fn request_timing(
State(gateway): State<Arc<Gateway>>,
request: axum::extract::Request,
next: Next,
) -> Response {
let Some(telemetry) = &gateway.telemetry else {
return next.run(request).await;
};
let timing = crate::telemetry::HttpRequestGuard::new(telemetry.clone(), &request);
let response = next.run(request).await;
timing.wrap(response)
}

// Match complete paths and methods, including native aliases. New routes and
// arbitrary proxy paths stay closed until explicitly reviewed for this mode.
fn is_allowed_restricted_api(method: &http::Method, path: &str) -> bool {
Expand Down Expand Up @@ -467,7 +481,7 @@ async fn respond(
loop {
match tokio::time::timeout_at(deadline, running.events.recv()).await {
Ok(Some(mut event)) => {
usage.observe(&event.value);
usage.observe_at(&event.value, event.received_at);
if aggregate_output && accumulator.observe(&mut event.value) {
event.bytes = Bytes::from(format!("event: {}\ndata: {}\n\n",event.value["type"].as_str().unwrap_or("message"),event.value));
}
Expand Down Expand Up @@ -520,7 +534,7 @@ async fn respond(
usage.failure("upstream_error");
GatewayError::internal("upstream closed without terminal response")
})?;
usage.observe(&event.value);
usage.observe_at(&event.value, event.received_at);
if aggregate_output {
accumulator.observe(&mut event.value);
}
Expand Down
Loading
Loading