Skip to content

refactor(agents): consolidate failover classification into one substrate - #121341

Merged
steipete merged 5 commits into
mainfrom
steipete/failover-02-substrate
Aug 10, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/failover-02-substrate

Conversation

@steipete

@steipete steipete commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Failover classification was spread across the oversized embedded-agent error grab-bag, three separate matcher modules, and two mutually exclusive provider-hook paths. That made precedence drift easy: structured and message-only failures did not consult plugins consistently, status-like numbers matched inside unrelated identifiers, and the same provider wording could land in timeout, overload, or server-error lanes.

This change creates one canonical failover substrate under src/agents/failover/, gives the frozen 16 reason codes a readonly tuple for later schema derivation, and makes one provider-plugin consultation with the fullest available signal precede legacy provider fallbacks and generic tables.

Why This Change Was Made

The classifier now owns the shared tables and precedence while concept-specific residue moved into small modules for assistant-message failures, runtime diagnostics, error text, image parsing, context observations, and signal extraction. The old errors.ts, failover-matches.ts, provider-error-patterns.ts, context-overflow.ts, and failover type path are removed rather than retained as shims.

The golden corpus moved with the classifier and was expanded with 189 distinct real strings recovered from the deleted matcher suites. It now covers 570 unique central-classification rows, while predicate-specific differences remain in focused tests.

User Impact

Approved classification changes:

  • Embedded numeric text input length 14295 tokens exceeds the model limit: rate_limit → unclassified. PR 6 will reclaim this wording in the canonical overflow table.
  • Request identifier req-4291: rate_limit → unclassified because 429 is no longer accepted inside identifiers.
  • Generic model wording model gpt-5.5-preview-0429 not found: rate_limit → model_not_found.
  • Generic model wording model model-x-500-preview not found: unclassified → model_not_found.
  • OpenAI model-id wording 400 Model Id [gpt-5.4-nano] not found: unclassified → model_not_found.
  • 503 Service Unavailable, Mistral temporary-unavailable text, generic LLM service-unavailable text, API-error service-unavailable JSON, billing/subscription service failures, and Retry-After service-unavailable text: timeout → overloaded (seven frozen corpus rows).
  • concurrency limit breached and concurrency limit was reached: unclassified → rate_limit.
  • Long provider JSON containing insufficient credits: billing predicate false → true; the 512-character cliff is gone while explanatory multi-section Markdown remains excluded.
  • ThrottlingException is now owned only by the generic word-bounded throttling rule; the legacy provider-specific result changes rate_limit → null. Central classification remains rate_limit.
  • throttling disabled for this account remains rate_limit by the accepted generic-rule tradeoff.
  • Explicit 429/rate-limit precedence over overloaded wording is unchanged. Auth-pattern breadth is unchanged. Plain 500/502/internal-server-error forms remain server errors.

Evidence

  • node scripts/run-vitest.mjs src/agents/failover: 16 files, 2,039 tests passed on the final head.
  • node scripts/run-vitest.mjs src/agents/embedded-agent-helpers: 15 files, 114 tests passed.
  • node scripts/run-vitest.mjs src/plugins/provider-runtime.test.ts: 66 tests passed.
  • Isolated post-sweep checks: model fallback 151 tests passed; incomplete-turn 172 tests passed.
  • pnpm build: passed in 5m22s; no [INEFFECTIVE_DYNAMIC_IMPORT] warning.
  • pnpm check:import-cycles: 0 runtime value cycles.
  • pnpm check:test-types: passed.
  • pnpm check:max-lines-ratchet: passed after pruning the two deleted oversized files.
  • pnpm plugin-sdk:api:check: passed with the regenerated manifest.
  • pnpm deadcode:dependencies and pnpm deadcode:exports: passed with zero unused exports.
  • Targeted changed-file oxlint and git diff --check: passed.
  • Production LOC: +2054 / -2058, net -4. Tests/corpus: +2794 / -1923, net +871.
  • Autoreview: initial two-chunk review and final guard-fix review both reported no accepted/actionable findings.

The requested broad src/agents sweep was attempted, but the shared host collapsed into unrelated 120-second timeouts across MCP, message-tool, cron, CLI, subagent, and hook suites while the heavy-check lock rotated among other worktrees. The two failover-adjacent failures from that run passed when isolated. node scripts/check-changed.mjs also attempted its required remote route, but every configured backend failed readiness; exact-head PR CI is the authoritative full type/lint fan-out.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 10, 2026
@steipete
steipete marked this pull request as ready for review August 10, 2026 01:54
@steipete
steipete requested a review from a team as a code owner August 10, 2026 01:54
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Aug 10, 2026
@steipete
steipete force-pushed the steipete/failover-02-substrate branch from ced60a0 to 9a4f3e5 Compare August 10, 2026 02:21
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 10, 2026
@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 9, 2026, 10:46 PM ET / August 10, 2026, 02:46 UTC.

ClawSweeper review

What this changes

This PR moves agent failover classification into a shared subsystem and redirects fallback, retry, gateway, cron, and provider consumers to the consolidated classifier.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep open: the proposed refactor removes the current cheap context-candidate gate before provider-hook dispatch, so ordinary error classification can resolve provider runtime unnecessarily. The branch is also currently dirty against main and needs a corrected rebase plus exact-head validation.

Priority: P2
Reviewed head: 0b4fbdd2b51201842cd73e2de5a6c81f648c87f2
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The consolidation has substantial focused coverage, but a concrete hot-path regression and dirty merge state prevent a higher rating.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored internal refactor is not subject to the external-contributor proof gate; the supplied focused test and CI evidence remains supplemental.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored internal refactor is not subject to the external-contributor proof gate; the supplied focused test and CI evidence remains supplemental.
Evidence reviewed 7 items Proposed hot-path regression: The supplied head patch changes the context-overflow wrapper to call unified provider classification before the table-based classifier, removing the current candidate gate.
Current lazy guard: Current main rejects non-context-shaped text before consulting provider overflow hooks, avoiding runtime hook resolution for generic failures.
User-visible caller: The same context-overflow predicate participates in formatting assistant-facing error text, making unnecessary hook dispatch part of routine error handling.
Findings 1 actionable finding [P2] Retain the cheap gate before resolving provider hooks
Security None None.

How this fits together

Provider and runtime errors are converted into stable failover reasons that drive model fallback, retry decisions, gateway responses, and user-facing recovery text. Provider plugins can refine those reasons before shared rules select the final outcome.

flowchart LR
A[Provider or runtime error] --> B[Failover signal]
B --> C[Context candidate check]
C --> D[Provider plugin classification]
C --> E[Shared error tables]
D --> F[Stable failover reason]
E --> F
F --> G[Fallback retry and user error output]
Loading

Decision needed

Question Recommendation
Should this protected maintainer PR be corrected to preserve lazy provider-hook dispatch, then rebased and revalidated on its exact head? Correct and revalidate: Restore an equivalent cheap context candidate gate before provider dispatch, add the no-call regression test, then resolve conflicts and rerun exact-head CI.

Why: The PR changes a shared provider-runtime hot path and currently has merge conflicts; protected maintainer work requires an explicit human merge decision after the mechanical correction.

Before merge

  • Retain the cheap gate before resolving provider hooks (P2) - This dispatches into provider classification before the table checks. On current main, non-context-shaped errors return before provider hooks are consulted; removing that gate can resolve provider runtime while formatting or classifying ordinary 429/auth/format failures. Keep an equivalent cheap prefilter and add a no-call regression test for a generic non-context error.
  • Resolve merge risk (P1) - Without the existing cheap candidate gate, generic auth, rate-limit, and format failures can enter provider runtime hook resolution during classification and user-error formatting.
  • Resolve merge risk (P1) - GitHub currently reports the branch as dirty against main, so merge conflict resolution and exact-head CI are required before landing.
  • Resolve merge risk (P1) - The PR head could not be fully materialized locally because the configured remote DNS lookup failed; review of the head relies on the supplied patch context.

Findings

  • [P2] Retain the cheap gate before resolving provider hooks — src/agents/failover/context-overflow.ts:90
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production vs test LOC production +2,054/-2,058 (net -4); tests/corpus +2,794/-1,923 (net +871) The refactor is production-net-negative while substantially expanding classification coverage, but the hot-path regression still needs correction.

Stored data model

Persistent data-model change detected: serialized state: src/agents/failover/signal-details.ts, serialized state: src/agents/failover/signal.test.ts, unknown-truncated-pull-files, vector/embedding metadata: src/agents/embedded-agent-helpers/image-errors.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Preserve lazy hook dispatch (recommended)
    Restore the context-candidate prefilter before resolving provider hooks and add focused coverage for generic non-context failures.
  2. Accept eager provider resolution
    Land the new dispatch order only if maintainers explicitly accept the runtime-loading and hook-side-effect cost for every error-classification path.

Technical review

Best possible solution:

Keep provider-hook consultation behind the existing cheap context-shape gate, retain table classification for ordinary errors, and add a regression test proving generic non-context errors do not invoke provider hooks.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: current main gates provider-hook dispatch on context-shaped text, while the supplied patch invokes it before table checks; a focused spy test can demonstrate the changed call behavior.

Is this the best way to solve the issue?

No: consolidation is reasonable, but the best fix retains the existing lazy candidate boundary before invoking provider hooks rather than making all error paths consult them.

Full review comments:

  • [P2] Retain the cheap gate before resolving provider hooks — src/agents/failover/context-overflow.ts:90
    This dispatches into provider classification before the table checks. On current main, non-context-shaped errors return before provider hooks are consulted; removing that gate can resolve provider runtime while formatting or classifying ordinary 429/auth/format failures. Keep an equivalent cheap prefilter and add a no-call regression test for a generic non-context error.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ca6a3797452b.

Labels

Label changes:

  • add P2: The patch has a concrete shared failover-path regression with bounded but cross-provider impact.
  • add merge-risk: 🚨 availability: Removing the prefilter can resolve provider runtime hooks during routine generic failure handling, adding avoidable hot-path work and possible hook side effects.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored internal refactor is not subject to the external-contributor proof gate; the supplied focused test and CI evidence remains supplemental.

Label justifications:

  • P2: The patch has a concrete shared failover-path regression with bounded but cross-provider impact.
  • merge-risk: 🚨 availability: Removing the prefilter can resolve provider runtime hooks during routine generic failure handling, adding avoidable hot-path work and possible hook side effects.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored internal refactor is not subject to the external-contributor proof gate; the supplied focused test and CI evidence remains supplemental.

Evidence

What I checked:

Likely related people:

  • steipete: Current classifier and provider-hook wrapper history attributes the central implementation to this contributor, who also authored the proposed consolidation. (role: recent area contributor; confidence: high; commits: 055a2dc6ced5; files: src/agents/embedded-agent-helpers/errors.ts, src/plugins/provider-runtime.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Restore the cheap provider-hook candidate gate and add a no-call regression test.
  • Resolve merge conflicts and rerun exact-head CI.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete force-pushed the steipete/failover-02-substrate branch 2 times, most recently from d8b067d to fb037cc Compare August 10, 2026 06:26
@steipete
steipete force-pushed the steipete/failover-02-substrate branch from fb037cc to 364a9f7 Compare August 10, 2026 06:38
@steipete
steipete merged commit 145ec37 into main Aug 10, 2026
123 checks passed
@steipete
steipete deleted the steipete/failover-02-substrate branch August 10, 2026 06:58
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

rishitamrakar added a commit to rishitamrakar/openclaw that referenced this pull request Aug 10, 2026
Upstream openclaw#121341 removed embedded-agent-helpers/types.ts; FailoverReason
now lives in failover/signal.ts. Also un-export two module-internal
symbols flagged by knip (ModelCircuitGateResult,
laterFallbackCandidateCanReachTransport).

Local gates on this head: build:plugin-sdk:dts, tsgo:core,
tsgo:core:test, tsgo:extensions, extension package boundary,
deadcode:full, check:max-lines-ratchet, oxlint, oxfmt - all clean;
425 tests passed (model-fallback, circuit, failover-error suites).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 11, 2026
…ate (openclaw#121341)

* refactor(agents): consolidate failover classification substrate

* chore(agents): align failover refactor guards

* fix(agents): preserve leading 429 status handling

* perf(agents): retain lazy failover hook gating

* chore(agents): refresh failover guard artifacts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant