Repository navigation
fix(model): bound internal provider-response retries - #5890
Conversation
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]>
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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.
| """ | ||
| try: | ||
| return await response.content.read() | ||
| return (await response.content.read())[:ERROR_BODY_PREFIX_BYTES] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. | |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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]>
Signed-off-by: Onur Yilmaz <[email protected]>
|
/ok to test ff167e5 |
|
/review |
|
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 |
giuliolovisotto
left a comment
There was a problem hiding this comment.
Approved. No must-fix findings in the focused retry change; the reviewed files are unchanged by the latest merge from main.
|
/ok to test 9ed31e6 |
@oyilmaz-nvidia, there was an error processing your request: See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/ |
yuhezhang-ai
left a comment
There was a problem hiding this comment.
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.
|
/ok to test 69770b2 |
|
/ok to test c58a951 |
yuhezhang-ai
left a comment
There was a problem hiding this comment.
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.
|
/ok to test 7f1b6f7 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43085530561 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43098676237 |
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]>
…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]>
What changed
An internal
NeMoGymAsyncOpenAIclient (internal=True) raised its attempt cap on every 429/502/503/504/520 answer.triesandmax_num_triesgrew together, so a saturated provider was retried forever. This is the failure PR #2527 describes (a single request reached 10,895 attempts).max_rate_limit_wait_seconds) that external clients use for 429/503. With a budget of 0 they stop atmax_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.context_length_exceededanswer 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.code,typeandparamintact, so the next client reads the same terminal code. Small and non-JSON bodies are unchanged. The final status is kept.vllm_model,openai_model,switchyard_model,inference_provider) passinternal=Falseexplicitly. Theinternalfield stays; its description andopenai.mdxare updated.Backoff (full jitter, 1 s doubling, 60 s cap) and
Retry-Afterhandling (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
internal=Trueon this client no longer retries without limit. It now stops atmax_rate_limit_wait_seconds(default 3600 s) ormax_http_attempts. No code in this repository sets it on this client; configs outside the repo are not visible to me.http_client.py(_internal), which fix(openai_model): bound refused provider connection retries #5199, fix(model): add an optional connection retry time budget #4853 and fix(vllm_model): opt-in time cap on connection retries to a dead model server #5181 cover.OutcomePolicyConfig) instead of the module constantsRETRY_ERROR_CODESandWAIT_OUT_ERROR_CODES.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-Afterbeyond 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 localaiohttpstub): 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/clientandtests/unit_tests/models: 2483 passed.vllm_model1040,openai_model170,switchyard_model53 (11 skipped),inference_provider33. All passed.pre-commit(ruff, ruff-format, import-linter) passed on the changed files.tests/unit_tests/server_runtime/test_review_boundary_interfaces.py(collection error,cloudpicklemissing from my venv; it fails the same way onmain), the fulltests/unit_testssuite, per-servergym env test, and the functional and e2e suites.Real rollouts.
gym env startplusgym eval run --no-servewithexample_single_tool_call, the realopenai_modelserver andsimple_agent, against a local stub provider.internal=Truewas forced with a temporary, uncommitted env-var edit toopenai_model/app.py, because nothing in the repo sets it. The stub cycles 429/503/502/504/520 withRetry-After: 1.environment_server_failedand a final HTTP 500. Every attempt's status is recorded as amodel_request_errorevent with itshttp_status.Limits of this evidence: the provider was a stub, not a real model endpoint;
internal=Truewas forced. Before the fix I checked old-code behavior only with aTestClientscript, which was still retrying whentimeoutkilled 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=Trueforced by a temporary uncommitted env-var edit toopenai_model/app.py, reverted afterwards).Retry-After: 1)context_length_exceeded429model_retryand no wait. The layer above the model server retried the forwarded 429 (3 requests per rollout in total); that layer is unchanged.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_errorhandler, not by these runs. Same limits as above: a stub provider, andinternal=Trueforced.gym env startalso pollsGET /v1/modelson 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).