Skip to content

fix(translation): always emit Responses usage detail objects - #144

Merged
linj-glitch merged 1 commit into
mainfrom
linj/responses-usage-details-always-emitted
Jul 26, 2026
Merged

linj-glitch merged 1 commit into
mainfrom
linj/responses-usage-details-always-emitted

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

What

encode_responses_usage (buffered) and responses_usage_value (streaming) emitted
input_tokens_details and output_tokens_details only when the upstream happened to report a
cache or reasoning breakdown. Both are now always emitted, defaulting to zero.

Why

Both fields are required by the Responses usage schema. The OpenAI SDK types them as
non-optional, with non-optional ints inside:

class ResponseUsage(BaseModel):
    input_tokens_details: InputTokensDetails    # cached_tokens: int
    output_tokens_details: OutputTokensDetails  # reasoning_tokens: int

So when an upstream omits the breakdown, Switchyard returns a Responses payload that any
OpenAI-SDK client fails to deserialize:

ValidationError: 2 validation errors for Response
usage.input_tokens_details   Field required
usage.output_tokens_details  Field required

This is not a hypothetical. Routing /v1/responses to an OpenAI-format upstream on
integrate.api.nvidia.com fails for every request, because those models report no
completion_tokens_details:

Upstream model prompt_tokens_details completion_tokens_details Missing fields
meta/llama-3.3-70b-instruct {cached_tokens: 32} absent 1
nvidia/nemotron-3-ultra-550b-a55b absent absent 2
nvidia/nemotron-3-nano-omni-30b-a3b-reasoning absent absent 2

Absent means the upstream reported no cached or reasoning tokens — that is zero, not unknown — so
defaulting to zero is the accurate encoding rather than a placeholder.

Found while routing NeMo Gym evals through Switchyard: /v1/chat/completions worked end-to-end
while /v1/responses returned 500 on every rollout.

How tested

  • cargo fmt --all --check clean
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo test --workspace green
  • uv run ruff check . clean
  • uv run mypy switchyard clean (160 files)
  • uv run pytest tests/ -m "not integration" green (1944 passed, 12 skipped)
  • Manual: replayed the live integrate.api.nvidia.com usage payloads above through the
    bindings; both now deserialize into openai.types.responses.ResponseUsage.

Three regression tests added: no-breakdown (buffered), cache-only-still-emits-reasoning
(buffered, guards the partial case), and no-breakdown (streaming).

Notes for reviewers

  • The streaming encoder had the identical bug; fixing only buffered.rs would have left SSE
    clients broken, so both are changed together.
  • One existing assertion in response_translation.rs compared the whole usage object for a
    chat→responses translation and was updated to include the two now-always-present objects. No
    other expectation changed; the decode paths are untouched.
  • Scope is deliberately narrow: the Anthropic and Chat encoders are untouched, since their schemas
    do not mark these objects required.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Responses usage data now consistently includes input and output token detail objects.
    • Missing cached-token and reasoning-token breakdowns are represented as 0, improving compatibility with clients expecting the standard schema.
  • Tests

    • Added coverage for buffered and streaming responses, including missing and partially available usage details.

@linj-glitch
linj-glitch requested a review from a team as a code owner July 26, 2026 18:15
@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: ee9a2a8b-013f-4d78-bd6d-8d3fbd550d39

📥 Commits

Reviewing files that changed from the base of the PR and between 64eaa61 and f46a043.

📒 Files selected for processing (4)
  • crates/switchyard-translation/src/codecs/responses/buffered.rs
  • crates/switchyard-translation/src/codecs/responses/stream.rs
  • crates/switchyard-translation/tests/response_translation.rs
  • crates/switchyard-translation/tests/stream_translation.rs

Walkthrough

Responses usage encoders now always emit input_tokens_details and output_tokens_details, defaulting absent cached or reasoning token values to zero. Buffered and streaming translation tests cover missing and partial breakdowns.

Changes

Responses usage details

Layer / File(s) Summary
Usage detail emission
crates/switchyard-translation/src/codecs/responses/buffered.rs, crates/switchyard-translation/src/codecs/responses/stream.rs
Both encoders always serialize input and output token detail objects, using zero for absent breakdown values.
Usage detail validation
crates/switchyard-translation/tests/response_translation.rs, crates/switchyard-translation/tests/stream_translation.rs
Tests verify detail objects and zero defaults for missing and partial buffered or streaming usage breakdowns.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

I’m a rabbit with tokens tucked neat,
Zeroes now make every detail complete.
Buffered or streaming, the fields hop in line,
Cached and reasoning both parse just fine.
Sniffles and carrots—what a schema delight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: always emitting Responses usage detail objects in translation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

