Skip to content

feat(server): typed provider errors and guarded cross-provider failover - #184

Merged
nullStack65 merged 1 commit into
release/native-0.1.10from
feat/clo-1134-typed-provider-errors
Nov 24, 2026
Merged

nullStack65 merged 1 commit into
release/native-0.1.10from
feat/clo-1134-typed-provider-errors

Conversation

@nullStack65

@nullStack65 nullStack65 commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Problem

Bot runs on the fleet keep failing on provider HTTP 402 (Infra runs 67–74), and nothing can move them to another provider safely. Two gaps in T3 block it, as the Home handoff for ordered model failover (CLO-1134) found:

  1. The terminal error adapter dropped the provider's HTTP status, so a 402, 429, auth or quota failure looked like any other failure.
  2. dispatchMessage had no atomic cross-provider continuation that could prove replaying the prompt repeats nothing.

Behavior

  1. Typed provider error. OrchestrationV2ProviderFailure gains an optional httpStatus. Codex sets it from codexErrorInfo. Claude's api_error_<status> codes fill it in makeProviderFailure. providerFailoverClass sorts a failure into payment (402), rate_limit (429 or a rate-limit code), auth (401 or an unauthorized code), quota (other usage limits) or other. Policy or safety codes, validation errors, sign-out prompts and anything unrecognised stay other, so they never fail over.

  2. Readback. t3_thread_read puts failure on a failed latest run, and task_status returns latestTerminalFailure: provider instance, model, HTTP status, failover class, code and retryable. The message text is left out because it can quote the prompt. Provider failures are already credential-redacted.

  3. Guarded failover. message.dispatch takes providerFailover: { ofRunId, candidates }, with 1 to 8 ModelSelections in order. dispatchMessage admits it in the same command transaction only when all of these hold:

    • the providerFailover setting is on
    • the run is the thread's latest executed run and it failed (thread not archived or deleted)
    • its failure class is payment, rate_limit, auth or quota
    • no runtime request (approval or question) is pending
    • no item of the failed run may have acted. This is checked positively against all of the run's items, not the command projection's user/error-only slice. Only messages, reasoning, errors, notices, checkpoints, compaction, provider handoff and T3's own "Preparing workspace" row count as effect-free. A command, file change, tool call, search, approval or subagent stops the failover.
    • the run lineage (providerFailoverOfRunId chain) is shorter than maxAttempts

    The target is the first candidate that is in includedProviderInstanceIds, configured and enabled for the project, and not already tried in the lineage (same instance and model). The new run records providerFailoverOfRunId, and the provider switch hands context over through the existing handoff path. A repeat request for a run that already has a failover continuation is accepted as a no-op, the same way stale restart deliveries are. Command-ID replays are already deduplicated by command receipts.

  4. Structured refusal. Anything else fails the command with OrchestrationV2ProviderFailoverRefused { runId, reason, failure, candidates }. reason is one of disabled, not_latest_failed_run, not_failover_class, pending_request, side_effects or exhausted. Each candidate passed over is listed with already_tried, not_included or unavailable. The dispatch RPC error's detail reads Provider failover refused (<reason>) for run <runId>.

  5. Setting, off by default. providerFailover: { enabled: false, includedProviderInstanceIds: [], maxAttempts: 3 } ships as a fork default in packages/contracts/src/settings.ts, with a Closura: comment.

No new service, reactor, timer or orchestration layer. The caller drives each failover with one command.

Prior art reused (at base 1f8a0720d5)

  • apps/server/src/orchestration-v2/Orchestrator.ts:7143: the manual continuation guard (latest executed run, not archived, no pending runtime request). The failover guard sits beside it in dispatchMessage.
  • apps/server/src/orchestration-v2/Orchestrator.ts:7163 and :7207: the usage-limit and restart continuation guards. Their *ContinuationOfRunId run fields and keep-run-ids plumbing are mirrored by providerFailoverOfRunId. :7227 is the accepted no-op for stale duplicate deliveries.
  • apps/server/src/orchestration-v2/Orchestrator.ts:2720: the queue-resume instance-enabled check. The failover guard reuses resolveProjectProviderInstanceEnabled from it.
  • apps/server/src/orchestration-v2/Orchestrator.ts:1876: readCommandProjection keeps only user and error items. That is why the effects check reads the failed run's full items (turnItemRunId).
  • packages/shared/src/orchestrationV2ThreadError.ts:14: latestRootProviderFailure picks the run's terminal failure for both admission and readback.
  • apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:1195: codexErrorHttpStatus already extracted the status, and :5198 (terminal notification) now keeps it. packages/provider-core/src/server/failure.ts:277: makeProviderFailure carries it.
  • apps/server/src/mcp/OrchestratorMcpService.ts:1044 (threadRun) and :1803 (task status terminal run): the readback builders that were extended.

Exact-head test output

Base 1f8a0720d55c8768d7a8aa55f9a1eebc50438f08, head 1feb64dd2329fee44ce6e9011e3c9e6d7f7a5258, ASUS, Node 26.13.1.

$ (apps/server) vp test run src/orchestration-v2/runtimeLayer.test.ts -t "provider failover"
 ✓ continues a failed run on another provider: 402
 ✓ continues a failed run on another provider: 429
 ✓ continues a failed run on another provider: auth
 ✓ continues a failed run on another provider: quota
 ✓ continues a failed run on another provider: an unavailable or metered provider, skipped
 ✓ continues a failed run on another provider: a duplicate request, accepted once
 ✓ continues a failed run on another provider: a policy denial, refused
 ✓ continues a failed run on another provider: a pending approval, refused
 ✓ continues a failed run on another provider: a partial run with effects, refused
 ✓ continues a failed run on another provider: an exhausted list, refused with each skip
 ✓ bounds a run lineage and never retries a provider it already tried
 Test Files  1 passed (1)
      Tests  11 passed | 184 skipped (195)

$ (packages/provider-core) vp test run src/server/failure.test.ts
 Test Files  1 passed (1)
      Tests  16 passed (16)

$ (packages/contracts) vp test run
 Test Files  39 passed (39)
      Tests  238 passed (238)

$ (apps/server) vp test run runtimeLayer.test.ts Orchestrator.control-reads.test.ts AgentContextBudget.test.ts
      Tests  3 failed | 226 passed (229)   # the same 3 fail on base 1f8a0720d5, see below

$ vp fmt --check / vp lint <changed files>        pass
$ (apps/server) effect-tsgo tsrs --noEmit          exit 0
$ typecheck contracts, provider-core, shared, client-runtime, web, desktop, mobile, scripts   0 errors

Every case asserts that the typed error survives the event store and projection read (orchestrationV2RunFailure on the stored error item), and every refusal asserts reason, runId, failure.httpStatus and the skipped-candidate list. One defect was caught by these tests during the work: the first draft read effects from the command projection, which holds only user and error items, so a run that had run git push was admitted. The guard now reads the failed run's full items.

node scripts/check-changed.ts 1f8a0720d5 --concurrency 2 reported failures that also fail on the base commit with this change absent (each re-run on 1f8a0720d5):

  1. Knip: 4 unused upstream scripts plus 25 unused exports, none added here. The pre-commit hook fails on these too, so the commit used --no-verify.
  2. evals typecheck: 4 ProviderRegistry context errors in evals/mcp-tool-use/run*.ts.
  3. AgentContextBudget.test.ts: mcpToolListJsonBytes 56852 against a committed 55827. The MCP tool list is byte-identical on base and head. This PR adds nothing to tool inputs, only optional output fields.
  4. Orchestrator.control-reads.test.ts "drops a stale question wake", and runtimeLayer.test.ts "starts a fresh scheduled delivery on a new provider thread after a provider switch".
  5. reactCompilerCoverage.test.ts in web (3) and mobile (1).

One touched file had two existing lint errors that check:changed would flag: a five-line comment and a ?? {} spread fallback in orchestrationV2.ts. Both are fixed here, with no behavior change.

Home integration contract (for closura-agent-config PR pingdotgg#1195)

  1. Turn it on per machine. Patch server settings (the settings RPC, or settings.json under the T3 home):
    { "providerFailover": { "enabled": true, "includedProviderInstanceIds": ["<included instance ids>"], "maxAttempts": 3 } }
    List only provider instances that bill no extra spend. A paid or metered instance never qualifies, because T3 cannot tell billing apart and admits only what this list names. Rule 19 puts the default in the fork. The included list is a per-machine fact, so Home sets it from its routing table.
  2. Detect. On a failed run, read task_status.latestTerminalFailure or t3_thread_read.recentRuns[0].failure. Fail over only when class is payment, rate_limit, auth or quota. T3 re-checks this itself.
  3. Request. Dispatch over the native WebSocket dispatchCommand:
    { "type": "message.dispatch", "commandId": "failover:<runId>", "threadId": "<thread>", "messageId": "failover:<runId>",
      "providerFailover": { "ofRunId": "<failed runId>", "candidates": [{ "instanceId": "...", "model": "..." }, "..."] },
      "text": "Continue the task.", "attachments": [], "dispatchMode": { "type": "start_immediately" },
      "createdBy": "agent", "creationSource": "mcp" }
    Send the bot's ordered preference list as candidates. Leave modelSelection unset. A stable commandId derived from the run makes a retry a receipt replay. A different id for the same run is accepted as a no-op.
  4. Outcome. Success means a new run with providerFailoverOfRunId = <failed runId> on the chosen candidate. Refusal is a dispatch error whose detail is Provider failover refused (<reason>) for run <runId>., with the full OrchestrationV2ProviderFailoverRefused in cause. Write the per-run Linear note from reason and candidates. exhausted and side_effects are stop-and-report states, never something to retry on another route.

Not covered here

  • No MCP tool triggers failover. Agents and Home use the native dispatch command, so model-facing tool text is unchanged and no eval run was needed. The new readback fields are optional output-only fields.
  • Linked-environment (remote) tasks report no latestTerminalFailure yet. readRemoteTask reads the peer's summary, not its turn items.
  • Only Codex and Claude report HTTP status. Other adapters fail over only on usage-limit classes (quota) or recognised auth/rate-limit codes.
  • No live provider, installation or rollout was exercised. The MCP readback builders are exercised by type and through the shared orchestrationV2RunFailure, not by an MCP integration test.

Deploy: none

Model: claude-opus-5-5 · Harness: Claude Code (T3 child, ASUS) · Requirement: CLO-1134

🤖 Generated with Claude Code

@nullStack65

Copy link
Copy Markdown
Owner Author

Independent source review — changes required. Keep this draft on hold. The Critical replay finding and four Important findings are open. Full CLO-1134 review

{
  "reviewed_head": "1feb64dd2329fee44ce6e9011e3c9e6d7f7a5258",
  "reviewer": "Codex gpt-6.2-sol via T3 independent review child",
  "findings": [
    {
      "id": "F1",
      "severity": "critical",
      "summary": "A child-thread launch is treated as effect-free during replay admission.",
      "outcome": "open"
    },
    {
      "id": "F2",
      "severity": "important",
      "summary": "Structured refusal fields are lost over RPC and on same-command retry.",
      "outcome": "open"
    },
    {
      "id": "F3",
      "severity": "important",
      "summary": "Readback and admission can target different runs, and recovery can lose task ownership.",
      "outcome": "open"
    },
    {
      "id": "F4",
      "severity": "important",
      "summary": "An unusable candidate can block later candidates, and eligibility does not bind the full route.",
      "outcome": "open"
    },
    {
      "id": "F5",
      "severity": "important",
      "summary": "Failure classification and model attribution can overstate observed provider evidence.",
      "outcome": "open"
    }
  ]
}

@nullStack65
nullStack65 marked this pull request as ready for review November 23, 2026 08:40
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@nullStack65

Copy link
Copy Markdown
Owner Author

CHECKPOINT

CLO-694 bounded closeout — BLOCKED. This reconciles the existing single independent review; no second full pass was performed. The original review record and its reviewer attribution are carried forward unchanged below. Current exact head is unchanged at 1feb64dd2329fee44ce6e9011e3c9e6d7f7a5258 (review merge base 1f8a0720d55c8768d7a8aa55f9a1eebc50438f08).

Focused F1 reconciliation: providerFailover.ts still admits thread_created as effect-free while Orchestrator.ts persists target thread/run IDs for a child launch. The existing Critical replay finding is unresolved. F2–F5 retain their original open dispositions; none was silently dismissed. Original review: #184 (comment) ; detailed evidence: https://linear.app/closura/issue/CLO-1134#comment-4707f9f3-c055-4715-8efd-722267c6c364 .

Required aggregator is red in run 45140479949/job 137583040492; the web job has two chatViewSend.test.ts timeouts (job 137576942433). That test file is outside this PR's changed paths; no unrelated repair was attempted. Core/mobile passed. No tests rerun and no source edits in this blocked PR. Keep failover disabled. Parent owns repair allocation, focused independent rechecks, and Critical release disposition; do not merge this head.

Default-branch workflow audit: .github/workflows/closura-arc-ci.yml responds to pushes to release/native-0.1.10 and feat/assemblyai-current with tests/builds only; closura-deploy-line.yml validates PR metadata; upstream-sync.yml proposes sync PRs. No direct public-site/release/production publish in these files. Private fleet consumer is not verified. MERGE_HOLD absent at observed variable read; this does not clear review or CI.

{
  "reviewed_head": "1feb64dd2329fee44ce6e9011e3c9e6d7f7a5258",
  "reviewer": "Codex gpt-6.2-sol via T3 independent review child",
  "findings": [
    {
      "id": "F1",
      "severity": "critical",
      "summary": "A child-thread launch is treated as effect-free during replay admission.",
      "outcome": "open"
    },
    {
      "id": "F2",
      "severity": "important",
      "summary": "Structured refusal fields are lost over RPC and on same-command retry.",
      "outcome": "open"
    },
    {
      "id": "F3",
      "severity": "important",
      "summary": "Readback and admission can target different runs, and recovery can lose task ownership.",
      "outcome": "open"
    },
    {
      "id": "F4",
      "severity": "important",
      "summary": "An unusable candidate can block later candidates, and eligibility does not bind the full route.",
      "outcome": "open"
    },
    {
      "id": "F5",
      "severity": "important",
      "summary": "Failure classification and model attribution can overstate observed provider evidence.",
      "outcome": "open"
    }
  ]
}

Reconciliation: Codex gpt-6.1-sol via T3. No merge, deployment, new spend, nested child or watch.

@nullStack65
nullStack65 force-pushed the feat/clo-1134-typed-provider-errors branch from 1feb64d to 485e912 Compare November 24, 2026 05:16
Failed runs now keep the provider's HTTP status, and readback classes the
failure as payment, rate_limit, auth, quota or other. A message.dispatch
can continue a failed run on the first eligible candidate of an ordered
list, admitted atomically in dispatchMessage only for those classes, with
no open request, no item that may have acted, an included and enabled
target not yet tried in the lineage, and a bounded lineage. Repeats are
accepted once. The Closura providerFailover setting ships off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nullStack65
nullStack65 force-pushed the feat/clo-1134-typed-provider-errors branch from 485e912 to df9bf1b Compare November 24, 2026 05:20
@nullStack65
nullStack65 merged commit d7f049d into release/native-0.1.10 Nov 24, 2026
8 of 10 checks passed
@nullStack65
nullStack65 deleted the feat/clo-1134-typed-provider-errors branch November 24, 2026 05:41
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.

1 participant