Skip to content

fix(client): bound retries between Gym servers and the TCP handshake - #6013

Merged
oyilmaz-nvidia merged 5 commits into
mainfrom
fix/bound-transport-defaults
Nov 12, 2026
Merged

oyilmaz-nvidia merged 5 commits into
mainfrom
fix/bound-transport-defaults

Conversation

@oyilmaz-nvidia

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

Copy link
Copy Markdown
Contributor

What goes wrong

Part of #2750 (rollout failures bounded, visible and recoverable); relates to the transport items in #3159.

  • A call between Gym servers (ServerClient, always _internal=True) retried connection errors, and retried any other error (timeouts, DNS, payload errors), without a limit when the caller passed no _max_num_tries, _max_connection_retries or retry window. A peer that stayed unreachable but was not seen dead by the head server could stall a rollout indefinitely.
  • The shared aiohttp sessions were built with ClientTimeout(), which sets every limit to None, so even a single TCP handshake had no bound.

The "internal calls retry quietly" behaviour comes from #90 (a restarting Gym server should be ridden out, and a truly dead one is handled by the head server). That stays. It now has a bound.

What this changes

  • Internal retry budget. A call between Gym servers with no caller-owned bound gets global_aiohttp_internal_retry_budget_seconds (default 600 s). It covers an unbroken run of connection errors (a ConnectionRetryWindow) and an elapsed cap on retries of other errors. 0 keeps today's unlimited retries. Calls that pass _max_num_tries, _max_connection_retries or their own window are unchanged.
  • TCP handshake timeout. sock_connect is set to global_aiohttp_sock_connect_timeout_seconds (default 60 s) on the data and control sessions. connect (which also counts the wait for a free pool slot), total and read time stay unlimited, so requests queued behind a busy pool, long generations and long /run episodes are not cut short.
  • A handshake timeout is a connection that was never made. aiohttp.ConnectionTimeoutError is retried like a refused connection, within the caller's limits and even for calls that must not resend a delivered request (a checkpointed /run, the collector's _max_num_tries with _retry_other_errors=False). The collector's connect-grace loop and its delivery="not_sent" marking, and the model-request outcome policy in single_agent_turn, recognise it as well as ClientConnectorError. A timeout under an open retry window keeps the window's original connection error.

Not changed

Compatibility

Behaviour change only for calls with no explicit bound that were failing for more than 10 minutes in a row: they now raise the last error instead of retrying forever. Set global_aiohttp_internal_retry_budget_seconds=0 to restore the old behaviour. New config fields are on GlobalAIOHTTPAsyncClientConfig and default-compatible.

Validation

  • tests/unit_tests/client: new tests for connection errors and other errors stopping at the budget, 0 meaning unlimited, a caller bound replacing the budget, and the handshake timeout on both sessions. Four existing mocks (test_http_client, test_rollout_collection, test_checkpoint_identity) got a real ClientTimeout because internal calls now open a retry window.

  • After merging main (conflicts only in openai_client.py and its test, both taken from main unchanged), the same suites run on this branch and on a clean origin/main checkout: tests/unit_tests/{client,rollouts,server_runtime,core,environment}, environment_servers/single_agent_turn/tests and environment_servers/legacy_agent/tests. The branch has 6639 passed, main 6615 passed (the difference is this PR's new tests). Both have the same 9 failing tests (old uv, missing cloudpickle). The branch showed three more in my checkout: two Ray opt-out tests that scan an untracked deps/ folder in my working tree (absent from a clean checkout), and one worker-pool test that passes when run alone.

  • pre-commit run --files <changed files> and import-linter: clean. DCO sign-off included.

  • Real processes: gym env start --resources-server example_single_tool_call --model-type vllm_model (against a stub OpenAI-compatible model endpoint) plus gym eval run --no-serve collected 5/5 rollouts with 0 failures.

  • Unmocked retry check: the real request(..., _internal=True) against a closed port with an 8 s budget raised ClientConnectorError after 8.0 s. With the 600 s default it was still retrying at 15 s. Clean main was still retrying at 40 s.

  • Killing a Gym server under gym env start makes the head supervisor shut everything down within seconds ("Process finished unexpectedly"), so that path did not exercise the budget. The budget covers a peer that stays alive but unreachable.

  • Review fixes (07e3457, 0e6011c): tests for handshake timeouts under each replay policy, read timeouts still not resent, the collector classifying a handshake timeout as never sent (mocked, and with a real full accept queue), the single_agent_turn policy, and a caller's limit replacing the internal budget. Each fails when its fix is removed. 5486 tests pass across the client, rollouts, server_runtime and core suites; the 9 failures and 1 collection error are in files this PR does not touch and are present on main in my environment (old uv, missing cloudpickle). single_agent_turn: 248 passed.

  • The two settings are documented in the configuration reference.

Rollout evidence

Smoke rollouts as above with a stub model (reward 0 is expected, the stub never calls the tool). No benchmark or training run: the change only affects calls that were already failing without a bound, and the defaults leave healthy calls untouched.

@copy-pr-bot

copy-pr-bot Bot commented Nov 11, 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 requested review from briyan-nvidia and yuhezhang-ai and removed request for briyan-nvidia November 11, 2026 19:00

@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 — No confirmed runtime defects found. One non-blocking test-coverage suggestion follows.

I reviewed all six changed files and traced the retry controls through ServerClient, the OpenAI retry scheduler, session configuration, and the affected rollout/checkpoint tests. This was static source review only; I couldn't execute tests or independently verify the validation reported in the PR.

Note: formal approval is not available for this request, so this review is posted as a comment only.

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

async def test_a_caller_bound_replaces_the_internal_budget(self, monkeypatch: MonkeyPatch) -> None:
client = MagicMock(timeout=ClientTimeout())
client.request = AsyncMock(side_effect=TimeoutError("peer hung"))
self._internal_budget_clock(monkeypatch, client, budget_s=1000.0)

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: make the caller-bound test detect simultaneous budget enforcement.

The 1000-second budget cannot expire during two immediate failures separated by one 0.5-second sleep. This test therefore also passes if the implementation incorrectly enforces the automatic budget alongside _max_num_tries. It protects attempt exhaustion, but not the replacement behavior named by the test.

Could you retain the existing two-attempt exhaustion assertion and add a recovery case that crosses a short automatic budget? After the current assertion, this additional setup would distinguish the two behaviors:

response = MagicMock()
client.request = AsyncMock(
    side_effect=[TimeoutError("peer hung"), TimeoutError("peer hung"), response]
)
self._internal_budget_clock(monkeypatch, client, budget_s=0.1)

actual = await nemo_gym.client.http_client.request(
    "POST", "http://peer:1/verify", _internal=True, _max_num_tries=3
)

assert actual is response
assert client.request.await_count == 3

The invariant is that an explicit attempt bound replaces—not supplements—the automatic internal budget, as implemented by the eligibility guard. The proposed case should recover on attempt three after two sleeps; incorrectly enabling the automatic budget would instead raise on the second timeout. Keep the existing cap-exhaustion assertion and the neighboring default-budget and zero-budget cases. These expected outcomes are source reasoning; I haven't executed the suggested test.

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.

Addressed in 07e3457 together with the same point from the other review (see the thread on this test file above). I have requested a fresh review.

bxyu-nvidia
bxyu-nvidia previously approved these changes Nov 11, 2026

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

Please preserve safe connection retries and never-sent accounting for the new handshake timeout before merging. The two smaller suggestions cover caller-limit test coverage and documenting the changed retry defaults.

client_session = ClientSession(
connector=connector,
timeout=ClientTimeout(),
timeout=ClientTimeout(sock_connect=cfg.global_aiohttp_sock_connect_timeout_seconds),

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 safe retries for connection-setup timeouts

The new sock_connect timeout raises aiohttp.ConnectionTimeoutError, which is neither ClientOSError nor ClientConnectorError. It enters the generic exception handler, which raises immediately for _resend_after_disconnect=False or _retry_other_errors=False. Consequently, a checkpointed /run, or an eval dispatch requesting _max_num_tries=2, _retry_other_errors=False, stops after its first unanswered handshake even though the task was never sent.

I reproduced this with real sockets and aiohttp 3.14.4 using a full accept queue and a shortened one-second handshake timeout: both policies made one attempt; a refused connection under the two-attempt policy made two. Collection's connect-grace and delivery="not_sent" checks also recognize only ClientConnectorError (rollout_collection.py:5502,5589), so this can consume failure/retry progress instead of recognizing an interruption before delivery.

Please handle connection-setup timeouts consistently in the safe connection-retry and never-sent classification paths, and add regression coverage for this boundary.

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.

Thanks, good catch. I reproduced it with a full accept queue and fixed it in 07e3457.

  • A connect timeout is now handled with the connection errors in _request_with_retries. It is retried even with _resend_after_disconnect=False or _retry_other_errors=False, it counts against the caller's limits, and when the window runs out the original connection error is still the one raised.
  • New is_unsent_connection_failure helper, used by the collector's connect-grace loop and by the delivery="not_sent" marking.
  • Tests: each replay policy resends a handshake timeout and stops at the attempt limit, read timeouts are still not resent, and a collector test with a real full accept queue. That one fails without the fix: the run gave up at 1.26 s instead of using the 1.5 s grace period.

While checking the other places that name ClientConnectorError, I found the same gap in single_agent_turn._model_request_not_sent: a handshake timeout was treated as possibly delivered. Fixed in 0e6011c, with a test. swebench_pro and agentic_if_realworld already accept ConnectionTimeoutError, and session_routing uses its own session, so they needed nothing.

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, verified on d891fd7. Handshake timeouts now retain safe connection retries and never-sent classification through the collector and single_agent_turn policy. Read and total timeouts remain excluded from safe retries. The real-socket grace-period test passes. This resolves the blocking finding.

async def test_a_caller_bound_replaces_the_internal_budget(self, monkeypatch: MonkeyPatch) -> None:
client = MagicMock(timeout=ClientTimeout())
client.request = AsyncMock(side_effect=TimeoutError("peer hung"))
self._internal_budget_clock(monkeypatch, client, budget_s=1000.0)

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.

[P3] Make the caller-limit test distinguish the competing policies

Nonblocking: a 1000-second default budget and two immediate failures pass whether the caller's limit replaces the default or both limits apply. Removing the _max_num_tries and _max_connection_retries exclusions from the implementation still passes this test and all four touched suites.

Could this use a short internal budget and connection errors so the implicit budget would expire before the explicit attempt limit? For example, a 0.1-second budget with ClientOSError and _max_num_tries=2 should still make two attempts; applying the implicit window incorrectly would stop after one.

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.

Agreed, the test passed under both policies. In 07e3457 I added your recovery case (0.1 s budget, _max_num_tries=3, recovers on the third attempt) and a ClientOSError variant with _max_num_tries=2. I also added _max_connection_retries and caller-window variants.

I checked them by temporarily making the budget apply alongside a caller's limit: all four new tests fail, and the original passes as before. The connection-error ones use a 0.25 s budget, because the fake clock does not add 0.1 s up exactly.

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.

Verified—the short-budget cases now exercise the distinction between replacing the automatic budget and applying both limits, covering attempt limits, connection retry limits, and caller-owned windows. This addresses the test gap.

"unless the caller passes its own timeout."
),
)
global_aiohttp_internal_retry_budget_seconds: float = Field(

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.

[P3] Document the new retry default and its scope

Nonblocking: please add the two new settings to the configuration reference and update the affected core retry descriptions. The request() docstring still says internal generic retries are unbounded and that no connection window means no time limit, while this default now supplies a 600-second window.

Please document the zero opt-out and clarify that, after the first connection error, the active window also counts waiting for a free connection-pool slot. The socket timeout itself excludes pool waiting, but the retry window does not. It would also help to state explicitly that the other-error elapsed cap currently starts at call entry, whereas the connection window starts at the first connection error.

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.

Done in 07e3457. The configuration reference has a new "HTTP Timeouts and Retries Between Servers" section covering both settings and the 0 opt-out. It states that the socket timeout excludes pool waiting while the connection window includes it after the first connection error, and that the other-error cap starts at call entry while the connection window starts at the first connection error. The request() docstring now describes the internal retry budget instead of saying internal retries are unbounded.

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.

Confirmed. The reference and request docstring now explain both settings, the zero opt-out, pool waiting under an active connection window, and the different clock start points. This addresses the documentation comment.

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.
- NeMoGymAsyncOpenAI(internal=True) now spends max_rate_limit_wait_seconds on
  every retryable rate-limit status instead of extending max tries forever;
  a budget of 0 keeps the unlimited behaviour.

Model connection retries stay unbounded by default (see #5181), and a POST
is still resent after an ambiguous disconnect; both are separate decisions.

Signed-off-by: Onur Yilmaz <[email protected]>
@oyilmaz-nvidia
oyilmaz-nvidia force-pushed the fix/bound-transport-defaults branch from 0eae750 to 6393859 Compare November 11, 2026 21:27
…r and document the budget

Address review of #6013.

- A handshake or pool-wait timeout (ConnectionTimeoutError) means the request
  was never sent, like a refused connection. Handle it with the connection
  errors in _request_with_retries, so a call that must not resend a delivered
  request (checkpointed /run, the collector's _max_num_tries with
  _retry_other_errors=False) still retries it within its bound. A timeout
  under an open retry window keeps the window's original connection error.
- Add is_unsent_connection_failure and use it for the collector's connect
  grace loop and its delivery="not_sent" classification, which only
  recognised ClientConnectorError.
- Tests: handshake timeouts are resent under each replay policy and stop at
  the attempt limit, read timeouts are not resent, the collector classifies a
  handshake timeout as not sent (mocked, and with a real full accept queue),
  and a caller's limit replaces the internal budget instead of adding to it
  (a short budget that connection errors and timeouts would spend).
- Document the two settings, the 0 opt-out and the clocks in the
  configuration reference and the request() docstring.

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

Copy link
Copy Markdown
Contributor Author

/review reset=true

oyilmaz-nvidia and others added 3 commits November 11, 2026 17:03
…tion in the model-request policy

_model_request_not_sent decides whether a failed model request may follow the
configured outcome action (it never connected) or must fail (it may have been
delivered). It recognised only ClientConnectorError. With the handshake
timeout on the shared client, a connect that hangs now surfaces as
ConnectionTimeoutError instead of the OS's ClientConnectorError, so such a
request was classified as possibly delivered. Both types report an incomplete
upload, and neither connected, so accept both.

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]>
@oyilmaz-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test d891fd7

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 12, 2026 19:30
@github-actions

Copy link
Copy Markdown
Contributor

@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 these. The handshake retry/classification fix, caller-limit coverage, and documentation resolve my review comments, and compatibility with the merged provider-retry policy is preserved. The remaining secrets-check failure is a parser error in the unchanged baseline from main.

@oyilmaz-nvidia
oyilmaz-nvidia added this pull request to the merge queue Nov 12, 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/43312405063

Merged via the queue into main with commit 11a62e4 Nov 12, 2026
114 of 115 checks passed
@oyilmaz-nvidia
oyilmaz-nvidia deleted the fix/bound-transport-defaults branch November 12, 2026 21:54
Comment on lines +819 to +834
except (ClientOSError, ConnectionTimeoutError) as error:
global _NUM_CLIENT_OS_ERROR
if _on_transport_failure is not None:
_on_transport_failure(error, _request_upload_complete(upload))
if not _resend_after_disconnect and not isinstance(error, ClientConnectorError):
timed_out = isinstance(error, ConnectionTimeoutError)
if timed_out and window is not None and window.expired():
# The connect cap set from the window ran out: report the connection error it stood for.
raise window.last_error from error
if not _resend_after_disconnect and not is_unsent_connection_failure(error):
raise
global _NUM_CLIENT_OS_ERROR
_NUM_CLIENT_OS_ERROR += 1
if not timed_out:
_NUM_CLIENT_OS_ERROR += 1
retries += 1
if _max_num_tries is not None and explicit_tries >= _max_num_tries:
raise
if _NUM_CLIENT_OS_ERROR % DISCONNECTED_CLIENT_OS_PRINT_INTERVAL == 0:
if not timed_out and _NUM_CLIENT_OS_ERROR % DISCONNECTED_CLIENT_OS_PRINT_INTERVAL == 0:

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.

External calls that hit a connect timeout no longer have an attempt limit, and these timeouts are never printed.

Before this PR, a ConnectionTimeoutError went to the generic except Exception branch. An external call (_internal=False) that passed its own connect or sock_connect timeout and no other limit stopped after MAX_NUM_TRIES (3) attempts and printed each one. The error now lands in this branch, which ends only through _max_num_tries, _max_connection_retries or a connection retry window. So the same call now retries forever, and because timed_out skips both the counter and the print, it does so without any output.

For example, request(..., timeout=ClientTimeout(connect=0.3)) against a full accept queue raises after three attempts on the merge base, but at this head it is still retrying after 10 attempts and 8 s, with nothing printed. No caller in the repository reaches the lost limit today, because each one that sets a connect timeout also passes a bound. NeMoGymAsyncOpenAI.connect_timeout_seconds is a public setting, however, so a model client that sets it without max_connection_retries would retry without end.

External calls with no timeout of their own now hit the 60 s sock_connect instead of the kernel's TCP connect timeout. Those calls were already unbounded on main, so the change for them is in what the log shows. On main, the kernel timeout surfaced as ClientConnectorError, which fed the _NUM_CLIENT_OS_ERROR counter and printed every 100th error, so many calls stuck on an unresponsive vLLM server showed up in the log. Now they print nothing.

Please restore the MAX_NUM_TRIES limit only for external calls that passed their own connect or sock_connect timeout, which keeps the default vllm_model client unbounded as vllm_model intends. Please also count and print connect timeouts under their own counter and message, not the ClientOSError help text.

Comment on lines +865 to +866
if internal_budget_s is not None and time.monotonic() - retry_start >= internal_budget_s:
raise

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.

When the internal retry budget runs out, the call raises without logging anything.

This line, the connection-error check in the branch above, and the window check at the top of the loop all re-raise the last error with no message. Internal calls also skip the "Hit an exception" print. So a call between Gym servers that gave up after 600 s of retries reads in the log the same as one that failed on its first attempt. The error still reaches the caller, but the fact that the internal retry budget stopped it is lost.

Please log one warning when the budget is spent, with the URL, the server name, the budget, the elapsed time, the number of attempts and the error type.

Comment on lines +824 to +826
if timed_out and window is not None and window.expired():
# The connect cap set from the window ran out: report the connection error it stood for.
raise window.last_error from error

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.

When a model client's connection retry window runs out on handshake timeouts, the raised error is not the one last passed to _on_transport_failure, so the NgFailureEvent is lost.

The first timeout opens the window and becomes window.last_error. Each later timeout is passed to _on_transport_failure but, by design, is not recorded in the window. When the window expires, this line raises the first timeout. NeMoGymAsyncOpenAI links its NgFailureEvent only when the raised error is the last one reported (openai_client.py). Here it is not, so the event is dropped and the observe_terminal call is skipped.

This affects a model server with endpoint_connection_retry_timeout_s (vLLM) or connection_retry_timeout_s set, while the vLLM server's handshakes keep timing out. Without the event, the failure report has no model request failure to select. single_agent_turn._model_request_not_sent then cannot treat the failure as never sent, even though this PR adds handshake timeouts to the errors it treats that way. For example, with a 1.5 s window the raised error's __cause__ was the NgFailureEvent on the merge base and a ConnectionTimeoutError at this head. The setting is opt-in, and on main a refused connection followed by a connect timeout under the window's cap already had the same mismatch.

The window can also expire at the check at the top of the loop, so changing only this line leaves that path open. Please have openai_client keep two failure events, one for the error that opened the current connection retry window and one for the last reported error, and match the raised error against both.

Comment on lines +201 to +204
- **Connection errors.** The window opens at the first connection error and closes when the server
answers, so it bounds an unbroken run of failures. After the first connection error, the window
also bounds each attempt's wait for a free pool slot, not only the handshake.
- **Other errors**, such as a timeout or a DNS failure. The cap is the time since the call started.

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.

Two statements in this list do not match the code.

A DNS failure is a connection error, not an "other error". In aiohttp 3.14.4, ClientConnectorDNSError subclasses ClientConnectorError, which subclasses ClientOSError (client_exceptions.py). So the connection-error branch catches it, and its clock starts at the first failure, not at the start of the call. Connect timeouts belong to the connection retry window as well, which leaves read and total timeouts as the timeouts the cap on time since the call started covers.

The window also bounds more than "an unbroken run of failures", because it closes only when response headers arrive. Take an internal /run that is resent after a dropped keep-alive connection, connects, runs for 700 s and then loses its connection again. It is still inside the connection retry window that opened at the first drop, so it is not resent. Likewise, a single attempt that runs longer than 600 s and then fails with another error is not retried, because that cap counts from the start of the call. Not resending a request that may already have been delivered is what #3159 asks for, so the behavior is right, and the text should say so. The compatibility note in the PR description ("only for calls … failing for more than 10 minutes in a row") has the same gap.

Suggested wording:

Suggested change
- **Connection errors.** The window opens at the first connection error and closes when the server
answers, so it bounds an unbroken run of failures. After the first connection error, the window
also bounds each attempt's wait for a free pool slot, not only the handshake.
- **Other errors**, such as a timeout or a DNS failure. The cap is the time since the call started.
- **Connection errors**, such as a refused connection, a DNS failure or a handshake timeout.
The connection retry window opens at the first connection error and closes only when the server sends response headers.
A request that connects, runs past the budget and then loses its connection is therefore not resent, because it may already have been delivered.
After the first connection error, it also bounds each attempt's wait for a free pool slot, not only the handshake.
- **Other errors**, such as a read or total timeout, or a malformed reply.
The cap is the time since the call started, so an attempt that ran longer than the budget is not retried.

Comment on lines +189 to +194
`global_aiohttp_sock_connect_timeout_seconds` (default `60`) limits one TCP handshake. It does not
count the wait for a free connection-pool slot, so a request queued behind a busy pool is not cut
short. Total and read time stay unlimited unless the caller passes its own timeout, because a model
generation or a `/run` episode can run for hours. A handshake that times out counts as a connection
that was never made: the request cannot have been delivered, so it is retried like a refused
connection, within the caller's limits and even where a dropped connection is not resent.

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.

This paragraph says that a caller's own timeout changes only total and read time. In aiohttp, a per-request timeout= replaces the session's ClientTimeout as a whole (client.py), so it also drops the 60 s sock_connect limit. For example, NeMoGymAsyncOpenAI with request_timeout_seconds builds ClientTimeout(total=..., connect=...) with no sock_connect. Those calls are still bounded by their own total, so nothing hangs. A reader tuning global_aiohttp_sock_connect_timeout_seconds would still expect it to apply to them.

The limit also covers the TLS handshake. It applies to every call on the shared sessions, including calls to external providers, not only to calls between Gym servers.

Suggested wording:

Suggested change
`global_aiohttp_sock_connect_timeout_seconds` (default `60`) limits one TCP handshake. It does not
count the wait for a free connection-pool slot, so a request queued behind a busy pool is not cut
short. Total and read time stay unlimited unless the caller passes its own timeout, because a model
generation or a `/run` episode can run for hours. A handshake that times out counts as a connection
that was never made: the request cannot have been delivered, so it is retried like a refused
connection, within the caller's limits and even where a dropped connection is not resent.
`global_aiohttp_sock_connect_timeout_seconds` (default `60`) limits one TCP and TLS handshake on every outgoing call that uses the shared sessions, including calls to external providers.
It does not count the wait for a free connection-pool slot, so a request queued behind a busy pool is not cut short.
Total and read time stay unlimited, because a model generation or a `/run` episode can run for hours.
A caller that passes its own `timeout` replaces the session timeout as a whole, so that call has no handshake limit unless its own timeout sets one.
A handshake that times out counts as a connection that was never made: the request cannot have been delivered, so it is retried like a refused connection, within the caller's limits and even where a dropped connection is not resent.

Comment on lines +176 to +178
async def advance(seconds: float) -> None:
sleeps.append(seconds)
clock.now += seconds

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.

If the budget stops working, these tests hang instead of failing. advance never yields to the event loop, and the mocked request fails on every call. So without a budget, the retry loop spins forever. With the merge-base code, the three budget tests never finished. The repository has no per-test timeout, so CI would run until the 45-minute job limit and never name the test.

A guard in the fake sleep makes them fail at once, and the zero-budget test (250 fake seconds) stays well inside it:

Suggested change
async def advance(seconds: float) -> None:
sleeps.append(seconds)
clock.now += seconds
async def advance(seconds: float) -> None:
sleeps.append(seconds)
clock.now += seconds
# Fail instead of spinning forever when no budget stops the retries.
if clock.now > 100.0 + 2000.0:
raise AssertionError("still retrying long after every budget in these tests")

assert 1.5 <= elapsed < 10
failures = config.output_jsonl_fpath.replace(".jsonl", "_failures.jsonl")
[row] = [json.loads(line) for line in open(failures) if line.strip()]
assert row["_ng_failure_record"]["delivery"] == "not_sent"

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.

This is the only test that fails when rollout collection's handling of connect timeouts is reverted, but it does not check that a timeout happened. On a network stack that answers a full accept queue with a reset instead of dropping the handshake, every attempt would raise ClientConnectorError. The test would then still pass without covering a timeout. The failure record already names the exception type, so asserting it keeps the test on the path it is meant to cover:

Suggested change
assert row["_ng_failure_record"]["delivery"] == "not_sent"
assert row["_ng_failure_record"]["delivery"] == "not_sent"
assert row["_ng_failure_record"]["exception_type"] == "ConnectionTimeoutError"

Comment on lines +827 to +830
unconnected_types = {
f"{error_type.__module__}.{error_type.__qualname__}"
for error_type in (ClientConnectorError, ConnectionTimeoutError)
}

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.

This set repeats the error types from is_unsent_connection_failure as exact type names, and the two disagree. The helper uses isinstance, so rollout collection treats a DNS failure, a TLS failure or a proxy connection failure as never sent, since each is a subclass of ClientConnectorError. This exact-name match does not. A DNS failure on a model request is therefore a terminal failure here but delivery="not_sent" in rollout collection. The exact match predates this PR, but the PR rewrote these lines.

Please export the helper's error types as one tuple from http_client, and build this set from those types and all of their subclasses, so both places use one definition.

Comment on lines +169 to +171
"Wall-clock budget for retries of a call between Gym servers when the caller passes no attempt or "
"retry-window limit: an unbroken run of connection errors, or retries of other errors, ends in the last "
"error once it is spent. 0 retries without a time limit."

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.

This description calls the caller's _connection_retry_window a "retry-window limit". The glossary reserves "retry window" for something else: its Not column lists it as a wrong name for the close retry window, which is how long a fence lasts. A reader who knows the glossary would look for session_close_retry_window_seconds here. The request() docstring already uses the full name, "connection retry window":

Suggested change
"Wall-clock budget for retries of a call between Gym servers when the caller passes no attempt or "
"retry-window limit: an unbroken run of connection errors, or retries of other errors, ends in the last "
"error once it is spent. 0 retries without a time limit."
"Wall-clock budget for retries of a call between Gym servers when the caller passes no attempt limit or "
"connection retry window: an unbroken run of connection errors, or retries of other errors, ends in the "
"last error once it is spent. 0 retries without a time limit."

@staticmethod
def _model_request_not_sent(response: NeMoGymResponse) -> bool:
"""A selected connector failure is safe only if every attempt of that operation never connected."""
"""A selected connector failure is safe only if every attempt of that operation never connected.

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.

This docstring still says "a selected connector failure", but the set now also holds ConnectionTimeoutError, which is not a ClientConnectorError. "Connection failure" covers both, and "safe to resend" says what the result decides:

Suggested change
"""A selected connector failure is safe only if every attempt of that operation never connected.
"""A selected connection failure is safe to resend only if every attempt of that operation never connected.

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.

5 participants