@linj-glitch
linj-glitch force-pushed the linj/responses-usage-details-always-emitted branch from f46a043 to 69ab31b Compare July 26, 2026 20:36
@linj-glitch
linj-glitch merged commit 0a03235 into main Jul 26, 2026
14 checks passed
@linj-glitch
linj-glitch deleted the linj/responses-usage-details-always-emitted branch July 26, 2026 21:25
linj-glitch added a commit to NVIDIA-NeMo/Gym that referenced this pull request Jul 26, 2026
The published 0.1.0 cannot serve this server's /v1/responses endpoint at all.
Its chat->responses translation emits a usage object without the
input_tokens_details and output_tokens_details members that the Responses
schema marks required, so every response fails NeMoGymResponse validation and
the endpoint returns 500. A real eval against
integrate.api.nvidia.com failed on every rollout; /v1/chat/completions was
unaffected, which is why this only surfaced for Responses-API agents.

NVIDIA-NeMo/Switchyard#144 makes both members unconditional. It is merged but
unreleased -- PyPI still carries only 0.1.0 -- so this pins the merge commit
directly and should move to `>=0.1.1,<0.2.0` as soon as a release ships.

Installing from git builds Switchyard's Rust extension through maturin, so this
now requires a cargo toolchain on the installing machine. Gym's CI does not
provide one, so `gym env test` for this server will not run there until the pin
moves to a released wheel. That cost is accepted deliberately: the alternative
is shipping a server whose Responses endpoint cannot serve a single request.

The uv override that neutralized 0.1.0's stale openai>=2.34.0 floor is dropped
with it. Switchyard declares openai>=2.7,<3.0 as of #142, which co-installs
with Gym's ceiling directly -- verified by rebuilding the server venv from
scratch, which resolves openai 2.7.2 with no override present.

Verified end to end from a clean venv: 25 unit tests pass, and a
`gym eval run` against a live model returns reward 1.0 rollouts carrying
well-formed usage, where the same run previously failed on every rollout.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to NVIDIA-NeMo/Gym that referenced this pull request Aug 18, 2026
The published 0.1.0 cannot serve this server's /v1/responses endpoint at all.
Its chat->responses translation emits a usage object without the
input_tokens_details and output_tokens_details members that the Responses
schema marks required, so every response fails NeMoGymResponse validation and
the endpoint returns 500. A real eval against
integrate.api.nvidia.com failed on every rollout; /v1/chat/completions was
unaffected, which is why this only surfaced for Responses-API agents.

NVIDIA-NeMo/Switchyard#144 makes both members unconditional. It is merged but
unreleased -- PyPI still carries only 0.1.0 -- so this pins the merge commit
directly and should move to `>=0.1.1,<0.2.0` as soon as a release ships.

Installing from git builds Switchyard's Rust extension through maturin, so this
now requires a cargo toolchain on the installing machine. Gym's CI does not
provide one, so `gym env test` for this server will not run there until the pin
moves to a released wheel. That cost is accepted deliberately: the alternative
is shipping a server whose Responses endpoint cannot serve a single request.

The uv override that neutralized 0.1.0's stale openai>=2.34.0 floor is dropped
with it. Switchyard declares openai>=2.7,<3.0 as of #142, which co-installs
with Gym's ceiling directly -- verified by rebuilding the server venv from
scratch, which resolves openai 2.7.2 with no override present.

Verified end to end from a clean venv: 25 unit tests pass, and a
`gym eval run` against a live model returns reward 1.0 rollouts carrying
well-formed usage, where the same run previously failed on every rollout.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
linj-glitch added a commit to NVIDIA-NeMo/Gym that referenced this pull request Aug 25, 2026
The published 0.1.0 cannot serve this server's /v1/responses endpoint at all.
Its chat->responses translation emits a usage object without the
input_tokens_details and output_tokens_details members that the Responses
schema marks required, so every response fails NeMoGymResponse validation and
the endpoint returns 500. A real eval against
integrate.api.nvidia.com failed on every rollout; /v1/chat/completions was
unaffected, which is why this only surfaced for Responses-API agents.

NVIDIA-NeMo/Switchyard#144 makes both members unconditional. It is merged but
unreleased -- PyPI still carries only 0.1.0 -- so this pins the merge commit
directly and should move to `>=0.1.1,<0.2.0` as soon as a release ships.

Installing from git builds Switchyard's Rust extension through maturin, so this
now requires a cargo toolchain on the installing machine. Gym's CI does not
provide one, so `gym env test` for this server will not run there until the pin
moves to a released wheel. That cost is accepted deliberately: the alternative
is shipping a server whose Responses endpoint cannot serve a single request.

The uv override that neutralized 0.1.0's stale openai>=2.34.0 floor is dropped
with it. Switchyard declares openai>=2.7,<3.0 as of #142, which co-installs
with Gym's ceiling directly -- verified by rebuilding the server venv from
scratch, which resolves openai 2.7.2 with no override present.

Verified end to end from a clean venv: 25 unit tests pass, and a
`gym eval run` against a live model returns reward 1.0 rollouts carrying
well-formed usage, where the same run previously failed on every rollout.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
ananthsub pushed a commit to NVIDIA-NeMo/Gym that referenced this pull request Aug 26, 2026
The published 0.1.0 cannot serve this server's /v1/responses endpoint at all.
Its chat->responses translation emits a usage object without the
input_tokens_details and output_tokens_details members that the Responses
schema marks required, so every response fails NeMoGymResponse validation and
the endpoint returns 500. A real eval against
integrate.api.nvidia.com failed on every rollout; /v1/chat/completions was
unaffected, which is why this only surfaced for Responses-API agents.

NVIDIA-NeMo/Switchyard#144 makes both members unconditional. It is merged but
unreleased -- PyPI still carries only 0.1.0 -- so this pins the merge commit
directly and should move to `>=0.1.1,<0.2.0` as soon as a release ships.

Installing from git builds Switchyard's Rust extension through maturin, so this
now requires a cargo toolchain on the installing machine. Gym's CI does not
provide one, so `gym env test` for this server will not run there until the pin
moves to a released wheel. That cost is accepted deliberately: the alternative
is shipping a server whose Responses endpoint cannot serve a single request.

The uv override that neutralized 0.1.0's stale openai>=2.34.0 floor is dropped
with it. Switchyard declares openai>=2.7,<3.0 as of #142, which co-installs
with Gym's ceiling directly -- verified by rebuilding the server venv from
scratch, which resolves openai 2.7.2 with no override present.

Verified end to end from a clean venv: 25 unit tests pass, and a
`gym eval run` against a live model returns reward 1.0 rollouts carrying
well-formed usage, where the same run previously failed on every rollout.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
ananthsub pushed a commit to NVIDIA-NeMo/Gym that referenced this pull request Aug 26, 2026
…ion provenance (#2141)

Part of #2088. This PR now also absorbs #2600 (routing-condition
provenance) so the whole feature reviews in one place.

Adds `responses_api_models/switchyard_model/`, a model server that
routes Gym model calls through a Switchyard proxy, so any benchmark Gym
supports can run against a router without harness changes — unlike the
per-harness integrations in #2026/#2080, which are right for RL trace
capture but not for evaluating the router itself. Gym either hosts the
router in-process from a native Switchyard TOML deployment
(`deployment=routes.toml`; a bad deployment fails at startup, nothing
outlives the process, and multi-worker configs are rejected since each
worker would host its own proxy) or attaches to an externally run proxy
via `switchyard_base_url`, which does support multiple workers. A
caller-supplied `model` is always overridden with the configured route
so an agent can't bypass the router, and Gym forwards its
rollout-attempt id as the Switchyard session id
(`x-switchyard-session-id`) so routing decisions and costs join back to
the rollout that produced them. That id only arrives when model-call
capture or token capture is enabled, so the server validates the
requirement at startup: a warning under the default config, a refusal to
start when forwarding was requested explicitly but no capture is on.

From #2600: set `condition_dir` and the server records the routing
condition the run served under — `switchyard-condition.json` at startup
(route, mode, proxy URL, deployment SHA-256 plus an archive with inline
`api_key` and all `extra_headers` values redacted, and the proxy's
identity: the local wheel version when hosting, a caller-supplied
`proxy_provenance` mapping when attaching) and `switchyard-stats.json`
at shutdown (per-target requests, errors, tokens, and latency plus
classifier-side usage from `/v1/stats`, fetched through Gym's shared
async client as the configured caller and hard-capped inside the
shutdown window). The snapshot labels its scope, since a hosted proxy's
counters cover exactly the run while an attached proxy's aggregate
everything it has served. Both writes are best-effort and cannot take
down serving. This makes two routed runs comparable and a hosted run
reproducible from the archived deployment; the docs page gains a
"Compare routing conditions" workflow that aligns rollout rows by task
and rollout index, reports rollouts missing a counterpart, and includes
the classifier tokens the selected model's usage omits.

The only dependency is `nemo-switchyard==0.2.0`, pinned exactly in this
server's own pyproject.toml (Gym core never imports Switchyard); 0.2.0
is the floor because it is the first release whose Responses translation
passes `NeMoGymResponse` validation (NVIDIA-NeMo/Switchyard#144), and
the ceiling because upstream has already removed the Python serve stack
this PR originally drove. 47 tests pass with 100% coverage on app.py,
including an integration suite that drives the real 0.2.0 wheel with no
mocks (chat/responses round trips, route override, stats, provenance
files written across a real shutdown), and a live routed rollout ran
against this revision with reward 1.0 (results in [this
comment](#2141 (comment))).

Two reviewer notes. `ModelCallRecord.model_ref` names the Gym model
server, not the routed target, so per-call attribution must be read from
captured payloads — promoting it to a first-class record field is the
follow-up flagged for #2088 and needs a core-schema design pass. And
`harbor_agent` overwrites `response["model"]` with the policy model
name, so Harbor-run benchmarks report the route name for every call;
flagging in case that overwrite is unintentional.

---------

Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants