Skip to content

OpenAI provider doesn't treat TLS BadRecordMac / fatal-alert as retryable (inconsistent with other providers) #338

Closed

Description

@1jehuang

Summary

The OpenAI/Codex streaming path uses its own retryability classifier is_retryable_error (crates/jcode-base/src/provider/openai_stream_runtime.rs:1477) which does not include TLS-layer transient errors like BadRecordMac / received fatal alert. Every other provider (Claude, Copilot, OpenRouter, Anthropic) delegates to the shared is_transient_transport_error (crates/jcode-base/src/provider/routing.rs:5), which does classify these:

// routing.rs (used by Claude/Copilot/OpenRouter/Anthropic)
|| lower.contains("badrecordmac")
|| lower.contains("bad_record_mac")
|| lower.contains("fatal alert: badrecordmac")
|| lower.contains("received fatal alert: badrecordmac")
|| lower.contains("decryption failed or bad record mac")
// ... also tls handshake eof, dns errors, no route to host, network unreachable, connection aborted

openai_stream_runtime::is_retryable_error is missing all of the above (no badrecordmac, no fatal alert, no tls handshake eof, no connection aborted, no DNS/route errors).

Impact

On the OpenAI transport, a transient TLS blip (Stream error: IO error: received fatal alert: BadRecordMac) surfaces straight to the user and hard-fails the turn, with no retry. The exact same error on any other provider would be retried transparently. Reported by a user on v23.

Proposed fix

Have the OpenAI path delegate to (or include the cases from) the shared is_transient_transport_error so retry behavior is unified across all providers. Add a regression test asserting BadRecordMac / received fatal alert / tls handshake eof are classified retryable on the OpenAI path.

Notes

This is the correct fix regardless of any single user's root cause. It does not necessarily resolve a user whose underlying network path is corrupting TLS records (a proxy/VPN/hardware issue); in that case retries may still exhaust. It only ensures jcode treats these transient TLS/network errors consistently and gives them a chance to recover.

References

  • crates/jcode-base/src/provider/openai_stream_runtime.rs:1477 (is_retryable_error)
  • crates/jcode-base/src/provider/routing.rs:5 (is_transient_transport_error)
  • crates/jcode-base/src/provider/openai_provider_impl.rs:468 (retry decision in the OpenAI stream loop)

Activity

  1. 1jehuang commented on Jun 8, 2026

    @1jehuang
    OwnerAuthor

    Additional robustness gaps found during a wider transport audit

    While reviewing the original BadRecordMac issue, I audited all 5 provider retry paths (OpenAI, Claude, Anthropic, Copilot, OpenRouter). Beyond the classifier gap above, here are the other gaps worth tracking. Listing them here so they live alongside the original.

    2. OpenAI doesn't retry 429 / rate limits

    The other providers (Anthropic, Copilot) retry 429 too many requests / rate limit / rate_limit. OpenAI's is_retryable_error (openai_stream_runtime.rs:1477) has no 429 case; it only formats a "Rate limited" message and returns non-retryable. So a transient rate limit hard-fails on OpenAI but recovers on other providers. Should be unified.

    3. Duplicate / garbled output on mid-stream retry (all HTTP providers) -- highest correctness risk

    The retry loops re-invoke stream_response with the same tx sender after a failure. Several retryable errors are mid-stream (unexpected eof, error decoding, stream disconnected before completion, broken pipe). If text/tokens were already streamed to the user before the break, the retry replays the response from the top, producing duplicated or garbled output.

    Only the Claude CLI path guards this, via if !saw_output && is_retryable_error(...) (claude.rs:993). The HTTP providers (OpenAI, Anthropic, Copilot, OpenRouter) have no equivalent guard.

    Proposed fix: track whether any output was emitted in the current attempt, and only auto-retry mid-stream transport errors when nothing has been streamed yet (otherwise surface the error rather than silently duplicating). This is the subtlest but most user-visible robustness issue.

    4. No jitter in retry backoff (thundering herd)

    All providers use pure exponential backoff RETRY_BASE_DELAY_MS * (1 << (attempt - 1)) with no randomization. During a correlated upstream outage, many sessions retry in lockstep. Adding jitter (e.g. +/- 20%) is a cheap improvement.

    5. Inconsistent MAX_RETRIES

    Claude = 5; OpenAI / Anthropic / Copilot / OpenRouter = 3. Possibly intentional, but undocumented. Worth a comment or unification.


    Suggested grouping for fixes

    Additional references

    • crates/jcode-base/src/provider/claude.rs:993 (!saw_output guard, the only partial-output guard)
    • crates/jcode-base/src/provider/anthropic.rs:1580 (retry loop, no partial-output guard)
    • crates/jcode-base/src/provider/copilot.rs:633 (retry loop, no partial-output guard)
    • crates/jcode-base/src/provider/openrouter_sse_stream.rs:45 (retry loop, no partial-output guard)
    • crates/jcode-base/src/provider/claude.rs:28 (MAX_RETRIES = 5 vs 3 elsewhere)
  2. 1jehuang commented on Jun 9, 2026

    @1jehuang
    OwnerAuthor

    Fix posted + an additional root cause (anyhow .context() masking)

    PR #347 implements the low-risk unification from #1 (and the masking fix below).

    New root cause found: the classifier is fed a masked error string

    Routing OpenAI through is_transient_transport_error is necessary but not sufficient. Several providers feed the classifier e.to_string(), but when a transport cause is wrapped behind anyhow's .context("Failed to send request to ... API"), to_string() returns only the top-level context and hides the underlying cause. Verified with the shipped reqwest 0.12.28 + rustls:

    e.to_string()       = "Failed to send request to Anthropic API"                  // BadRecordMac hidden
    format!("{e:#}")    = "Failed to send request to ...: ... received fatal alert: BadRecordMac"  // visible
    

    So even with the shared classifier, the send-path causes are invisible. claude / copilot / openrouter (and OpenAI's OpenAIStreamFailure::Other path) all classified on the masked e.to_string(); only anthropic already used format!("{e:#}").

    PR #347:

    • OpenAI is_retryable_error delegates to the shared is_transient_transport_error.
    • claude/copilot/openrouter/openai classify on format!("{e:#}") (full source chain).
    • Regression tests for the TLS terms + the masked-context case.

    Deterministic reproduction added

    scripts/repro/tls-bad-record-mac/ wires reqwest(rustls) -> corrupting TCP proxy -> real rustls server; the proxy flips one ciphertext byte to force a genuine bad_record_mac fatal alert, reproducing the exact user error, then asserts old logic misses it and the fix retries. 15/15 stable.

    Scope note

    PR #347 covers gap #1 (and the masking sub-bug). The other gaps in this issue are intentionally left for follow-up: #2 (429 retry on OpenAI), #3 (no-output-yet guard before mid-stream retry; highest correctness risk), #4 (jitter), #5 (MAX_RETRIES). #3 in particular deserves its own careful PR.

    (Closing #346 as a duplicate of this issue.)

  3. added a commit that references this issue on Jun 9, 2026
    7fb1f52
  4. 1jehuang commented on Jun 11, 2026

    @1jehuang
    OwnerAuthor

    Status update: both BadRecordMac fixes are now fully on master.

    Validation: repro harness reproduces a genuine bad_record_mac fatal alert through a corrupting TLS proxy and confirms old logic fails immediately while the shipped logic retries; provider:: test suite passes (403 tests).

    Still open as follow-ups (not BadRecordMac per se): #3 no-output-yet guard before mid-stream retry, #4 backoff jitter, #5 MAX_RETRIES unification.

  5. 1jehuang commented on Jun 12, 2026

    @1jehuang
    OwnerAuthor

    Gap #3 (mid-stream retry duplication), #4 (jitter), and #5 (MAX_RETRIES docs) are now on master in ec2f3f8.

    Design: instead of refusing to retry after partial output (which would surface more errors to users), providers now emit a RetryRollback stream event when a transient transport fault hits mid-stream after output was already streamed. The agent loops discard the partial attempt's accumulators (so history records only the final attempt) and the TUI rolls back the on-screen partial render (streaming buffer, in-progress tool calls, and transcript-committed assistant segments from the aborted attempt). The user sees the partial text disappear, a 'retrying (n/3)' status, then the clean replayed response.

    Safe because jcode HTTP providers only execute tools after the stream completes, so a partial attempt has no side effects (the Claude CLI path keeps its existing no-retry-after-output guard since the CLI executes tools live).

    Validation: end-to-end regression test with a real SSE server that streams partial output then drops the socket mid-stream, asserting RetryRollback ordering and no duplication; plus attempt-tracker unit tests and jitter bound tests. All provider suites pass (409 tests).

    With this, all 5 gaps tracked in this issue are closed.

  6. added 8 commits that reference this issue on Aug 30, 2026
    3de80c8
    967ffc7
    e9ad858
    97ed59a
    46899d9
    55c5bb6
    8fc8bc0
    c510019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions