Skip to content

fix(model-refresh): refresh HTTP client on transport errors - #502

Closed
linusmixson wants to merge 4 commits into
Soju06:mainfrom
linusmixson:fix-reconnection
Closed

linusmixson wants to merge 4 commits into
Soju06:mainfrom
linusmixson:fix-reconnection

Conversation

@linusmixson

@linusmixson linusmixson commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR makes model refresh recover from transport-level upstream failures by rebuilding the shared aiohttp client and retrying the fetch once.

Handled failures now include compact error details, while unexpected exceptions still keep stack traces.

Observed Bug Evidence

Running codex-lb via uvx in low-reliability network environments (VPN, laptop sleep/wake, etc.) often resulted in the software entering a state in which the upstream connection was lost and could not be regained without restarting the process. These present changes make codex-lb behave seamlessly under the same condtions.

Root Cause

The model refresh path uses the shared aiohttp.ClientSession.

When the network changes underneath the process, the model fetch can fail before an HTTP response is received, surfacing as transport exceptions.

Previously, model refresh treated these the same as other model-fetch failures. It did not rebuild the shared HTTP client, so a bad/stale session or connector could continue to be reused after the network came back.

Fix

Model-fetch transport exceptions are now wrapped as ModelFetchError with transport_error=True.

When the scheduler sees the first transport error in a refresh cycle, it refreshes the shared HTTP client, closes the previous client, and retries the model fetch once.

HTTP status errors, auth failures, and invalid upstream responses stay on the existing paths.

The recovery logs now include the original transport error tersely, so failures are easier to diagnose without turning expected retry paths into stack traces.

Test Plan

  • uv run ruff check app/core/openai/model_refresh_scheduler.py tests/unit/test_model_refresh_scheduler.py
  • uv run pytest tests/unit/test_model_refresh_scheduler.py
  • uv run pytest tests/unit/test_http_client.py
  • uv run pytest tests/unit/test_model_refresh_scheduler.py
  • git diff --check

@linusmixson
linusmixson requested a review from Soju06 as a code owner April 26, 2026 23:21
@linusmixson linusmixson changed the title fix(model-refresh): surface recovery errors in logs fix(model-refresh): refresh HTTP client on transport errors Apr 27, 2026
@Soju06

Soju06 commented Apr 27, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7e45502853

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread app/core/clients/http.py Outdated
Comment on lines +74 to +75
if previous is not None:
await _close_client(previous)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid closing active shared client during transport recovery

refresh_http_client replaces the global client and immediately closes the previous one, but other request paths (for example app/core/clients/proxy.py at get_http_client().session) keep a per-request reference to that old session. If model refresh triggers this path while user traffic is in flight, those requests can fail mid-call with session/connection-closed transport errors unrelated to their own upstream health. This regression was introduced by runtime client rotation and needs graceful draining (or deferred close) instead of immediate teardown.

Useful? React with 👍 / 👎.

@Soju06

Soju06 commented Apr 27, 2026

Copy link
Copy Markdown
Owner

Thanks for digging into this @linusmixson — the failure mode you describe (codex-lb stuck after VPN flap / sleep without a process restart) is a real and frequently reported problem, and the fix shape (transport-error tagging + one-shot HTTP client rotation + retry) is in the right direction.

A couple of things to address before I merge:

P1 (codex review): old client closed while still in flight

The codex bot review caught a real concern that I'd want fixed before merge:

refresh_http_client() swaps the global client and then immediately calls _close_client(previous). Other call sites (proxy, etc.) hold per-request references to the old session / retry_client via get_http_client(). If a model-refresh transport recovery races a real proxy request, that proxy request can fail mid-flight with a session/connector-closed error unrelated to its own upstream — a regression introduced purely by client rotation.

Would you mind reworking refresh_http_client() so that the previous client isn't torn down synchronously? A reasonable shape:

  • swap _http_client to the new instance under the lock (already done)
  • schedule the previous client for closure on a small grace delay (or after its outstanding requests drain) rather than awaiting _close_client(previous) immediately
  • the simplest version: asyncio.create_task(_close_client(previous)) with a small await asyncio.sleep(...) inside, so the previous client lives long enough for in-flight requests to complete before its connector is torn down

Even better, a true "drain" (track in-flight requests on the client and only close after they complete) — but a deferred close on a timer is probably the right tradeoff here vs. the bookkeeping cost of true drain. Open to either.

If you'd rather not tackle the drain in this PR, an alternative is to scope the rotation to the model-fetcher only — give the model-refresh path its own dedicated aiohttp.ClientSession and only rotate that, leaving the shared _http_client for proxy / websocket traffic alone. That sidesteps the cross-path teardown entirely.

CI: ty type-check failing

The PR is currently red on Type check (ty) because of two issues:

  1. tests/unit/test_model_refresh_scheduler.py:106 — _fetch_with_failover expects list[Account] but the test passes [SimpleNamespace(...)]. Either annotate the helper as _account() -> Account (with a real Account instance), or add an explicit cast(list[Account], [account]) at the call site, or # type: ignore[arg-type] if you want to keep the duck type.
  2. There's a related "unused suppression comment" warning on tests/unit/test_model_refresh_scheduler.py:179 (# type: ignore[attr-defined] on registry._snapshot = snapshot — ty doesn't seem to need it). Easy drop.

You can reproduce locally with:

uv run ty check

Smaller things, not blockers

  • Nice call on _compact_error_message and the transport_error flag — the log lines are way more diagnosable now.
  • _fetch_models_with_transport_recovery keeping transport_recovery_attempted per failover loop (not per account) is the right call — avoids hammering rotation across many accounts.
  • (aiohttp.ClientError, asyncio.TimeoutError, OSError) is a reasonable transport-error classifier; consider also aiohttp.ClientConnectorError is already covered, but explicitly call out ConnectionResetError if you want belt-and-braces — it's an OSError subclass so already caught, just noting it.

Once the P1 (deferred close or scoped rotation) and the ty errors are addressed, this should be ready. Thanks again 🙏

@linusmixson

Copy link
Copy Markdown
Contributor Author

@Soju06 Can do; thanks for looking this over.

Retry model fetches after transport failures by refreshing the shared HTTP client.
  - Add transport-error classification to model fetch failures.
  - Refresh the shared HTTP client once on transport errors, then retry the fetch with the same account.
  - Keep the retry path from cascading into repeated reconnect attempts.
  - Add unit coverage for transport error detection, HTTP client refresh replacement, and failover retry behavior.

Agent: GPT-5.4; GPT-5.5
Agent: GPT-5.4-mini; GPT-5.5
@linusmixson

linusmixson commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Model's comments:

Changes address the PR review’s main blocker by replacing immediate shared HTTP client teardown with lease-aware client rotation.

The P1 race is handled in app/core/clients/http.py:25: the global client is now wrapped in _ManagedHttpClient, tracks active_leases, and only closes a retired client after all active leases release. refresh_http_client() now swaps in the replacement under the lock and requests close on the previous managed client instead of synchronously tearing it down while proxy/model/usage requests may still hold it (app/core/clients/http.py:197). Shutdown still force-closes active and retired clients so process exit does not hang on long-lived streams (app/core/clients/http.py:209).

Call sites that use the shared session/retry client were moved onto lease helpers, so in-flight work pins the client it started with. This includes model fetch, token refresh, OAuth flows, proxy streaming/compact/transcription, and usage fetch. The compatibility get_http_client() remains, but now documents that network use should lease the client (app/core/clients/http.py:227).

The model refresh recovery path was also broadened to cover token-refresh transport failures, not just model-fetch transport failures. RefreshError now carries transport_error, token refresh maps aiohttp.ClientError, timeout, and OSError into non-permanent transport errors (app/core/auth/refresh.py:40), and the scheduler performs one shared-client rotation/retry per failover loop for either refresh or fetch transport errors (app/core/openai/ model_refresh_scheduler.py:145).

The CI type-check comments from the review are fixed in tests/unit/test_model_refresh_scheduler.py:20: _account() now returns a real Account instead of a SimpleNamespace, and the unused suppression is gone. I ran uv run ty check; it passes.

Tests were expanded around the new behavior: HTTP client lease/drain semantics, forced shutdown, model-fetch transport retry, token-refresh transport retry, one-shot recovery across failover, and avoiding cached cooldown reuse for temporary transport refresh failures.

@Soju06: requesting rereview.

@linusmixson

Copy link
Copy Markdown
Contributor Author

@Soju06 ping (sorry)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants