Skip to content

fix(model): bound internal provider-response retries - #5890

Merged
oyilmaz-nvidia merged 11 commits into
mainfrom
fix/bound-internal-provider-retries
Nov 11, 2026
Merged

oyilmaz-nvidia merged 11 commits into
mainfrom
fix/bound-internal-provider-retries

Conversation

@oyilmaz-nvidia

@oyilmaz-nvidia oyilmaz-nvidia commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What changed

An internal NeMoGymAsyncOpenAI client (internal=True) raised its attempt cap on every 429/502/503/504/520 answer. tries and max_num_tries grew together, so a saturated provider was retried forever. This is the failure PR #2527 describes (a single request reached 10,895 attempts).

  • Internal clients now wait out 429/502/503/504/520 on the same budget (max_rate_limit_wait_seconds) that external clients use for 429/503. With a budget of 0 they stop at max_http_attempts. One try counter and one budget cover a changing status sequence. The budget is now monotonic time since the call started, so provider response time and error-body reads spend it as well as the waits (it summed only the sleeps before). This applies to internal and external clients.
  • A propagated context_length_exceeded answer is terminal whatever status it arrives with (a Gym model server can re-emit it as 5xx). Input, authentication, authorization and spent-quota answers were already not retried; tests now cover them.
  • The complete error body is classified (permanent quota, invalid key, context overflow) before anything is cut. The body kept for the final error, and forwarded by a Gym model server, is at most 64 KiB; an oversized JSON error is rebuilt as valid JSON with its code, type and param intact, so the next client reads the same terminal code. Small and non-JSON bodies are unchanged. The final status is kept.
  • The model servers (vllm_model, openai_model, switchyard_model, inference_provider) pass internal=False explicitly. The internal field stays; its description and openai.mdx are updated.

Backoff (full jitter, 1 s doubling, 60 s cap) and Retry-After handling (honored only within the remaining budget) were already in #4786; this PR adds tests for them.

Closes #2845. Supersedes #2527, which can be closed.

Compatibility

Validation

Reproduced first. The new tests were written before the fix. On the unfixed code 27 of them failed: every internal-client sequence ran to the 500-request ceiling in the fake provider.

Tests after the fix

  • tests/unit_tests/client/test_provider_retry_bounds.py: 134 tests, all passing. Fake sleep: persistent 429/503/502/504/520 for internal and external clients, mixed-status sequences, Retry-After beyond the remaining budget and capped at 60 s, context-overflow and 400/401/403/422 not retried, spent-quota 429 terminal, cancellation during a wait, 20 concurrent callers with distinct jittered waits. Fake clock that advances inside the request and the body read: latency alone spends the budget. Real HTTP (a local aiohttp stub): a mixed-status provider ends with the final status and a bounded body; a context-overflow answer reaches the provider once; a slow provider (25 ms budget, 50 ms responses) gets one request; an oversized terminal error (context overflow, spent quota, invalid key) forwarded through the production model-server error handler is terminal for the next client (one request, no wait).
  • tests/unit_tests/client and tests/unit_tests/models: 2483 passed.
  • Model-server suites run directly: vllm_model 1040, openai_model 170, switchyard_model 53 (11 skipped), inference_provider 33. All passed.
  • pre-commit (ruff, ruff-format, import-linter) passed on the changed files.
  • Not run: tests/unit_tests/server_runtime/test_review_boundary_interfaces.py (collection error, cloudpickle missing from my venv; it fails the same way on main), the full tests/unit_tests suite, per-server gym env test, and the functional and e2e suites.

Real rollouts. gym env start plus gym eval run --no-serve with example_single_tool_call, the real openai_model server and simple_agent, against a local stub provider. internal=True was forced with a temporary, uncommitted env-var edit to openai_model/app.py, because nothing in the repo sets it. The stub cycles 429/503/502/504/520 with Retry-After: 1.

Scenario Provider Wait budget Result
A always busy 8 s Ended after about 26 s with 54 provider requests for 2 rollouts. Both rollouts failed with environment_server_failed and a final HTTP 500. Every attempt's status is recorded as a model_request_error event with its http_status.
B busy for 4 requests, then a real answer 30 s Request 5 returned 200 and the rollout completed (exit 0, 8 s). The 4 recovered events were kept on the result. Reward was 0.0, because the stub never calls the tool.
C always busy 0 Stopped at 9 provider requests over 7.6 s (3 attempts per call, 3 agent-level tries). The rollout failed.

Limits of this evidence: the provider was a stub, not a real model endpoint; internal=True was forced. Before the fix I checked old-code behavior only with a TestClient script, which was still retrying when timeout killed it at 40 s, not with a full rollout.

Real rollouts again on the final head (e336402). Same setup (gym env start --resources-server example_single_tool_call --model-type openai_model, gym eval run --no-serve --agent example_single_tool_call_simple_agent, 2 rollouts per scenario, a local stub provider, internal=True forced by a temporary uncommitted env-var edit to openai_model/app.py, reverted afterwards).

Scenario Provider Wait budget Result
A always busy (429/503/502/504/520, Retry-After: 1) 8 s Ended in 26 s with 48 provider requests across the 2 rollouts; both rollouts failed with the final status recorded.
B busy for 4 requests, then a real answer 30 s Both rollouts completed; the recovered 502, 503 and 504 attempts are kept on the results. Reward 0.0, because the stub never calls the tool.
D one 66 KB context_length_exceeded 429 30 s The model server made 1 provider request per call, with no model_retry and no wait. The layer above the model server retried the forwarded 429 (3 requests per rollout in total); that layer is unchanged.
E 0.5 s per answer, always 503 1 s Each model call made exactly 2 attempts (answer, 0.2 to 0.3 s wait, answer), then ended: response time counts against the budget.

The forwarding fix itself (the next client reading the terminal code) is covered by the unit tests that send the first client's error through the production upstream_error handler, not by these runs. Same limits as above: a stub provider, and internal=True forced. gym env start also polls GET /v1/models on the provider every ~3 s until it answers; those requests are not counted.

Observation, not changed here: bounds multiply across layers. The agent's call to the model server retries a 500 three times and each try gets its own wait budget, so a budget of N seconds can mean about 3N seconds per rollout (scenario A: 27 provider requests per rollout, 3 tries of about 9).

An internal NeMoGymAsyncOpenAI client raised its attempt cap on every
429/502/503/504/520 answer, so a saturated provider was retried forever
(#2845; the failure #2527 reported). Internal clients now wait out those
statuses on the same elapsed budget (max_rate_limit_wait_seconds) that
external clients use for 429/503, and fall back to max_http_attempts when
the budget is 0. One try counter and one wait budget cover a changing
status sequence.

- A propagated context_length_exceeded answer is terminal whatever its
  status; input, auth and permission statuses were already not retried.
- An error body is cut to a 64 KiB prefix before a retry decision and on
  the final error; the final status is kept.
- The model servers pass internal=False explicitly. The internal flag stays.
- Tests: unit tests with a fake sleep (mixed statuses, Retry-After bounds,
  cancellation, concurrent callers) and real-HTTP tests against a stub
  provider. The old test that pinned unbounded retries is replaced.

Moving retry-vs-fail decisions into the shared outcome policy is a
follow-up.

Signed-off-by: Onur Yilmaz <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 9, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@oyilmaz-nvidia
oyilmaz-nvidia marked this pull request as ready for review November 9, 2026 22:06

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE

The internal HTTP-status retries now share the existing wait budget. One RISK remains: truncating a structured error before parsing it disables permanent-error and context-overflow detection for oversized replies. There's also one documentation NOTE about which retries are bounded.

I reviewed all eight changed files and the directly affected transport, error-propagation, adapter, and test paths. This was a static review; I couldn't execute tests or independently verify the reported results.

Comparison limitation: the mounted base client contains connection-retry timeout code absent from both the supplied diff and head. I haven't attributed those additional snapshot differences to this PR.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Comment thread nemo_gym/client/openai_client.py Outdated
"""
try:
return await response.content.read()
return (await response.content.read())[:ERROR_BODY_PREFIX_BYTES]

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.

RISK — Parse structured error fields before truncating the body.

A valid reply such as json.dumps({"error": {"code": "insufficient_quota", "message": "x" * 65536}}).encode() becomes incomplete JSON here, even though its code is near the beginning. The parser then returns no codes. A permanent 429 consequently retries instead of tripping the client, potentially spending the default hour-long wait budget on each call. Oversized invalid_api_token auth errors likewise stop tripping the client, and oversized context_length_exceeded replies bypass the new terminal branch. This affects internal and external clients; the complete-body quota/auth classifiers worked before this truncation.

Could you classify the complete body, then retain only its prefix for diagnostics and raised errors? The smallest correction uses the full body already read here, without changing transport I/O. Suggested changes, not executed—verify before adopting:

# _read_error_body: return the complete body; update its docstring.
return await response.content.read()

# _request_with_retry, in the 401/403 branch:
body = await _read_error_body(response, failure)
permanent_auth = _error_body_is_permanent_auth(body)
content = body[:ERROR_BODY_PREFIX_BYTES]
del body
if permanent_auth:
    # Keep the existing terminal observation and _trip_permanent_error.
    ...

# _request_with_retry, before its quota/overflow branches:
body = await _read_error_body(response, last_failure)
permanent_quota = response.status == 429 and _error_body_is_permanent_quota(body)
context_overflow = _error_body_is_context_overflow(body)
content = body[:ERROR_BODY_PREFIX_BYTES]
del body
# Replace the existing classifier conditions with these saved booleans.

The invariant is that truncation must not change retry classification. Keep _trip_permanent_error and _raise_exhausted receiving the capped content; retain ordinary busy-status retries, generic quota messages that aren't permanent, and non-sticky context-overflow handling. Preserve the existing failed-body-read cause handling.

Proposed acceptance checks: extend the local HTTP stub tests with valid JSON larger than 64 KiB, including code/type fields before and after the long message and the supported detail.error wrapper. For both client modes, a spent-quota 429 or invalid-key 401/403 must make one wire request, sleep zero times, and make no further wire request on a second call. A context-overflow 503 must make one request with no wait, but must not prevent a later independent successful call. Ordinary busy replies must still retry and expose the final status with exactly the capped body prefix. Retain the existing small-body permanent-trip assertions and the forwarded-failure cause assertions.

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.

Fixed in c704be9. _read_error_body now returns the complete body; the 401/403 branch and the retry branch classify that full body (permanent auth, permanent quota, context overflow) and only then keep the first 64 KiB for _trip_permanent_error, _raise_exhausted and the raised error. Truncation no longer changes classification.

Tests added in test_provider_retry_bounds.py (36 failed on the previous commit, all pass now), for internal and external clients: valid JSON over 64 KiB with the code before and after the long text, plain and in the detail.error wrapper. A spent-quota 429 and an invalid-key 401/403 make one wire request, sleep zero times, and send nothing on a second call. A context-overflow 503 makes one request with no wait and does not block a later successful call. An oversized ordinary busy reply is still retried and the final error keeps exactly the capped prefix. A real-HTTP stub test covers the quota and invalid-key cases. The existing small-body and forwarded-failure assertions are unchanged and pass.

| `max_concurrent_requests` | `int` | `null` | Cap on in-flight upstream requests (per-process, at least 1). `null` = unlimited; set it on rate-limited endpoints. |
| `max_http_attempts` | `int` | `3` | Bounded retries for transient HTTP failures (404, 408, 429, 500, 502, 503, 504, 520). Retries wait with exponential backoff and full jitter (1 s doubling, capped at 60 s), or for the answer's `Retry-After` within the same cap. A 429 whose `error.code`/`error.type` is `budget_exceeded` or `insufficient_quota`, or a 401/403 whose body is an invalid key, trips the client immediately; later requests skip the wire. Generic "quota exceeded" 429s and other 401/403s still retry or return as before. A provider that refuses or drops connections gets the same number of connection attempts, 0.5 s apart, before the call fails with HTTP 500. Values of 1 or 2 also reduce request-timeout attempts from three to one or two; the default stays three. |
| `max_rate_limit_wait_seconds` | `float` | `3600` | Total wait for 429 and 503 answers, which are retried until it is spent instead of `max_http_attempts` times; the request fails once the next wait would pass it, even when `max_http_attempts` allows more tries. `0` keeps 429 and 503 on the `max_http_attempts` count. |
| `max_rate_limit_wait_seconds` | `float` | `3600` | Total wait for 429 and 503 answers, which are retried until it is spent instead of `max_http_attempts` times; the request fails once the next wait would pass it, even when `max_http_attempts` allows more tries. `0` keeps 429 and 503 on the `max_http_attempts` count. A client built with `internal=True` (calls to NeMo Gym's own servers) waits out 429, 502, 503, 504 and 520 on the same budget; no client retries without a bound. |

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.

NOTE — Suggestion: qualify the HTTP retry bound.

“No client retries without a bound” also promises a transport bound, which this change intentionally doesn't provide. Repeated connection errors can still retry indefinitely when both connection and explicit attempt limits are unset in the transport, as permitted by the client default. Users shouldn't interpret the HTTP-status wait budget as protection against connection-only retries.

Could you replace that final clause with:

HTTP-status retries are bounded; connection-error retries have separate limits and can still be unlimited.

Also replace “every 429/5xx answer” in the updated internal field description with “429, 502, 503, 504 and 520 answers.” The status lists distinguish these from 500 and other 5xx statuses.

Acceptance — proposed static check: confirm both descriptions distinguish HTTP-status retries from transport retries, retain external 429/503 behavior and the zero-budget attempt-count rule, and name the internal wait-out statuses exactly. This needs only a documentation correction; preserve the transport behavior and adapter controls.

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.

Fixed in c704be9. The openai.mdx row now ends with "HTTP-status retries are bounded; connection-error retries have separate limits and can still be unlimited.", and the internal field description names 429, 502, 503, 504 and 520 instead of "every 429/5xx answer". Transport behavior, external 429/503 behavior and the zero-budget attempt-count rule are unchanged.

oyilmaz-nvidia and others added 3 commits November 10, 2026 12:05
The error body was cut to 64 KiB before the permanent-quota, invalid-key and
context-overflow checks parsed it. A valid JSON reply longer than that became
incomplete JSON, so its error code was lost: a spent-quota 429 was retried
for the whole wait budget, an invalid-key 401/403 no longer tripped the
client, and an oversized context_length_exceeded reply was retried.

The complete body is now classified first; only its first 64 KiB is kept for
diagnostics and the final error. Truncation no longer changes retry
classification.

Also qualify the documentation: HTTP-status retries are bounded, while
connection-error retries have separate limits and can still be unlimited, and
the internal wait-out statuses are named exactly (429, 502, 503, 504, 520).

Tests: oversized valid JSON with the code before or after the long text and
inside the detail.error wrapper, for internal and external clients, over a
fake provider and a real HTTP stub.

Signed-off-by: Onur Yilmaz <[email protected]>
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test ff167e5

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/review

@giuliolovisotto

Copy link
Copy Markdown
Contributor

No must-fix findings from this review of ff167e5. The 187 focused client tests passed, including the oversized-error-body regression cases. Once this PR merges, we can close #2845; the remaining integration can be handled separately.

For subsequent changes, the failure-handling RFC should be our reference for the shared conventions: preserve NgFailureEvent observations even when recovery succeeds, select actions through the configurable outcome-policy mechanism, and keep retry execution and budgets with the owning boundary. The broader migration to those conventions should not block this focused fix.

@giuliolovisotto giuliolovisotto 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.

Approved. No must-fix findings in the focused retry change; the reviewed files are unchanged by the latest merge from main.

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 9ed31e6

@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 2026

Copy link
Copy Markdown

/ok to test 9ed31e6

@oyilmaz-nvidia, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@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 the fixes and the added coverage. Two requests remain: count elapsed time in the internal provider retry budget, and preserve terminal error codes through model-server forwarding. I also left a nonblocking suggestion to guard the regression test against a runaway loop. Validation used the focused client tests and local HTTP reproductions; no live model endpoint was tested.

Comment thread nemo_gym/client/openai_client.py Resolved
Comment thread nemo_gym/client/openai_client.py Resolved
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 69770b2

@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test c58a951

@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 the elapsed-time budget, terminal-error forwarding, and regression-test guard. All three review points are resolved; the fixes and their tests remain unchanged after the latest merge from main. Approving the code changes.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Nov 11, 2026
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 7f1b6f7

@github-actions

Copy link
Copy Markdown
Contributor

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

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 11, 2026
@oyilmaz-nvidia
oyilmaz-nvidia added this pull request to the merge queue Nov 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit ad2d03b Nov 11, 2026
67 of 69 checks passed
@oyilmaz-nvidia
oyilmaz-nvidia deleted the fix/bound-internal-provider-retries branch November 11, 2026 21:12
oyilmaz-nvidia added a commit that referenced this pull request Nov 11, 2026
A call between Gym servers retried connection errors and other failures
without a limit, and the shared aiohttp sessions had no timeout at all, so
a peer that stayed unreachable could stall a rollout indefinitely.

- Give calls with no caller-owned bound an internal retry budget
  (global_aiohttp_internal_retry_budget_seconds, default 600 s, 0 keeps the
  old unlimited behaviour). It is a connection retry window plus an elapsed
  cap on retries of other errors. Calls with _max_num_tries,
  _max_connection_retries or their own window are unchanged.
- Bound one TCP handshake with sock_connect
  (global_aiohttp_sock_connect_timeout_seconds, default 60 s). The wait for a
  connection-pool slot, total time and read time stay unlimited, so requests
  queued behind a busy pool are not cut short.

Model connection retries stay unbounded by default (see #5181), a POST is
still resent after an ambiguous disconnect, and the internal=True rate-limit
retries of NeMoGymAsyncOpenAI are left to #5890; each is a separate decision.

Signed-off-by: Onur Yilmaz <[email protected]>
oyilmaz-nvidia added a commit that referenced this pull request Nov 12, 2026
…efaults

Conflicts were in nemo_gym/client/openai_client.py and
tests/unit_tests/client/test_openai_client.py. #5890 merged to main and fixes
the internal=True rate-limit retries that this branch had also changed, so
both files take main's version unchanged and this PR no longer touches them.

Signed-off-by: Onur Yilmaz <[email protected]>

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(model): bound provider-response retries

4 participants