Skip to content

feat(codex): add opt-in provider-host circuit breaker - #1243

Merged
Wibias merged 35 commits into
devfrom
maint/1039-host-circuit
Aug 7, 2026
Merged

feat(codex): add opt-in provider-host circuit breaker#1243
Wibias merged 35 commits into
devfrom
maint/1039-host-circuit

Conversation

@Wibias

@Wibias Wibias commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Supersedes #1039.

This is a maintainer-owned port of the provider-host circuit work from #1039 onto current dev. The original feature commit was cherry-picked cleanly so the contributor attribution is preserved, then the implementation was reviewed and hardened on the current routing/auth/config code.

What changed

  • Adds opt-in upstreamHostCircuitThreshold for native OpenAI forward Responses and native compact sends.
  • 0 disables the circuit; live writes accept only integer values 120 when enabled.
  • Counts only terminal logical pre-connection connect_neutral DNS/TCP failures.
  • Opens a 30-second provider-origin cooldown and returns bounded 503 + Retry-After before final Pool account selection/upstream send when possible.
  • Admits exactly one half-open logical request after cooldown.
  • Uses generation-fenced leases so stale physical retries cannot mutate a newer circuit generation.
  • A real HTTP response closes the circuit, including a concurrent admitted request that reaches the host after its peer opened the cooldown.
  • Aborts/local/non-connect failures release admission without adding host evidence.
  • Applies only to unpinned Codex Pool routing; direct mode and account-qualified selectors are inert.
  • Disabling the option downgrades prior circuit-owned state to observational state so disabled-mode success can clear stale failures instead of resurrecting an old circuit when re-enabled.

Review findings carried forward from #1039

All four unresolved CodeRabbit findings from #1039 were addressed:

  • documentation distinguishes account cooldowns from the provider-host cooldown;
  • regular Responses and compact share the circuit eligibility predicate and 503 builder;
  • blocked-request tests directly assert final Codex account resolution is not invoked;
  • lease-key mismatch has focused regression coverage for reset and failure settlement.

Additional maintainer fixes

The current-tree review also fixed:

  1. Strict config contract. The original field was TypeScript-only and passed through config parsing, so invalid live values could be silently disabled/clamped. Malformed hand edits now degrade only this optional feature with a warning, while live writes reject invalid values.
  2. Disable/re-enable stale state. Turning the threshold off now revokes circuit/lease authority while preserving only observational history.
  3. Concurrent success semantics. A real HTTP response from an already-admitted same-generation request can close a cooldown opened concurrently by a peer, while stale failures remain fenced out.
  4. Pre-send probe cleanup. If adapter.buildRequest() throws after Codex auth selection, any claimed quota probe lease is released before propagating the error.
  5. State-machine coverage. Added threshold-boundary, failure-window expiry, retention-cap, active-lease retention, concurrent-success, mismatched-key and disable/re-enable regressions.
  6. CI shard stability. The new regressions are consolidated into existing test files so Bun's deterministic 4-way file sharding remains on the repository's established layout; this avoids unrelated Bun 1.3.14 epoll_ctl EEXIST isolate corruption caused by changing the test-file count.
  7. Pre-auth quota-prime suppression. When the canonical ChatGPT provider-origin circuit is open, subagent quota priming now uses cached quota instead of sending credential-bearing /backend-api/wham/usage probes to the same unavailable origin. The single-flight path re-checks the circuit after taking ownership, while the final route-dependent host admission remains in place after fallback selection.
  8. Review/test hardening. Added a positive control for the quota-prime circuit gate, asserted every active-lease release under retention pressure, and corrected the synthetic timestamps so the regression genuinely crosses the 60-second quota-prime TTL.

Security / privacy review

  • no credential, API-key, token, account-id, request-body, or response-body material is stored in host-circuit state;
  • host keys use provider name plus canonical origin only;
  • no new SSRF target selection, auth bypass, command injection, routing privilege, billing, or account-health mutation was introduced;
  • state remains process-local and retention-bounded;
  • generation fencing prevents stale failure mutation while allowing only narrowly scoped reachability proof from concurrent admitted HTTP success.

Validation

Final maintainer validation on head 36c4058:

  • React Doctor: green
  • Cross-platform CI: green (run 31224500702, attempt 2)
  • Linux test shards 1/4, 2/4, 3/4 and 4/4: green
  • macOS full unsharded suite: green
  • npm-global smoke: green on Ubuntu, macOS and Windows
  • typecheck / GUI tests / privacy scan / release-helper syntax / CLI smoke: green
  • CodeRabbit: green
  • all inline CodeRabbit/Codex review threads: resolved
  • no submitted REQUEST_CHANGES review remains

The first shard-4 attempt hit the repository's known Bun 1.3.14 isolate/runtime corruption (EEXIST: file already exists, epoll_ctl, followed by test registration after the run had already terminated) and timed out. Re-running that unchanged shard on the same head completed successfully, confirming the failure was runtime flakiness rather than a code change.

Summary by CodeRabbit

  • New Features
    • Added an optional provider-host circuit breaker for DNS/TCP connection failures.
    • Thresholds support values from 0–20 and are disabled by default.
    • Open circuits return 503 responses with Retry-After and allow recovery probes after 30 seconds.
    • Protection covers regular and compact requests without affecting account health or failover routing.
  • Documentation
    • Updated provider configuration guidance across supported languages.
  • Bug Fixes
    • Clarified which failures count toward provider failover thresholds.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds an opt-in provider-host circuit breaker for native Responses and compact requests. It adds configuration validation, lease-based cooldown and recovery state, request-path integration, quota-priming checks, tests, and localized documentation.

Changes

Provider host circuit breaking

Layer / File(s) Summary
Configuration contract
src/types.ts, src/config.ts, tests/config-user-edits.test.ts, docs-site/src/content/docs/.../configuration/providers.md
Defines upstreamHostCircuitThreshold, validates integers from 0 through 20, warns on malformed persisted values, rejects invalid writes, and documents the 30-second cooldown and excluded failures.
Lease-based host health state
src/codex/upstream-host-health.ts, tests/upstream-reachability.test.ts
Adds admission leases, cooldowns, half-open probes, concurrent lease handling, generation fencing, release, disabling, reset behavior, pruning, and health snapshots.
Responses and compact request integration
src/server/responses/core.ts, src/server/responses/compact.ts, tests/responses-compaction-routing.test.ts
Adds pre-auth circuit admission, leased failure recording, successful-response settlement, cancellation cleanup, retry handling, and 503 responses with Retry-After.
Quota priming circuit gate
src/codex/subagent-model-fallback.ts, tests/upstream-reachability.test.ts
Skips Codex quota priming while the canonical upstream host circuit is cooling down and rechecks the circuit after single-flight ownership is acquired.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Responses
  participant UpstreamHostHealth
  participant AccountSelection
  participant ProviderUpstream
  Client->>Responses: Submit Responses or compact request
  Responses->>UpstreamHostHealth: Acquire host admission
  UpstreamHostHealth-->>Responses: Lease or 503 circuit-open response
  Responses->>AccountSelection: Resolve account after admission
  Responses->>ProviderUpstream: Send request
  ProviderUpstream-->>Responses: Success or connection failure
  Responses->>UpstreamHostHealth: Settle, record failure, or release lease
  Responses-->>Client: Return provider response or error
Loading

Possibly related PRs

Suggested reviewers: ingwannu, lidge-jun

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.42% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding an opt-in provider-host circuit breaker for Codex.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch maint/1039-host-circuit

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Wibias commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs-site/src/content/docs/reference/configuration/providers.md`:
- Line 28: Update the upstreamHostCircuitThreshold documentation to state that
the circuit applies only to Codex pool routing with no pinned account and
remains inert for codexAccountMode: "direct" or account-qualified selectors. Add
equivalent wording to
docs-site/src/content/docs/reference/configuration/providers.md:28-28,
docs-site/src/content/docs/ja/reference/configuration/providers.md:26-26,
docs-site/src/content/docs/ko/reference/configuration/providers.md:26-26,
docs-site/src/content/docs/ru/reference/configuration/providers.md:27-27, and
docs-site/src/content/docs/zh-cn/reference/configuration/providers.md:26-26.

In `@docs-site/src/content/docs/zh-cn/reference/configuration/providers.md`:
- Line 25: Remove the locale-only clause “未确认的失败仍归属账户。” from the
upstreamFailoverThreshold row in the zh-cn provider configuration table, leaving
the shared behavioral description consistent with the English, ja, ko, and ru
locale rows.

In `@src/codex/upstream-host-health.ts`:
- Around line 302-307: The cooldown-generation change in
recordUpstreamHostFailure invalidates concurrent leases, preventing
resetUpstreamHostHealth from honoring a later HTTP response. Update the
lease-matching/reset flow so a fenced-out lease issued before the cooldown can
still clear that cooldown, preserving newer-generation safety; add a regression
test in the existing upstream-host circuit concurrency tests covering
failure/open first followed by a concurrent successful response.

In `@src/server/responses/core.ts`:
- Around line 2485-2490: Update the request-building flow around
adapter.buildRequest() to catch pre-send failures, release the Codex probe lease
via releaseCodexAuthContextProbeLease(authCtx), and rethrow the original error.
Keep the existing finally behavior conditional so streaming responses retain
probe ownership, and add a regression test covering this failure when host
admission is disabled.

In `@tests/upstream-host-circuit.test.ts`:
- Around line 19-50: Add focused tests in the existing opt-in upstream host
circuit describe block for failure-window expiry and retention-cap eviction,
using the explicit now values and constants shown in the review; also cover the
all-active-lease retention path so pruneTo’s early return is exercised. Extend
the threshold normalization assertions to include 0, the string "3", and 20,
verifying invalid values normalize to 0 and valid values remain bounded. Add the
required imports for UPSTREAM_HOST_FAILURE_WINDOW_MS and
UPSTREAM_HOST_HEALTH_MAX_ENTRIES, and keep the tests near the existing
upstream-host circuit coverage.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3a4c9388-fffd-4e5c-af31-a3a712b967eb

📥 Commits

Reviewing files that changed from the base of the PR and between 9326b85 and 0aa775a.

📒 Files selected for processing (13)
  • docs-site/src/content/docs/ja/reference/configuration/providers.md
  • docs-site/src/content/docs/ko/reference/configuration/providers.md
  • docs-site/src/content/docs/reference/configuration/providers.md
  • docs-site/src/content/docs/ru/reference/configuration/providers.md
  • docs-site/src/content/docs/zh-cn/reference/configuration/providers.md
  • src/codex/upstream-host-health.ts
  • src/config.ts
  • src/server/responses/compact.ts
  • src/server/responses/core.ts
  • src/types.ts
  • tests/responses-compaction-routing.test.ts
  • tests/upstream-host-circuit-config.test.ts
  • tests/upstream-host-circuit.test.ts

Comment thread docs-site/src/content/docs/reference/configuration/providers.md Outdated
Comment thread docs-site/src/content/docs/zh-cn/reference/configuration/providers.md Outdated
Comment thread src/codex/upstream-host-health.ts
Comment thread src/server/responses/core.ts
Comment thread tests/upstream-host-circuit.test.ts Outdated
@Wibias
Wibias marked this pull request as ready for review August 7, 2026 21:22

Wibias commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Already reviewed.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 745b3384d6

ℹ️ 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 src/codex/upstream-host-health.ts
Comment thread src/server/responses/core.ts

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/upstream-reachability.test.ts`:
- Around line 349-356: Strengthen the “retention pressure never evicts an active
admission lease” test by asserting that releaseUpstreamHostAdmission returns
true for every lease, including leases[0]. Replace the discard-only release loop
over leases.slice(1) with per-lease assertions while preserving the existing
release timestamps and coverage of all 129 leases.
- Around line 185-212: Add a final positive-control invocation in the test using
a closed or otherwise healthy upstream circuit, then assert primeCalls is 1.
Keep this step after the existing blocked assertions so
maybePrimeSubagentQuota’s Date.now()-based quotaPrimedAt does not affect earlier
checks, and preserve the existing setSubagentQuotaPrimeForTests wiring.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e1ff9a67-1265-46c2-b935-9b44f69d92ce

📥 Commits

Reviewing files that changed from the base of the PR and between d489e3d and aba10a4.

📒 Files selected for processing (3)
  • src/codex/subagent-model-fallback.ts
  • tests/config-user-edits.test.ts
  • tests/upstream-reachability.test.ts

Comment thread tests/upstream-reachability.test.ts
Comment thread tests/upstream-reachability.test.ts

Wibias commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer takeover/review complete.

  • feat(codex): preserve opt-in provider-host circuit follow-up #1039 has been superseded and closed, with contributor attribution preserved here.
  • Full manual pass covered routing/auth boundaries, concurrency and generation fencing, half-open/recovery semantics, cleanup paths, config validation, compact/Responses parity, retention, privacy/security, and direct/pinned inertness.
  • All CodeRabbit/Codex inline findings were fixed or resolved. No REQUEST_CHANGES review remains.
  • Extra hardening: an open ChatGPT provider-origin circuit now suppresses credential-bearing subagent quota priming; focused two-sided regression coverage verifies both blocked and healthy paths.
  • React Doctor and Cross-platform CI are green on 36c4058. The one failed shard-4 attempt was Bun 1.3.14 epoll_ctl EEXIST isolate corruption; rerunning the unchanged shard passed cleanly.

No known merge-blocking issue remains from this review.

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

✅ READY

  • all PR quality gates passed.

@github-actions
github-actions Bot marked this pull request as draft August 7, 2026 22:58
@Wibias

Wibias commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

no gui

@Wibias
Wibias marked this pull request as ready for review August 7, 2026 23:05
@Wibias
Wibias merged commit 396a009 into dev Aug 7, 2026
40 of 43 checks passed
@Wibias
Wibias deleted the maint/1039-host-circuit branch August 7, 2026 23:06

@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: 36c4058158

ℹ️ 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 on lines +1878 to +1879
const hostCircuitEnabled = hostKey !== null
&& normalizeUpstreamHostCircuitThreshold(config.upstreamHostCircuitThreshold) > 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restrict circuit admission to documented pool routes

When upstreamHostCircuitThreshold is nonzero, this condition enables the circuit for every forward-auth passthrough route, including codexAccountMode: "direct", account-qualified routes with route.codexAccountId, and noncanonical forward providers. After enough qualifying connection failures, those routes therefore start returning 503, despite docs-site/src/content/docs/reference/configuration/providers.md documenting the option as limited to unpinned Codex Pool routing and inert for Direct/account-qualified requests; the compact path repeats the same unrestricted check. Include the same pool, unfixed-account, and canonical-provider restrictions used by the pre-auth admission helper, or update the documented contract if this broader behavior is intended.

AGENTS.md reference: AGENTS.md:L231-L232

Useful? React with 👍 / 👎.

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants