Skip to content

fix(core): preserve provider bodies for propagated errors - #4285

Merged
giuliolovisotto merged 3 commits into
mainfrom
codex/preserve-propagated-error-body
Oct 9, 2026
Merged

giuliolovisotto merged 3 commits into
mainfrom
codex/preserve-propagated-error-body

Conversation

@giuliolovisotto

@giuliolovisotto giuliolovisotto commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Pi's SDK cannot recognize context overflow when an explicitly propagated provider error is wrapped as {"detail":{"error":...}}: it reports “400 status code (no body)” instead of the provider message. Its HTTP 400/503 integration tests also omitted the propagation setting required by the current OpenAI Model Server.

Remove the adapter's extra HTTPException conversion and use the existing shared Model Server error handler. Selected statuses now retain the original provider body, including top-level error.message and error.code. LiteLLM inherits the same correction. After Chat streaming sends a keepalive, the terminal SSE error also retains the selected provider explanation; unselected provider errors remain generic HTTP 500 messages in the stream. The Pi fixture explicitly enables the statuses it exercises.

The default propagation policy remains opt-in; unselected errors and exhausted provider retries retain their HTTP 500 behavior. Compatibility: consumers of explicitly propagated OpenAI/LiteLLM errors must read the original provider body rather than the former detail wrapper. Capture retains that same served body.

Follow-up to #3415 and #3626; related tracking: FEA-461. This addresses the separate Pi CI failure exposed while validating #4251.

Validation on this branch:

  • 507 passed: OpenAI and LiteLLM adapter tests, base Model Server/Chat and Responses streaming tests, and pinned Pi 0.80.2 SDK outcome tests. Covers opt-in and default status handling, Chat/Responses, streaming/nonstreaming, capture, exhausted retries, and permanent-error handling. A delayed-error regression fails before the fix; the pinned Pi SDK recognizes HTTP 400 context overflow and HTTP 503 both before and after the first keepalive.
  • Two real local HTTP smokes passed: Pi SDK → Gym OpenAI Model Server → fault-injection provider, HTTP 400 context overflow and HTTP 503 service unavailable. Exactly one upstream request per case; Pi retains each error message and correctly distinguishes context overflow. No generative-model benchmark run: this is an error-response wire-format change.
  • Full pre-commit run --all-files and git diff --check passed; DCO-signed.
python -m pytest -o addopts= --import-mode=importlib -q \
  responses_api_agents/pi_agent/tests/test_outcome.py \
  responses_api_models/openai_model/tests/test_app.py \
  responses_api_models/litellm_model/tests/test_app.py \
  tests/unit_tests/test_base_responses_api_model.py \
  tests/unit_tests/test_responses_api_model_streaming.py \
  tests/unit_tests/test_chat_completions_streaming.py

@copy-pr-bot

copy-pr-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@giuliolovisotto giuliolovisotto added area:model Model servers, inference providers, and model adapters bug Something isn't working labels Oct 9, 2026
@giuliolovisotto
giuliolovisotto marked this pull request as ready for review October 9, 2026 14:54
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 9, 2026 14:55
@giuliolovisotto giuliolovisotto changed the title fix(model): preserve provider bodies for propagated errors fix(core): preserve provider bodies for propagated errors Oct 9, 2026
@yaoyu-33 yaoyu-33 added complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 9, 2026
return NeMoGymChatCompletion.model_validate(response_dict)

return await self._serve_upstream(create_and_validate)
return await self._call_upstream(create_and_validate)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve provider error details after Chat streaming starts

This now raises ClientResponseError, but the late-stream error handler in nemo_gym/base_responses_api_model.py:447 includes provider details only for HTTPException. If a streaming Chat request remains pending beyond the 15-second keepalive interval—for example, while waiting for a concurrency slot—a subsequent opted-in context-limit error changes from a message containing the provider explanation to HTTP 400: Model request failed. The shared HTTP exception handler cannot replace the response after streaming has started, so Pi loses the text it needs to recognize context overflow. LiteLLM inherits this Chat path too.

Could you preserve the selected provider error body/message in that stream handler, respecting _should_propagate_upstream_http_error, and add a regression that raises the error after the first keepalive? A comparison against the base adapter reproduces the message loss for both 400 and 503; the existing immediate-error tests do not exercise this path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, done.

server._client.create_response = AsyncMock(side_effect=provider_error)

with pytest.raises(HTTPException) as exc_info:
with pytest.raises(ClientResponseError) as exc_info:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nonblocking: align the direct-call test names with what they verify

Could you rename test_responses_propagates_configured_http_status to describe preserving the original provider exception? It now calls responses() directly and checks exception identity; that behavior is the same with status propagation disabled, because forwarding is now handled at the HTTP boundary. The nearby test_http_routes_respect_propagation_policy already covers that policy.

The updated OpenAI test test_responses_preserves_provider_http_400_across_server_hop has the same naming issue: it makes a direct method call, and its remaining assertions check that the terminal 400 escapes without retrying. Renaming it to describe that behavior would make the coverage clearer. This is a test-clarity suggestion, not a request for additional forwarding tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added.

@yuhezhang-ai yuhezhang-ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing both comments. The delayed streaming path now preserves opted-in provider details, and the test names match their coverage. The previously failing reproduction and focused tests pass. Code review looks good; the separate harness-conformance gate still needs to be resolved before merging.

One nonblocking description clarification: Pi 0.80.2 already classifies 400 status code (no body) as context overflow. Preserving the actual message also avoids falsely classifying unrelated 400s (for example, an invalid tool schema) as overflow. It would be helpful to mention that distinction.

@giuliolovisotto
giuliolovisotto added this pull request to the merge queue Oct 9, 2026
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/37962615853

yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Oct 9, 2026
…DIA-NeMo#4251)

## What does this PR do?

Align conformance with NVIDIA-NeMo#4045: retained HTTP errors belong to an
invocation and may have zero or one step reference. Successful policy
responses still require a step; compaction calls remain separate. This
corrects the P0 check introduced in NVIDIA-NeMo#4192 without inventing turns for
failed HTTP exchanges.

Also pass the configured assistant-message header to the scripted Model
Server's capture middleware, matching normal Model Server startup. Tests
cover header retention on HTTP success/failure and reject duplicate
links or missing ownership.

The OpenCode plugin-loading commit was removed and replaced by the
separate shared-runtime PR NVIDIA-NeMo#4288. This PR only changes conformance
checks, probe wiring, their tests and documentation. It is rebased on
main `77509af61`.

## Validation

After removing the plugin-loading commit:

```bash
PYTHONPATH=$PWD python -m pytest \
  tests/unit_tests/harness_capabilities \
  scripts/harness_conformance/tests \
  tests/unit_tests/test_harness_conformance_checks.py -q
```

**342 passed, 2 skipped.** Full core and all-server suites were not run
locally. The all-files pre-commit check passed on the rebased branch
before removing the isolated plugin-loading commit.

The fresh four-harness probe run on the rebased branch, before that
split, gave OpenCode 5/7, Hermes 7/7, Pi 6/7, Codex 0/7. These are not
results for this final split: OpenCode additionally needs the separate
plugin setup. Hermes benefits from NVIDIA-NeMo#4048 now on main. Pi's two
provider-error classification unit failures remain separate (NVIDIA-NeMo#4285); its
HTTP-400 health expectation also remains unresolved. Codex retains
independent evidence gaps.

No fresh generative-model benchmark is needed for this diagnostic/probe
correction. No API migration or reward/scoring change. No new source
files; existing licenses retained. All commits have DCO sign-off.

---------

Signed-off-by: yaoyu-33 <[email protected]>
Merged via the queue into main with commit b141a1a Oct 9, 2026
48 of 50 checks passed
@giuliolovisotto
giuliolovisotto deleted the codex/preserve-propagated-error-body branch October 9, 2026 17:12
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Oct 15, 2026
…Mo#3978)

## What does this PR do?

With `propagate_context_overflow_errors` on, the vLLM model server lets
the engine's HTTP 400 reach the harness when a request no longer fits
the model's context window. On `main` the harness receives vLLM's raw
body, whose `code` is the integer 400. An OpenAI-compatible harness
(Codex, OpenCode) classifies a context overflow by the string code
`context_length_exceeded` inside OpenAI's `error` envelope, so it cannot
recognize the refusal and compact its history; on a streaming
`/v1/chat/completions` request that has passed its keepalive, the error
event carries the same integer code.

1. **OpenAI's error envelope for a propagated refusal.**
`VLLMModel._should_propagate_upstream_http_error` returns false for an
error the server marked as a propagated length refusal, so the shared
error handler (NVIDIA-NeMo#4285) lets it through to the server's own middleware,
which answers `{"error": {"message": <the engine's message, verbatim>,
"type": "invalid_request_error", "param": <the engine's param>, "code":
...}}` with the engine's status. `context_overflow_error_fields` in
`nemo_gym.base_responses_api_model` reads the message and `param` from
vLLM's nested `error` object (0.10.1 and later), from the flat top-level
`message` of older engines, or from the raw text, so no information is
lost. The mark is one attribute, `PROPAGATED_REFUSAL_CODE_ATTRIBUTE`:
its presence marks the error (`is_propagated_refusal`) and its value is
the envelope code. A streaming `/v1/responses` request gets the same
HTTP 400 before the stream, as `main` answers it since NVIDIA-NeMo#4285; nothing
has been sent yet, so an HTTP status is the right answer and the one
OpenAI itself gives.
2. **The code says whether compacting the prompt is the remedy.** A body
that names the context window carries `code: "context_length_exceeded"`:
vLLM 0.29.0's two wordings ("This model's maximum context length is ..."
and "Input length (N) exceeds model's maximum context length (M)."), the
engine's "decoder prompt ... is longer than the maximum model length",
and llama.cpp's `exceed_context_size_error` type and phrases. A body
that only names the output-token parameter ("max_tokens must be at least
1", "max_completion_tokens=N cannot be greater than max_model_len")
carries `code: null`: lowering the parameter fixes those, shortening the
prompt does not, so the harness reports an ordinary invalid request with
the engine's sentence instead of compacting. The classification itself
stays the shared `_is_context_length_error`; it now also recognizes
`max_completion_tokens` and "maximum model length", two length refusals
that the f128d43 base answered with a plain HTTP 400 from the shared
handler. With the setting off they are now absorbed into an empty
completion with `finish_reason: "length"` like every other recognized
refusal (see below); with it on they carry the envelope,
`context_length_exceeded` for the "maximum model length" wording and
`code: null` for the `max_completion_tokens` parameter error.
3. **The chat-SSE error after the keepalive carries the envelope.** Once
a streaming `/v1/chat/completions` request has committed its headers, a
marked refusal is reported as `event: error` with the same message,
`param`, and code, and logged as one warning instead of a traceback.

The default (`propagate_context_overflow_errors: false`) keeps absorbing
a recognized refusal into an empty HTTP 200 completion with
`finish_reason: "length"`. One consequence of the wider classifier: the
`max_completion_tokens` and "maximum model length" phrasings are now
recognized too, so with propagation off they are absorbed the same way,
where before this change they fell through to the shared HTTP 400
handler. With propagation on, a parameter-only error keeps `code: null`
and a context-window error carries `context_length_exceeded`.

### Relation to the model-execution record

`ModelExecutionOutcome` records an absorbed overflow as
`local_response_reason: "context_length_exceeded"` on the observability
model-call record, and that path is unchanged here. This PR concerns the
propagated case only, which is what the client sees.

## Issue

No issue filed; observed while training with the Codex CLI through the
streaming `/v1/responses` route, which could not classify the overflow
and retried the request.

## Validation

- `responses_api_models/vllm_model/tests/test_app.py`,
`tests/unit_tests/test_base_responses_api_model.py`,
`tests/unit_tests/test_responses_api_model_streaming.py`,
`tests/unit_tests/test_chat_completions_streaming.py`: 659 passed. The
propagation test runs six engine bodies (vLLM 0.29.0's two overflow
wordings with their `param`, the engine's "maximum model length"
message, llama.cpp's typed refusal, and the two output-token parameter
errors) on both engine routes and both APIs, with the setting on and
off; new tests cover the HTTP 400 on a streaming `/v1/responses`
request, the envelope in the chat-SSE error after the keepalive, and the
message, `param`, and code extraction from the nested, flat, and raw
bodies.
- Full `tests/unit_tests` and every `responses_api_models/*/tests` suite
on this branch: the only failures (opensandbox, telemetry, and the two
servers that import `vllm`) are the same as on `main` f128d43 in the
same environment.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Rollout evidence: the envelope has run for weeks in a downstream fork
training with OpenCode and Codex harnesses under token-id capture with
`propagate_context_overflow_errors: true`. With it, Codex fails the turn
without an item and OpenCode records the error and exits, so a session
that reaches the window ends cleanly and trains up to its last completed
call instead of retrying the refused request.

### Review follow-up

Rebased onto `main` f128d43 after NVIDIA-NeMo#3371 (the shared
`_is_context_length_error`) and NVIDIA-NeMo#4285 (the shared error handler and the
HTTP 400 before a stream), which changed the shape of this change: the
envelope is produced through the propagation hook, and the terminal
`response.failed` event of the earlier revision is gone. The
`huggingface-hub<2` bound that the validation merges had added to this
branch lives in NVIDIA-NeMo#4362 now.

`main` 4518db9 is merged into the branch (c19c51c, 2026-10-14). The
one conflict was the FastAPI import line of
`responses_api_models/vllm_model/app.py`; both sides are kept, and
`Response` is dropped from the import because the envelope is returned
as a `JSONResponse`, so nothing in the module constructs a bare
`Response` any more.

yaoyu-33's suggestion of 2026-10-12 (00ad0f0): the boolean marker and
the code attribute are one attribute whose presence is the mark and
whose value is the code (`None` for an output-token parameter refusal
stays distinct from an unmarked exception); the marking helper, the
shared-handler hook, the HTTP middleware and the chat-SSE path read it,
and the extraction test covers the unmarked, `None`-code and
overflow-code states.
`tests/unit_tests/test_base_responses_api_model.py` 106 passed,
`responses_api_models/vllm_model/tests` 439 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: alexandery <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>

This branch was previously deployed

1 inactive deployment
public — e485720a Deployed Oct 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #4862
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants