From ad63408f57e3eadb79aa0e3c05a9f6cb9e8b1c1d Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 18:04:35 +0000 Subject: [PATCH 1/4] feat: typed transient/permanent errors, fault-injection upstream, dev deploy canaries, PR template Bugs from 30 Nov passed CI and were found by using the app. This adds the guards that catch that class before users do. - Typed errors: `Orb.ErrorCode` is the one registry of error codes (transient reason or permanent); `OrbCore.ErrorClass` reads a harness's error text by `[orb:]` tags, error JSON code fields and the HTTP status, never phrases. The proxy tags every error message whose body names a registered code, stream-cut frames carry their tag, and the Pi driver's exit error carries `harness_exited`. Replaces the substring classifier. Shared vectors: shared/orb-spec/fixtures/error-classes.json, replayed by orb-spec-runner. - Fault-injection upstream: `/__fault/v1/*` in Core, on only when ORB_FAULT_UPSTREAM_KEY is set (dev, tests), speaking Chat Completions, Responses and Anthropic Messages; models fault-ok, fault-503, fault-503x, fault-cut, fault-stall-, fault-late429-. - Deploy canaries: scripts/ops/orb-deploy-canary, run by orb-deploy before prod promotion: restart dev and launch at once, harness x placement missions on the fault upstream to a real first turn, Pi 503 recovery, proxy cut/stall/late-429 probes, Mythos 403 no_cyber_access_account, no ghost missions. Reports via `orb-monitor --report`. ORB_DEPLOY_CANARY=warn|skip overrides. - PR template: "Not verified live" is a checklist closed by a named canary or follow-up. --- .github/pull_request_template.md | 25 ++ AGENTS.md | 3 +- docs/INFERENCE_PROTOCOLS.md | 23 +- docs/operations/deploy-canaries.md | 42 +++ docs/specs/fault-upstream.md | 39 +++ docs/specs/typed-errors.md | 50 +++ lean/Orb/ErrorCode.lean | 80 +++++ lean/Orb/PiHarness.lean | 9 +- lean/OrbCore/OrbCore.lean | 2 + lean/OrbCore/OrbCore/ConformanceRunner.lean | 39 ++- lean/OrbCore/OrbCore/Control.lean | 54 ++- lean/OrbCore/OrbCore/ErrorClass.lean | 88 +++++ lean/OrbCore/OrbCore/FaultUpstream.lean | 197 +++++++++++ lean/OrbCore/OrbCore/Proxy.lean | 4 + lean/OrbCore/OrbCore/ProxyRoutingTests.lean | 65 +++- lean/OrbCore/OrbCore/RemoteDispatch.lean | 44 +-- scripts/ops/orb-deploy | 30 +- scripts/ops/orb-deploy-canary | 362 ++++++++++++++++++++ scripts/ops/orb-monitor | 18 + shared/orb-spec/fixtures/error-classes.json | 58 ++++ 20 files changed, 1180 insertions(+), 52 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 docs/operations/deploy-canaries.md create mode 100644 docs/specs/fault-upstream.md create mode 100644 docs/specs/typed-errors.md create mode 100644 lean/Orb/ErrorCode.lean create mode 100644 lean/OrbCore/OrbCore/ErrorClass.lean create mode 100644 lean/OrbCore/OrbCore/FaultUpstream.lean create mode 100755 scripts/ops/orb-deploy-canary create mode 100644 shared/orb-spec/fixtures/error-classes.json diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..b11ec8439d --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,25 @@ +## What and why + + + +## How it was tested + + + +## Not verified live + + + +- [ ] + +## Platforms + +- [ ] Desktop +- [ ] iOS and Android at parity (or why not), version bumped +- [ ] Not user-visible diff --git a/AGENTS.md b/AGENTS.md index 3ea1e0f864..f678678c4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -500,7 +500,8 @@ settings between them and give missions a dev pass is Deploy with `/usr/local/sbin/orb-deploy [--detach] [--dev-only]` on `agent-core` (`scripts/ops/orb-deploy`): it builds that exact commit with the CI-parity Lean command (`orb-core`, `sandboxed-node`, `sandboxed-mcp`), runs both -`orb-core-test` and `orb-node-test`, installs and health-checks `dev`, stages +`orb-core-test` and `orb-node-test`, installs and health-checks `dev`, runs the dev +canaries (`scripts/ops/orb-deploy-canary`, [docs/operations/deploy-canaries.md](docs/operations/deploy-canaries.md)), stages the guest `sandboxed-node` release served by Core's `NodeRelease` endpoint, then promotes `prod` with a backup and automatic rollback; `--detach` runs it as a transient unit (`journalctl -u orb-deploy`, log `/var/log/orb-deploy.log`). diff --git a/docs/INFERENCE_PROTOCOLS.md b/docs/INFERENCE_PROTOCOLS.md index 73ae2ec358..fbc2657836 100644 --- a/docs/INFERENCE_PROTOCOLS.md +++ b/docs/INFERENCE_PROTOCOLS.md @@ -230,17 +230,20 @@ value bounds the whole reply, which would cut long generations. When a harness turn still fails, Core's one classifier (`OrbCore.RemoteDispatch.classifyTransientTurnFailureText?`, shared by -Core-hosted turns and remote node jobs for every harness) reads the harness's -error text. `stream_incomplete`, `idle_timeout`, `provider_unavailable` -(503/504/529, "overloaded", "no available channel", `server_unavailable`, -`model_cooldown`) and `harness_exited` (for example Pi ending before its final +Core-hosted turns and remote node jobs for every harness) reads the typed +error code in the harness's error text, never phrases +([specs/typed-errors.md](specs/typed-errors.md)): the `[orb:]` tag the +proxy adds to every error message whose body names a registered code, the +error JSON's code fields, or else the HTTP status (503/504/529 is +`provider_unavailable`). `stream_incomplete`, `idle_timeout`, +`provider_unavailable` (`server_unavailable`, `model_cooldown`, +`overloaded_error`) and `harness_exited` (Pi ending before its final `agent_end`) arm a durable retry continuation, at most twice per user -message, after 20 s and 40 s (`verifyTransientTurnRecovery`). Refusals that -name a configuration problem (`no_provider_for_model`, -`skipped_configuration`, `context_length_exceeded`, `client_or_auth_error`, -`out_of_credit`, …) are not retried. Every exhausted-chain body has the shape -`{"error":"","message":"…"}`, so an OpenAI-SDK client such as Pi -reports `" \"\""` and the code reaches the classifier. +message, after 20 s and 40 s (`verifyTransientTurnRecovery`). Registered +permanent codes (`no_provider_for_model`, `skipped_configuration`, +`context_length_exceeded`, `client_or_auth_error`, `out_of_credit`, +`no_cyber_access_account`, …) are not retried. The registry and its test +vectors are `shared/orb-spec/fixtures/error-classes.json`. ## Mid-stream contract (`/v1/chat/completions`, streaming) diff --git a/docs/operations/deploy-canaries.md b/docs/operations/deploy-canaries.md new file mode 100644 index 0000000000..f9f30e6bdd --- /dev/null +++ b/docs/operations/deploy-canaries.md @@ -0,0 +1,42 @@ +# Deploy canaries + +`orb-deploy` promotes prod only after `scripts/ops/orb-deploy-canary` passes on dev. The canary +exists because five bugs on 30 Nov 2026 passed CI and were found by using the app: a launch right +after a Core restart, VPN refusals for local harnesses, ghost missions from retried launches, a +503 that Pi did not recover from, and a Mythos request routed without a marked account. + +## What it checks + +1. **Restart, then launch at once.** Restarts `sandboxed-sh-dev` and launches the first mission + the moment `/api/health` answers, on the exact build being deployed. +2. **Harness × placement.** One mission per harness (Claude Code, Codex, OpenCode, Pi, + Antigravity) × placement (Core host; remote node `ORB_CANARY_NODE`, default `uruk`) on the + fault upstream (`docs/specs/fault-upstream.md`). Each must reach a real first turn: an + assistant message with the fault upstream's text. Antigravity runs on its own Google login, + so it only has to end cleanly (a turn, or a refusal with an error code and no mission). +3. **503 recovery.** A Pi mission on `fault-503x1` must answer after its first call got 503 + (typed errors: `docs/specs/typed-errors.md`). +4. **Proxy probes.** A cut stream reaches the client with `[orb:stream_incomplete]`; a late 429 + is a 429; a stalled first byte still answers; a 503 is a 503. +5. **Mythos.** `claude-mythos-*` with no CVP-marked account is `403 no_cyber_access_account` + (dev must have no marked account). +6. **No ghost missions.** Every create is retried with the same `idempotency_key` and must + coalesce; the only canary-titled missions are the ones the canary created. + +Not covered: the client/locald placement (needs a desktop `orb-locald`); list it under +"Not verified live" in the PR when a change touches it. + +## Running + +```bash +/var/tmp/orbcore-lean-build/scripts/ops/orb-deploy-canary --plan # what it would run +/var/tmp/orbcore-lean-build/scripts/ops/orb-deploy-canary --no-restart # against dev as it is +``` + +`orb-deploy` runs it with `--sha --report`. The report (PASS/FAIL per check) goes +to the Orb monitor (`orb-monitor --report`: Paloma and the "Orb monitor" Inbox mission) whether it +passed or not. Canary missions are deleted after a pass and kept on dev after a failure, titled +`[canary ]`. + +`ORB_DEPLOY_CANARY=warn orb-deploy …` promotes despite a failure; `=skip` does not run them. Use +either only with a reason in the deploy note. diff --git a/docs/specs/fault-upstream.md b/docs/specs/fault-upstream.md new file mode 100644 index 0000000000..b5d488c3d7 --- /dev/null +++ b/docs/specs/fault-upstream.md @@ -0,0 +1,39 @@ +# Fault-injection upstream + +A fake inference provider inside Core that fails on purpose, for dev canaries and tests. Code: +`lean/OrbCore/OrbCore/FaultUpstream.lean` (behaviour) and `Control.handleFaultUpstream?` (route). + +## Enabling + +Served under `/__fault/v1/*` only when `ORB_FAULT_UPSTREAM_KEY` is set, and only to a caller that +presents that key (`Authorization: Bearer` or `x-api-key`). Without the key the path is an unknown +route. `orb-deploy` sets it for `sandboxed-sh-dev` only, from `/etc/orb/fault-upstream.env` +(created once, mode 0600); prod never has it. + +Register it as a custom provider: + +```json +{"id": "prov-orb-fault", "provider_type": "custom", "name": "orbfault", + "base_url": "http://127.0.0.1:3002/__fault/v1", "api_key": "", + "custom_models": [{"id": "fault-ok"}, {"id": "fault-503x1"}]} +``` + +and address models as `orbfault/`. + +## Protocols + +OpenAI Chat Completions (`/chat/completions`), OpenAI Responses (`/responses`, Codex) and +Anthropic Messages (`/messages`, Claude Code), streamed or not; `GET /models` lists the models. + +## Models + +| Model | Behaviour | +| --- | --- | +| `fault-ok` | a short normal reply, text `Orb fault upstream: ok.` | +| `fault-503` | `503` with a new-api style body and no Orb code, every call | +| `fault-503x` | `503` for the first `n` calls of that model since Core started, then `fault-ok` | +| `fault-cut` | a streamed reply cut after its first text: no finish, no terminating chunk | +| `fault-stall-` | nothing for `` (max 600000), then `fault-ok` | +| `fault-late429-` | nothing for ``, then `429` with `Retry-After: 30` | + +Tests: `ProxyRoutingTests.faultUpstreamFixture`. Live use: `docs/operations/deploy-canaries.md`. diff --git a/docs/specs/typed-errors.md b/docs/specs/typed-errors.md new file mode 100644 index 0000000000..d64de798ba --- /dev/null +++ b/docs/specs/typed-errors.md @@ -0,0 +1,50 @@ +# Typed errors: transient or permanent + +**Rule.** Whether a failed turn is retried is decided by a typed error code, never by matching +phrases in the error text. One registry, one parser, one fixture: + +| Piece | Where | +| --- | --- | +| Registry (code → transient reason or permanent) | `lean/Orb/ErrorCode.lean` | +| Parser of a harness's error text, body tagger | `lean/OrbCore/OrbCore/ErrorClass.lean` | +| Turn settlement (retry or fail) | `RemoteDispatch.classifyTransientTurnFailureText?` → `settleTransientTurnFailure` | +| Shared test vectors (registry, texts, tagged bodies) | `shared/orb-spec/fixtures/error-classes.json`, replayed by `orb-spec-runner --fixtures` | + +## Why a tag + +Every harness reports a provider failure to its driver as text: the OpenAI SDK (Pi, OpenCode) as +`" "`, or `" "` when `error` is a string; Claude +Code as `API Error: `; an SSE error frame by its message alone. A code in a JSON +field is lost when the SDK prints only the message. So the code also rides in the message as +`[orb:]`: + +- **Proxy responses.** Every `/v1/*` error response from Core whose body names a registered code + (`error.code`, `error.type` or `error` as a string) gets `[orb:]` appended to + `error.message` (`Control.lean`, around `handleProxyRequest`). Upstream bodies with unknown + codes are left alone. +- **Stream cuts.** `streamCutErrorFrame` tags `stream_incomplete` / `upstream_idle_timeout`. +- **Harness drivers.** The Pi driver's "ended before `agent_end`" error carries + `[orb:harness_exited]` (`Orb.Kernel.piRpcEndedBeforeAgentEnd`). + +## Classification + +`ErrorClass.classifyText?` reads, in order: `[orb:]` tags; the error JSON's code fields +(`error.code`, `error` string, `error.type`, top-level `code`, a bare JSON string); and the HTTP +status at the head of the text (bare, or after `API Error:` / `unexpected status`). The first +registered code decides. With no registered code, status 503, 504 or 529 means +`provider_unavailable` (a new-api gateway's "No available channel", Anthropic overloaded). +Anything else is not transient. + +A phrase is never a code: "overloaded" or "no available channel" in prose with no status means +nothing. A number in prose is not a status. + +## Adding a code + +Add it to `Orb.ErrorCode.registry` and to `codes` in `error-classes.json` (the runner fails when +they differ), with a `text_cases` vector. A refusal that retrying cannot fix is `permanent`. + +## History + +Replaces the substring classifier from #1880/#2358, which matched `stream_incomplete`, +`overloaded`, `no available channel` and similar phrases anywhere in the text (Pi on Infistar, +30 Nov 2026). diff --git a/lean/Orb/ErrorCode.lean b/lean/Orb/ErrorCode.lean new file mode 100644 index 0000000000..d83513327b --- /dev/null +++ b/lean/Orb/ErrorCode.lean @@ -0,0 +1,80 @@ +/- + Orb.ErrorCode: the one registry of error codes that decide whether a failed turn is transient + (retry it) or permanent (stop and tell the user). Pure (`0 import Lean`), shared by Core's + proxy, Core's turn settlement and the node's harness drivers; the table is mirrored, with test + vectors, in `shared/orb-spec/fixtures/error-classes.json`. Spec: `docs/specs/typed-errors.md`. + + A code travels from where the failure is known (the proxy, a harness driver) to where it is + classified (turn settlement) inside the harness's own error text, as the tag `[orb:]`, + because every harness reports a provider error to its driver as text. Classification reads the + tag, the error JSON's code fields, or the HTTP status: never free-text phrases. +-/ + +namespace Orb.ErrorCode + +/-- Why a turn failure is worth retrying. Codes match `TransientTurnFailureReason`. -/ +inductive Transient where + | streamIncomplete + | idleTimeout + | providerUnavailable + | harnessExited + deriving Repr, DecidableEq, BEq + +/-- What one error code means for the turn that hit it. -/ +inductive ErrorClass where + | transient (reason : Transient) + | permanent + deriving Repr, DecidableEq, BEq + +def Transient.reasonString : Transient → String + | .streamIncomplete => "stream_incomplete" + | .idleTimeout => "idle_timeout" + | .providerUnavailable => "provider_unavailable" + | .harnessExited => "harness_exited" + +/-- The tag that carries `code` inside a harness's error text. -/ +def tag (code : String) : String := s!"[orb:{code}]" + +/-- Every code with a decided class. A code not listed here is unknown and falls back to the + HTTP status (`transientStatus?`). Keep in step with `error-classes.json`. -/ +def registry : Array (String × ErrorClass) := #[ + -- Transient: the same request can succeed on retry. + ("stream_incomplete", .transient .streamIncomplete), + ("upstream_idle_timeout", .transient .idleTimeout), + ("idle_timeout", .transient .idleTimeout), + ("server_unavailable", .transient .providerUnavailable), + ("provider_unavailable", .transient .providerUnavailable), + ("model_cooldown", .transient .providerUnavailable), + ("overloaded_error", .transient .providerUnavailable), + ("harness_exited", .transient .harnessExited), + -- Permanent: configuration, access or quota; retrying cannot help. + ("no_provider_for_model", .permanent), + ("skipped_configuration", .permanent), + ("model_not_found", .permanent), + ("no_user_enabled_providers", .permanent), + ("no_cyber_access_account", .permanent), + ("only_reserved_accounts", .permanent), + ("context_length_exceeded", .permanent), + ("out_of_credit", .permanent), + ("client_or_auth_error", .permanent), + ("transport_validation", .permanent), + ("usage_limit_reached", .permanent), + ("insufficient_quota", .permanent), + ("rate_limited_or_quota", .permanent), + ("cyber_access_store_unavailable", .permanent)] + +def classOf? (code : String) : Option ErrorClass := + (registry.find? (·.1 == code)).map (·.2) + +/-- HTTP statuses that mean "the provider could not serve right now" when no code says more: + 503 (e.g. new-api gateways' "No available channel"), 504, and 529 (Anthropic overloaded). -/ +def transientStatus? (status : Nat) : Option Transient := + if status == 503 || status == 504 || status == 529 then some .providerUnavailable else none + +/-- Classify from the parts of a harness error: a known code decides; otherwise the status. -/ +def classify (status? : Option Nat) (codes : List String) : Option ErrorClass := + match codes.findSome? classOf? with + | some c => some c + | none => (status?.bind transientStatus?).map .transient + +end Orb.ErrorCode diff --git a/lean/Orb/PiHarness.lean b/lean/Orb/PiHarness.lean index 1d7d1fea7c..3e4135d5a9 100644 --- a/lean/Orb/PiHarness.lean +++ b/lean/Orb/PiHarness.lean @@ -4,6 +4,8 @@ scalar kernel (`Orb.Kernel` / `shared/orb-spec/kernel_abi.json`) remains bit-exact untouched. -/ +import Orb.ErrorCode + namespace Orb.Kernel /-! ## Pi Harness RPC Session State Machine & MCP Policy Gate (`#2258`) -/ @@ -62,9 +64,10 @@ def piRpcIsFenced (s : PiRpcSession) : Bool := | _ => false /-- Error the `sandboxed-node pi-rpc` driver reports when Pi's stdout closes before the turn's - final `agent_end`. Core's transient-failure classifier matches this exact text - (`harness_exited`), so both sides share the one definition. -/ -def piRpcEndedBeforeAgentEnd : String := "Pi RPC process ended before agent_end" + final `agent_end`. It carries the typed code `harness_exited` (`Orb.ErrorCode`), which Core's + turn settlement reads to retry the turn. -/ +def piRpcEndedBeforeAgentEnd : String := + s!"Pi RPC process ended before agent_end {Orb.ErrorCode.tag "harness_exited"}" /-- True iff an outcome emits assistant text or tool events downstream. -/ def piRpcOutcomeEmitsOutput : PiRpcOutcome → Bool diff --git a/lean/OrbCore/OrbCore.lean b/lean/OrbCore/OrbCore.lean index 94bc7a3435..f8f5877dc8 100644 --- a/lean/OrbCore/OrbCore.lean +++ b/lean/OrbCore/OrbCore.lean @@ -16,6 +16,8 @@ import OrbCore.Store import OrbCore.Search import OrbCore.Harness import OrbCore.Proxy +import OrbCore.ErrorClass +import OrbCore.FaultUpstream import OrbCore.Cyber import OrbCore.Skills import OrbCore.AuthSidecar diff --git a/lean/OrbCore/OrbCore/ConformanceRunner.lean b/lean/OrbCore/OrbCore/ConformanceRunner.lean index c030a42df6..8eb1bd1680 100644 --- a/lean/OrbCore/OrbCore/ConformanceRunner.lean +++ b/lean/OrbCore/OrbCore/ConformanceRunner.lean @@ -5,6 +5,7 @@ import Orb.Kernel import LeanSys.Spec import OrbBin.Json +import OrbCore.ErrorClass namespace OrbCore.ConformanceRunner @@ -727,6 +728,38 @@ private def evalUsageLimitLabel (usage : JVal) (nowSec : UInt64) : Option (Strin label := label ++ s!" · resets in {resetVal}{unitStr}" return some (tone, label) +/-- `"transient:"`, `"permanent"` or `"none"`: an error class as `error-classes.json` writes it. -/ +private def errorClassLabel : Option Orb.ErrorCode.ErrorClass → String + | some (.transient r) => s!"transient:{r.reasonString}" + | some .permanent => "permanent" + | none => "none" + +/-- Replay `error-classes.json` (`docs/specs/typed-errors.md`): the registry matches the fixture + both ways, every text case classifies as written, and error bodies are tagged as written. -/ +def errorClassFixture (doc : JVal) : IO UInt32 := do + let codes := (doc.fieldOrNull "codes").asObj?.getD #[] + for (code, v) in codes do + let got := errorClassLabel (Orb.ErrorCode.classOf? code) + if some got != v.asStr? then + IO.eprintln s!"[orb-spec-runner] FAIL: error code {code}: registry {got}, fixture {v.asStr?}" + return 1 + for (code, _) in Orb.ErrorCode.registry do + if !(codes.any (·.1 == code)) then + IO.eprintln s!"[orb-spec-runner] FAIL: registry code {code} missing from error-classes.json" + return 1 + for c in (doc.fieldArr? "text_cases").getD #[] do + let got := errorClassLabel (OrbCore.ErrorClass.classifyText? ((c.fieldStr? "text").getD "")) + if some got != c.fieldStr? "expected" then + IO.eprintln s!"[orb-spec-runner] FAIL: error text case {(c.fieldStr? "name").getD ""}: got {got}" + return 1 + for c in (doc.fieldArr? "tag_body_cases").getD #[] do + let tagged? := OrbCore.ErrorClass.tagErrorBody? ((c.fieldStr? "body").getD "") + let msg? := tagged?.bind fun t => (parse t).toOption.bind fun v => (v.fieldOrNull "error").fieldStr? "message" + if msg? != c.fieldStr? "message" then + IO.eprintln s!"[orb-spec-runner] FAIL: error tag case {(c.fieldStr? "name").getD ""}: got {msg?}" + return 1 + return 0 + /-- Replay all `shared/orb-spec/fixtures/{projection-invariants,relative-time,usage-limit-status,r6a-client-kernel}.json` cases against `Orb.Kernel` exports (`--fixtures `). -/ def runSharedFixtures (fixturesDir : String) : IO UInt32 := do @@ -1043,7 +1076,11 @@ def runSharedFixtures (fixturesDir : String) : IO UInt32 := do IO.eprintln s!"[orb-spec-runner] FAIL: multiuser privd_exec mismatch {cname}" return 1 - IO.println "test result: ok. 5 passed; 0 failed; 0 ignored" + let ecRaw ← IO.FS.readFile s!"{fixturesDir}/error-classes.json" + let .ok ecDoc := parse ecRaw + | do IO.eprintln "[orb-spec-runner] FAIL: parse error-classes.json"; return 1 + if (← errorClassFixture ecDoc) != 0 then return 1 + IO.println "test result: ok. 6 passed; 0 failed; 0 ignored" return 0 /-- Execute a `cases.txt` batch (`id:symbol:arg0,arg1,...`) and print `id:value`. -/ diff --git a/lean/OrbCore/OrbCore/Control.lean b/lean/OrbCore/OrbCore/Control.lean index 105c903a05..ce4b615b42 100644 --- a/lean/OrbCore/OrbCore/Control.lean +++ b/lean/OrbCore/OrbCore/Control.lean @@ -41,6 +41,8 @@ import OrbCore.AccountVpnRelay import OrbCore.NativeGoalApproval import OrbCore.AutoPlacement import OrbCore.RemoteDispatch +import OrbCore.ErrorClass +import OrbCore.FaultUpstream import OrbCore.MachineTransfer import OrbCore.ProjectFilesAndController import OrbCore.CloudHttpAndWorker @@ -4510,6 +4512,52 @@ private def handleLocalWakeupDiscard (st : CoreAppState) (caller : CallerPrincip | .error "continuation_not_found" => return mkJson 404 "{\"error\":\"continuation_not_found\"}" | .error e => return mkJson 409 s!"\{\"error\":{jsonEscape e}}" +/-- Calls served so far per fault model, so `fault-503x` fails only its first `n` calls. -/ +initialize faultUpstreamCalls : IO.Ref (Array (String × Nat)) ← IO.mkRef #[] + +/-- `/__fault/v1/*` (`OrbCore.FaultUpstream`, `docs/specs/fault-upstream.md`): served only when + `ORB_FAULT_UPSTREAM_KEY` is set (dev and tests, never prod) and the caller presents that key. + `none` when the fault upstream is off, so the path is an ordinary unknown route. -/ +def handleFaultUpstream? (key : String) (req : HttpRequest) (cleanPath : String) : IO (Option CoreHttpResponse) := do + if key.isEmpty || !cleanPath.startsWith "/__fault/v1/" then return none + let bearer := ((lookupHeaderCI req.headers "authorization").getD "").trimAscii.toString + let presented := + if bearer.startsWith "Bearer " then (bearer.drop 7).toString.trimAscii.toString + else ((lookupHeaderCI req.headers "x-api-key").getD "").trimAscii.toString + if !ctEqSlice (ByteSlice.ofString presented) (ByteSlice.ofString key) then + return some (jsonResponse 401 "{\"error\":{\"message\":\"fault upstream: wrong key\",\"type\":\"authentication_error\"}}") + if req.method == "GET" && cleanPath.endsWith "/models" then + return some (jsonResponse 200 OrbCore.FaultUpstream.modelsBody) + let body := (String.fromUTF8? req.bodySlice.toByteArray).getD "" + let model := OrbCore.FaultUpstream.bareModel ((((OrbBin.Json.parse body).toOption.getD .null).fieldStr? "model").getD "") + let callIndex ← faultUpstreamCalls.modifyGet fun calls => + let n := ((calls.find? (·.1 == model)).map (·.2)).getD 0 + (n, (calls.filter (·.1 != model)).push (model, n + 1)) + let r := OrbCore.FaultUpstream.reply cleanPath body callIndex + if r.delayMs > 0 then IO.sleep r.delayMs.toUInt32 + if !r.streamed then + return some { status := r.status, contentType := r.contentType, extraHdrs := r.headers, + body := (String.join r.pieces.toList).toUTF8 } + return some { status := r.status, contentType := r.contentType, extraHdrs := r.headers, body := ByteArray.empty, + bodyStream? := some fun emit => do + for piece in r.pieces do + if !(← emit piece.toUTF8) then return false + IO.sleep 50 + return r.complete } + +/-- `handleFaultUpstream?` with the key from `ORB_FAULT_UPSTREAM_KEY`. -/ +def faultUpstreamRoute? (req : HttpRequest) (cleanPath : String) : IO (Option CoreHttpResponse) := do + if !cleanPath.startsWith "/__fault/" then return none + handleFaultUpstream? ((← IO.getEnv "ORB_FAULT_UPSTREAM_KEY").getD "").trimAscii.toString req cleanPath + +/-- Typed errors (`docs/specs/typed-errors.md`): a proxy error body's registered code also rides in + `error.message` as `[orb:]`, since harnesses report a provider error by its message. -/ +def tagProxyErrorResponse (resp : CoreHttpResponse) : CoreHttpResponse := + if resp.status < 400 || resp.bodyStream?.isSome then resp + else match (String.fromUTF8? resp.body).bind OrbCore.ErrorClass.tagErrorBody? with + | some tagged => { resp with body := tagged.toUTF8 } + | none => resp + set_option maxHeartbeats 1600000 in private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowEpochSec : UInt64) : IO (Except ByteArray CoreHttpResponse) := do let legacyManagedPrefix := "/api/managed/machines" @@ -4796,11 +4844,15 @@ private def dispatchCoreRequestRaw (st : CoreAppState) (req : HttpRequest) (nowE | some raw101 => return .error raw101 | none => return .ok (mkJson 400 "{\"error\":\"invalid_websocket_upgrade\"}") + -- Fault-injection upstream for dev canaries and tests (off unless `ORB_FAULT_UPSTREAM_KEY` is set). + if let some faultResp ← faultUpstreamRoute? req cleanPath then + return .ok faultResp + -- 4. Authenticated `/v1/*` LLM Proxy (`mission_proxy_token`, `SANDBOXED_PROXY_SECRET`, or Core Bearer Auth, `SM-21`) if cleanPath.startsWith "/v1/" then if !(← authenticateProxyRequest st req.headers nowEpochSec) then return .ok (mkJson 401 "{\"error\":\"unauthorized_proxy\"}") - return .ok (← handleProxyRequest st req cleanPath reqOrigin? nowEpochSec) + return .ok (tagProxyErrorResponse (← handleProxyRequest st req cleanPath reqOrigin? nowEpochSec)) -- 5. Privilege Broker Verification & Audit Log (`POST /api/privilege-access/verify-and-log`) if req.method == "POST" && cleanPath == "/api/privilege-access/verify-and-log" then diff --git a/lean/OrbCore/OrbCore/ErrorClass.lean b/lean/OrbCore/OrbCore/ErrorClass.lean new file mode 100644 index 0000000000..1cff589b91 --- /dev/null +++ b/lean/OrbCore/OrbCore/ErrorClass.lean @@ -0,0 +1,88 @@ +/- + OrbCore.ErrorClass: read the typed error code out of a harness's error text, and put it there. + The registry itself is `Orb.ErrorCode`; the spec is `docs/specs/typed-errors.md`; the shared + test vectors are `shared/orb-spec/fixtures/error-classes.json`. +-/ +import Orb.ErrorCode +import OrbBin.Json + +namespace OrbCore.ErrorClass + +open OrbBin.Json +open Orb.ErrorCode + +/-- Codes carried by `[orb:]` tags, in order of appearance. -/ +def taggedCodes (raw : String) : List String := + match raw.splitOn "[orb:" with + | _ :: rest => rest.filterMap fun seg => + match seg.splitOn "]" with + | code :: _ :: _ => if code.isEmpty || code.any Char.isWhitespace then none else some code + | _ => none + | [] => [] + +/-- The code fields of a provider or Orb error body, most specific first: + `{"error":{"code","type"}}` (OpenAI / Anthropic / new-api), `{"error":""}` (Orb's own + exhaustion bodies), a top-level `code` (Orb mission error events), or a bare JSON string. -/ +def jsonCodes (v : JVal) : List String := + let err := v.fieldOrNull "error" + ([err.fieldStr? "code", err.asStr?, err.fieldStr? "type", v.fieldStr? "code", v.asStr?].filterMap id).filter + (!·.isEmpty) + +/-- Words a harness may print before the HTTP status (`API Error: 503 …`, `unexpected status 503 …`). -/ +private def statusLead : List String := ["api", "error", "error:", "unexpected", "status", "http"] + +/-- The HTTP status at the head of a harness error (`" "`, the OpenAI SDK format, or + after one of `statusLead`), and the text after it. -/ +def statusSplit (raw : String) : Option Nat × String := + let toks := (raw.trimAscii.toString.splitOn " ").filter (!·.isEmpty) + let rec go (seen : List String) : List String → Option Nat × String + | [] => (none, raw) + | t :: rest => + let t' := if t.endsWith ":" then (t.dropEnd 1).toString else t + if t'.length == 3 && t'.all Char.isDigit then + match t'.toNat? with + | some n => if 400 ≤ n && n ≤ 599 then (some n, " ".intercalate rest) else (none, raw) + | none => (none, raw) + else if statusLead.contains t.toLower && seen.length < 3 then go (t :: seen) rest + else (none, raw) + go [] toks + +/-- The JSON value in a harness error: the outermost `{…}` object, else (after a status) a bare + JSON string such as `"server_unavailable"`. -/ +def jsonPart? (raw afterStatus : String) : Option JVal := + match raw.splitOn "{" with + | _ :: rest@(_ :: _) => + let fromBrace := "{" ++ "{".intercalate rest + let upToLast := "}".intercalate (fromBrace.splitOn "}").dropLast ++ "}" + (parse upToLast).toOption + | _ => + let t := afterStatus.trimAscii.toString + if t.startsWith "\"" then (parse t).toOption else none + +/-- The class of a harness's error text, or `none` when it carries no code or status we know. -/ +def classifyText? (raw : String) : Option ErrorClass := + if raw.trimAscii.toString.isEmpty then none + else + let (status?, rest) := statusSplit raw + let codes := taggedCodes raw ++ ((jsonPart? raw rest).map jsonCodes).getD [] + classify status? codes + +/-- `error.message` of an error body with `[orb:]` appended, for a body whose code is in the + registry, so a harness that prints only the message (OpenAI SDK, Anthropic SDK) keeps the code. + `none` leaves the body as it is: not JSON, no registered code, no message string, or already tagged. -/ +def tagErrorBody? (body : String) : Option String := + match (parse body).toOption with + | some v@(.obj kvs) => + match (jsonCodes v).find? (fun c => (classOf? c).isSome), v.fieldOrNull "error" with + | some code, err@(.obj ekvs) => + match err.fieldStr? "message" with + | some msg => + if (msg.splitOn "[orb:").length > 1 then none + else + let ekvs' := ekvs.map fun (k, x) => if k == "message" then (k, .str s!"{msg} {tag code}") else (k, x) + some (renderCompact (.obj (kvs.map fun (k, x) => if k == "error" then (k, .obj ekvs') else (k, x)))) + | none => none + | _, _ => none + | _ => none + +end OrbCore.ErrorClass diff --git a/lean/OrbCore/OrbCore/FaultUpstream.lean b/lean/OrbCore/OrbCore/FaultUpstream.lean new file mode 100644 index 0000000000..c871164ba0 --- /dev/null +++ b/lean/OrbCore/OrbCore/FaultUpstream.lean @@ -0,0 +1,197 @@ +/- + OrbCore.FaultUpstream: a fake inference provider that fails on purpose, for dev and tests only. + + Core serves it under `/__fault/v1/*` only when `ORB_FAULT_UPSTREAM_KEY` is set (never on prod), + and only to a caller presenting that key as its Bearer token: register it as a custom provider + with base URL `http://127.0.0.1:/__fault/v1` and that key. It speaks OpenAI Chat + Completions, OpenAI Responses and Anthropic Messages, streamed or not. The model id chooses the + behaviour (`docs/specs/fault-upstream.md`): + + - `fault-ok` a normal short reply + - `fault-503` `503` with a new-api style body (no Orb code), every call + - `fault-503x` `503` for the first `n` calls of that model, then a normal reply + - `fault-cut` a streamed reply cut after its first text, without a finish + - `fault-stall-` nothing for `` (≤ 600000) before a normal reply + - `fault-late429-` nothing for ``, then `429` with `Retry-After` + + Any `/` prefix on the model id is ignored. +-/ +import OrbBin.Json + +namespace OrbCore.FaultUpstream + +open OrbBin.Json + +inductive Mode where + | ok + | fail503 (firstCalls : Option Nat) + | cut + | stall (ms : Nat) + | late429 (ms : Nat) + deriving Repr, DecidableEq, BEq + +inductive Protocol where + | chat + | messages + | responses + deriving Repr, DecidableEq, BEq + +/-- What Core sends back: wait `delayMs`, then the head, then `pieces` (one chunk each when + `streamed`, else joined as the body). `complete = false` ends the connection without the + stream's terminating chunk, as a cut upstream would. -/ +structure Reply where + status : Nat + contentType : String := "application/json" + headers : Array (String × String) := #[] + delayMs : Nat := 0 + streamed : Bool := false + pieces : Array String := #[] + complete : Bool := true + deriving Repr + +def maxDelayMs : Nat := 600000 + +def replyText : String := "Orb fault upstream: ok." + +/-- The model id without any `/` prefix. -/ +def bareModel (model : String) : String := + ((model.splitOn "/").getLast?).getD model + +def parseMode? (model : String) : Option Mode := + match (bareModel model).splitOn "-" with + | ["fault", "ok"] => some .ok + | ["fault", "503"] => some (.fail503 none) + | ["fault", "cut"] => some .cut + | ["fault", "stall", ms] => ms.toNat?.map fun n => Mode.stall (min n maxDelayMs) + | ["fault", "late429", ms] => ms.toNat?.map fun n => Mode.late429 (min n maxDelayMs) + | ["fault", m] => + if m.startsWith "503x" then ((m.drop 4).toString.toNat?).map fun n => Mode.fail503 (some n) else none + | _ => none + +def protocol? (path : String) : Option Protocol := + if path.endsWith "/chat/completions" then some .chat + else if path.endsWith "/messages" then some .messages + else if path.endsWith "/responses" then some .responses + else none + +private def sse (event? : Option String) (data : JVal) : String := + (match event? with | some e => s!"event: {e}\n" | none => "") ++ s!"data: {renderCompact data}\n\n" + +private def ssev (event : String) (data : JVal) : String := sse (some event) data + +private def usageChat : JVal := + .obj #[("prompt_tokens", .nat 1), ("completion_tokens", .nat 4), ("total_tokens", .nat 5)] + +private def chatChunk (model : String) (delta : JVal) (finish : JVal) (usage? : Option JVal := none) : JVal := + .obj (#[("id", .str "chatcmpl-fault"), ("object", .str "chat.completion.chunk"), ("created", .nat 0), + ("model", .str model), + ("choices", .arr #[.obj #[("index", .nat 0), ("delta", delta), ("finish_reason", finish)]])] ++ + (match usage? with | some u => #[("usage", u)] | none => #[])) + +private def anthropicMessage (model : String) (content : Array JVal) (stop : JVal) : JVal := + .obj #[("id", .str "msg_fault"), ("type", .str "message"), ("role", .str "assistant"), ("model", .str model), + ("content", .arr content), ("stop_reason", stop), ("stop_sequence", .null), + ("usage", .obj #[("input_tokens", .nat 1), ("output_tokens", .nat 4)])] + +private def textBlock (t : String) : JVal := .obj #[("type", .str "text"), ("text", .str t)] + +private def outputText (t : String) : JVal := + .obj #[("type", .str "output_text"), ("text", .str t), ("annotations", .arr #[])] + +private def responsesItem (status : String) (content : Array JVal) : JVal := + .obj #[("id", .str "msg_fault"), ("type", .str "message"), ("role", .str "assistant"), + ("status", .str status), ("content", .arr content)] + +private def responsesObj (model status : String) (output : Array JVal) : JVal := + .obj #[("id", .str "resp_fault"), ("object", .str "response"), ("status", .str status), ("model", .str model), + ("output", .arr output), + ("usage", .obj #[("input_tokens", .nat 1), ("output_tokens", .nat 4), ("total_tokens", .nat 5)])] + +/-- The opening frames of a streamed reply, through the first text. `fault-cut` stops here. -/ +def streamHead (p : Protocol) (model : String) : Array String := + let t := replyText + match p with + | .chat => #[sse none (chatChunk model (.obj #[("role", .str "assistant"), ("content", .str t)]) .null)] + | .messages => #[ + ssev "message_start" (.obj #[("type", .str "message_start"), ("message", anthropicMessage model #[] .null)]), + ssev "content_block_start" (.obj #[("type", .str "content_block_start"), ("index", .nat 0), ("content_block", textBlock "")]), + ssev "content_block_delta" (.obj #[("type", .str "content_block_delta"), ("index", .nat 0), + ("delta", .obj #[("type", .str "text_delta"), ("text", .str t)])])] + | .responses => #[ + ssev "response.created" (.obj #[("type", .str "response.created"), ("response", responsesObj model "in_progress" #[])]), + ssev "response.output_item.added" (.obj #[("type", .str "response.output_item.added"), ("output_index", .nat 0), + ("item", responsesItem "in_progress" #[])]), + ssev "response.content_part.added" (.obj #[("type", .str "response.content_part.added"), ("item_id", .str "msg_fault"), + ("output_index", .nat 0), ("content_index", .nat 0), ("part", outputText "")]), + ssev "response.output_text.delta" (.obj #[("type", .str "response.output_text.delta"), ("item_id", .str "msg_fault"), + ("output_index", .nat 0), ("content_index", .nat 0), ("delta", .str t)])] + +/-- The closing frames of a streamed reply. -/ +def streamTail (p : Protocol) (model : String) : Array String := + let t := replyText + match p with + | .chat => #[sse none (chatChunk model (.obj #[]) (.str "stop") (some usageChat)), "data: [DONE]\n\n"] + | .messages => #[ + ssev "content_block_stop" (.obj #[("type", .str "content_block_stop"), ("index", .nat 0)]), + ssev "message_delta" (.obj #[("type", .str "message_delta"), + ("delta", .obj #[("stop_reason", .str "end_turn"), ("stop_sequence", .null)]), + ("usage", .obj #[("output_tokens", .nat 4)])]), + ssev "message_stop" (.obj #[("type", .str "message_stop")])] + | .responses => + let done := responsesItem "completed" #[outputText t] + #[ssev "response.output_text.done" (.obj #[("type", .str "response.output_text.done"), ("item_id", .str "msg_fault"), + ("output_index", .nat 0), ("content_index", .nat 0), ("text", .str t)]), + ssev "response.content_part.done" (.obj #[("type", .str "response.content_part.done"), ("item_id", .str "msg_fault"), + ("output_index", .nat 0), ("content_index", .nat 0), ("part", outputText t)]), + ssev "response.output_item.done" (.obj #[("type", .str "response.output_item.done"), ("output_index", .nat 0), ("item", done)]), + ssev "response.completed" (.obj #[("type", .str "response.completed"), ("response", responsesObj model "completed" #[done])])] + +def completeBody (p : Protocol) (model : String) : String := + let t := replyText + renderCompact <| match p with + | .chat => .obj #[("id", .str "chatcmpl-fault"), ("object", .str "chat.completion"), ("created", .nat 0), ("model", .str model), + ("choices", .arr #[.obj #[("index", .nat 0), ("message", .obj #[("role", .str "assistant"), ("content", .str t)]), + ("finish_reason", .str "stop")]]), ("usage", usageChat)] + | .messages => anthropicMessage model #[textBlock t] (.str "end_turn") + | .responses => responsesObj model "completed" #[responsesItem "completed" #[outputText t]] + +private def okReply (p : Protocol) (model : String) (stream : Bool) (delayMs : Nat := 0) : Reply := + if stream then + { status := 200, contentType := "text/event-stream", delayMs, streamed := true, + pieces := streamHead p model ++ streamTail p model } + else { status := 200, delayMs, pieces := #[completeBody p model] } + +/-- A new-api / one-api style outage: no Orb code, so only the status says "transient". -/ +def unavailableBody : String := + renderCompact (.obj #[("error", .obj #[("message", .str "Orb fault upstream: injected 503 (no available channel)"), + ("type", .str "fault_injected"), ("code", .str "")])]) + +def rateLimitBody : String := + renderCompact (.obj #[("error", .obj #[("message", .str "Orb fault upstream: injected rate limit"), + ("type", .str "rate_limit_error"), ("code", .str "rate_limit_exceeded")])]) + +/-- The reply to one request. `callIndex` counts earlier calls for the same model (from 0). -/ +def reply (path : String) (body : String) (callIndex : Nat) : Reply := + let req := (parse body).toOption.getD .null + let model := (req.fieldStr? "model").getD "" + let stream := (req.fieldBool? "stream").getD false + match protocol? path, parseMode? model with + | none, _ => { status := 404, pieces := #["{\"error\":{\"message\":\"unknown fault upstream path\",\"type\":\"not_found\"}}"] } + | _, none => { status := 404, pieces := #[renderCompact (.obj #[("error", .obj #[ + ("message", .str s!"unknown fault model '{model}'"), ("type", .str "invalid_request_error"), ("code", .str "model_not_found")])])] } + | some p, some mode => + match mode with + | .ok => okReply p model stream + | .fail503 none => { status := 503, pieces := #[unavailableBody] } + | .fail503 (some n) => if callIndex < n then { status := 503, pieces := #[unavailableBody] } else okReply p model stream + | .cut => { status := 200, contentType := "text/event-stream", streamed := true, pieces := streamHead p model, complete := false } + | .stall ms => okReply p model stream ms + | .late429 ms => { status := 429, delayMs := ms, headers := #[("Retry-After", "30")], pieces := #[rateLimitBody] } + +/-- `GET /__fault/v1/models`: the fault models, for harnesses that list models first. -/ +def modelsBody : String := + renderCompact (.obj #[("object", .str "list"), ("data", .arr (#["fault-ok", "fault-503", "fault-503x1", "fault-cut", + "fault-stall-5000", "fault-late429-5000"].map fun id => + JVal.obj #[("id", .str id), ("object", .str "model"), ("owned_by", .str "orb-fault")]))]) + +end OrbCore.FaultUpstream diff --git a/lean/OrbCore/OrbCore/Proxy.lean b/lean/OrbCore/OrbCore/Proxy.lean index e38f98dcde..3140867911 100644 --- a/lean/OrbCore/OrbCore/Proxy.lean +++ b/lean/OrbCore/OrbCore/Proxy.lean @@ -12,6 +12,7 @@ import LeanSys.Posix import Orb.Kernel import Orb.HarnessCloud import Orb.HarnessCloudSpec +import Orb.ErrorCode import OrbBin.Json import OrbBin.ClaudeControl import OrbCore.Spec @@ -2739,6 +2740,9 @@ def streamCutErrorFrame (timedOut : Bool) : String := ("upstream_idle_timeout", "upstream_idle_timeout: the upstream provider stopped sending data before the reply finished") else ("stream_incomplete", "stream_incomplete: upstream stream ended without a finish_reason") + -- The tag carries the code to Core's turn settlement: clients report a stream error frame by + -- its message alone (`docs/specs/typed-errors.md`). + let message := s!"{message} {Orb.ErrorCode.tag code}" s!"data: \{\"error\":\{\"message\":{jsonEscape message},\"type\":\"upstream_error\",\"code\":{jsonEscape code}}}\n\n" /-- Tail sent to the client when a streamed reply ends without recovery (`stream_incomplete` or diff --git a/lean/OrbCore/OrbCore/ProxyRoutingTests.lean b/lean/OrbCore/OrbCore/ProxyRoutingTests.lean index 1c4a54dd5a..6055f54476 100644 --- a/lean/OrbCore/OrbCore/ProxyRoutingTests.lean +++ b/lean/OrbCore/OrbCore/ProxyRoutingTests.lean @@ -2081,7 +2081,9 @@ def infistarRecoveryFixture : IO Unit := do ("529 Overloaded", some .providerUnavailable), ("504 \"upstream_idle_timeout\"", some .idleTimeout), (Orb.Kernel.piRpcEndedBeforeAgentEnd, some .harnessExited), - ("503 No configured provider account can serve model 'x'. (no_provider_for_model)", none), + ("503 No configured provider account can serve model 'x'. [orb:no_provider_for_model]", none), + -- Phrases are not codes: only tags, JSON codes and the status count (`docs/specs/typed-errors.md`). + ("upstream said: overloaded, no available channel", none), ("503 \"skipped_configuration\"", none), ("502 \"client_or_auth_error\"", none), ("400 Prompt exceeds context window (context_length_exceeded)", none), @@ -2105,7 +2107,7 @@ def infistarRecoveryFixture : IO Unit := do let vExit ← OrbCore.RemoteDispatch.settleTransientTurnFailure store none "m-inf-exit" nowIso nowSec (some Orb.Kernel.piRpcEndedBeforeAgentEnd) let vCfg ← OrbCore.RemoteDispatch.settleTransientTurnFailure store none "m-inf-cfg" nowIso nowSec - (some "503 No configured provider account can serve model 'infistar/x' (no_provider_for_model)") + (some "503 No configured provider account can serve model 'infistar/x' [orb:no_provider_for_model]") check (v503 == some ("awaiting_user", "transient_turn_retry") && vExit == some ("awaiting_user", "transient_turn_retry") && vCfg.isNone) s!"Infistar 503 and a Pi exit before agent_end arm a retry; a configuration refusal does not: {v503} {vExit} {vCfg}" @@ -2162,9 +2164,62 @@ private def infistarDirectRouting (store : CoreStore) (chainsRef : IO.Ref (Array s!"without a chain, Infistar's own 503 reaches Pi and is a transient failure: {soloResp.status} {soloMsg}" discard <| execParamQuery store.missionsDb "DELETE FROM ai_providers WHERE id='prov-infistar';" #[] +/-- The fault upstream (`docs/specs/fault-upstream.md`): off without a key, refuses a wrong key, + and each model id behaves as documented on every protocol. -/ +def faultUpstreamFixture : IO Unit := do + let key := "fault-fixture-key" + let mkReq : String → String → Bool → String → IO LeanSys.Http.HttpRequest := fun path model stream auth => do + let body := renderCompact (.obj #[("model", .str model), ("stream", .bool stream), ("messages", .arr #[])]) + let raw := s!"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {auth}\r\nContent-Length: {body.utf8ByteSize}\r\n\r\n{body}" + let .ok req := parseRequest raw.toUTF8 none + | throw (IO.userError "fault fixture: request parse failed") + pure req + let drain : CoreHttpResponse → IO (String × Bool) := fun r => do + match r.bodyStream? with + | none => pure ((String.fromUTF8? r.body).getD "", true) + | some pump => + let acc ← IO.mkRef "" + let complete ← pump fun piece => do acc.modify (· ++ (String.fromUTF8? piece).getD ""); pure true + pure (← acc.get, complete) + let r0 ← mkReq "/__fault/v1/chat/completions" "fault-ok" false key + check ((← handleFaultUpstream? "" r0 "/__fault/v1/chat/completions").isNone) "fault upstream is off without a key" + let some wrong ← handleFaultUpstream? key (← mkReq "/__fault/v1/chat/completions" "fault-ok" false "nope") "/__fault/v1/chat/completions" + | throw (IO.userError "fault fixture: no reply") + check (wrong.status == 401) s!"fault upstream refuses a wrong key: {wrong.status}" + let serve : String → String → Bool → IO (Nat × String × Bool) := fun path model stream => do + let some r ← handleFaultUpstream? key (← mkReq path model stream key) path + | throw (IO.userError s!"fault fixture: no reply for {model}") + let (text, complete) ← drain r + pure (r.status, text, complete) + for (path, done) in #[("/__fault/v1/chat/completions", "[DONE]"), ("/__fault/v1/messages", "message_stop"), + ("/__fault/v1/responses", "response.completed")] do + let (st, text, complete) ← serve path "fault/fault-ok" true + check (st == 200 && complete && (text.splitOn OrbCore.FaultUpstream.replyText).length > 1 && (text.splitOn done).length > 1) + s!"fault-ok streams a finished reply on {path}: {st} {complete}" + let (cst, ctext, ccomplete) ← serve path "fault-cut" true + check (cst == 200 && !ccomplete && (ctext.splitOn done).length == 1) + s!"fault-cut ends {path} without a finish: {cst} {ccomplete}" + let (bst, btext, _) ← serve path "fault-ok" false + check (bst == 200 && (OrbBin.Json.parse btext).isOk) s!"fault-ok answers {path} unstreamed: {bst}" + let chat := "/__fault/v1/chat/completions" + let (s503, b503, _) ← serve chat "fault-503" false + check (s503 == 503 && OrbCore.ErrorClass.classifyText? s!"503 {b503}" == some (.transient .providerUnavailable)) + s!"fault-503 is a transient provider outage by status alone: {s503}" + let (a1, _, _) ← serve chat "fault-503x1" false + let (a2, _, _) ← serve chat "fault-503x1" false + check (a1 == 503 && a2 == 200) s!"fault-503x1 fails once, then answers: {a1} {a2}" + let t0 ← IO.monoMsNow + let (s429, _, _) ← serve chat "fault-late429-300" false + let (sStall, _, _) ← serve chat "fault-stall-300" false + check (s429 == 429 && sStall == 200 && (← IO.monoMsNow) - t0 ≥ 600) + s!"fault-late429 and fault-stall wait before answering: {s429} {sStall}" + let (sUnknown, _, _) ← serve chat "gpt-6" false + check (sUnknown == 404) s!"a non-fault model is refused: {sUnknown}" + /-- Actual request routing, including unknown errors and no default/name/suffix aliasing. -/ def run : IO Unit := do runStreaming + faultUpstreamFixture infistarRecoveryFixture runStreamingPumpContracts r26ProviderDisabledIsTerminal @@ -2307,6 +2362,12 @@ def run : IO Unit := do (((error.fieldStr? "message").getD "").splitOn model).length ≤ 1 || !(← attempts.get).isEmpty then failures := failures.push s!"{model}: expected named 400 before transport" + -- Typed errors: the code also rides in the message, so a harness that prints only the + -- message keeps it, and turn settlement calls it permanent. + let sdkMsg := s!"400 {(error.fieldStr? "message").getD ""}" + if !(((error.fieldStr? "message").getD "").endsWith "[orb:model_not_found]") || + OrbCore.ErrorClass.classifyText? sdkMsg != some .permanent then + failures := failures.push s!"{model}: proxy error message lacks its [orb:model_not_found] tag" -- Exercise every saved id and its compatibility spelling, not an allowlist -- containing only today's smart/reviewer incidents. for c in (← chainsRef.get) do diff --git a/lean/OrbCore/OrbCore/RemoteDispatch.lean b/lean/OrbCore/OrbCore/RemoteDispatch.lean index 2271d9aff2..bd7d7d9a2b 100644 --- a/lean/OrbCore/OrbCore/RemoteDispatch.lean +++ b/lean/OrbCore/OrbCore/RemoteDispatch.lean @@ -26,6 +26,7 @@ import OrbCore.RemoteFleetAndRelay import OrbCore.Skills import OrbCore.AutoPlacement import OrbCore.Proxy +import OrbCore.ErrorClass import OrbCore.TelemetryAndVoice import OrbCore.AccountVpnPool import OrbCore.AccountVpnRelay @@ -1778,40 +1779,19 @@ def settleEmptyTurn (store : CoreStore) (broadcastHub? : Option BroadcastHub) harness exit) before the mission is `failed`. -/ def maxTransientTurnRetries : Nat := 2 -/-- Provider refusals that name a configuration problem, not an outage: retrying cannot help. -/ -private def nonTransientProviderCodes : Array String := - #["no_provider_for_model", "skipped_configuration", "model_not_found", "no_user_enabled_providers", - "no_cyber_access_account", "context_length_exceeded", "out_of_credit", "client_or_auth_error", - "usage_limit_reached", "insufficient_quota"] - /-- The one classifier of transient turn failures, shared by every harness (Core-hosted turns in - `Control.lean` and remote node jobs). It reads the harness's own error text, which carries the - Orb proxy's error code: Pi and other OpenAI-SDK clients report a proxy refusal as - `" "` and a cut stream by the proxy's SSE error frame - message (`streamCutErrorFrame`). - - `stream_incomplete`: the stream ended without a finish. - - `idle_timeout`: the upstream stopped sending (`upstream_idle_timeout`). - - `provider_unavailable`: every reachable target answered 503/504/529, "overloaded" or - "no available channel" (new-api/one-api gateways such as Infistar) before any byte, unless - the refusal names a configuration problem (`nonTransientProviderCodes`). - - `harness_exited`: the harness process died before reporting the end of its turn. -/ + `Control.lean` and remote node jobs). It reads typed error codes, never phrases + (`docs/specs/typed-errors.md`, `OrbCore.ErrorClass.classifyText?`): the `[orb:]` tag the + proxy and the harness drivers put in the error text, the error JSON's code fields, or else the + HTTP status (503/504/529 is `provider_unavailable`). Registered permanent codes + (`no_provider_for_model`, `no_cyber_access_account`, …) are never retried. -/ def classifyTransientTurnFailureText? (raw : String) : Option TransientTurnFailureReason := - let low := raw.trimAscii.toString.toLower - let has := fun (k : String) => (low.splitOn k).length > 1 - if low.isEmpty then none - else if has "stream_incomplete" || has "upstream stream ended without a finish_reason" || has "[done]data:" then - some .streamIncomplete - else if has "idle_timeout" then - some .idleTimeout - else if nonTransientProviderCodes.any has then - none - else if has "no available channel" || has "overloaded" || has "server_unavailable" || - has "model_cooldown" || has "service unavailable" || - low.startsWith "503 " || low.startsWith "504 " || low.startsWith "529 " then - some .providerUnavailable - else if has Orb.Kernel.piRpcEndedBeforeAgentEnd.toLower then - some .harnessExited - else none + match OrbCore.ErrorClass.classifyText? raw with + | some (.transient .streamIncomplete) => some .streamIncomplete + | some (.transient .idleTimeout) => some .idleTimeout + | some (.transient .providerUnavailable) => some .providerUnavailable + | some (.transient .harnessExited) => some .harnessExited + | some .permanent | none => none /-- Encode `TransientTurnFailureReason` as its kernel gate reason code (`1..4`). -/ def transientTurnFailureReasonCode : TransientTurnFailureReason → UInt8 diff --git a/scripts/ops/orb-deploy b/scripts/ops/orb-deploy index 69aacbed87..1a840bf7d9 100755 --- a/scripts/ops/orb-deploy +++ b/scripts/ops/orb-deploy @@ -6,8 +6,8 @@ # (survives the SSH session; `journalctl -u orb-deploy`) # # Steps: fetch, check out exactly that commit, CI-parity build, Core self-test, -# install to dev and health-check, then prod with a backup and automatic -# rollback. A failed step stops the run and leaves prod untouched (or restored). +# install to dev and health-check, run the dev canaries (orb-deploy-canary), then +# prod with a backup and automatic rollback. A failed step stops the run and leaves prod untouched (or restored). # One run at a time; refuses to start while another Lean build is running. set -euo pipefail @@ -386,6 +386,14 @@ else install -m 755 "$BIN" /usr/local/bin/orb-core-dev.new mv /usr/local/bin/orb-core-dev.new /usr/local/bin/orb-core-dev fi +# Dev only: Core's fault-injection upstream (`docs/specs/fault-upstream.md`) for the canaries. +# Prod never gets this key, so `/__fault/*` does not exist there. +FAULT_ENV=/etc/orb/fault-upstream.env +if [[ ! -s "$FAULT_ENV" ]]; then + (umask 077; printf 'ORB_FAULT_UPSTREAM_KEY=%s\n' "$(head -c 32 /dev/urandom | sha256sum | cut -c1-48)" > "$FAULT_ENV") +fi +printf '%s\n' "[Service]" "EnvironmentFile=$FAULT_ENV" > /etc/systemd/system/sandboxed-sh-dev.service.d/32-fault-upstream.conf +systemctl daemon-reload if [[ $ROLLOUT_NODES == 1 ]]; then DEV_TOUCHED=1; fi systemctl restart sandboxed-sh-dev if ! healthy 3002 30 "$SHA"; then @@ -402,6 +410,24 @@ fi say "dev healthy on $SHA" [[ $DEV_ONLY == 1 ]] && { STAGE_COMMITTED=1; say "done (dev only)"; exit 0; } +# Canaries on dev before prod (`docs/operations/deploy-canaries.md`): restart dev and launch at +# once, one mission per harness and placement on the fault upstream, a 503 that must recover, +# Mythos refusal, no ghost missions. The result goes to the Orb monitor either way. +# ORB_DEPLOY_CANARY=warn promotes despite a failure; =skip does not run them. +CANARY_MODE="${ORB_DEPLOY_CANARY:-block}" +if [[ "$CANARY_MODE" != skip ]]; then + say "canaries on dev" + if ORB_CANARY_ENV_FILES="/etc/orb/environments/core.env:/etc/orb/environments/dev.env:$FAULT_ENV" \ + "$TREE/scripts/ops/orb-deploy-canary" --sha "$SHA" --report; then + say "canaries passed" + elif [[ "$CANARY_MODE" == warn ]]; then + say "canaries FAILED; ORB_DEPLOY_CANARY=warn, promoting anyway" + else + say "canaries failed; prod untouched, dev stays on $SHA for debugging" + exit 1 + fi +fi + BACKUP="/usr/local/bin/orb-core.pre-deploy-$TS" OLD_SHA="$(sed -n 's/^Environment=ORB_BUILD_SHA=//p' /etc/systemd/system/sandboxed-sh-prod.service.d/30-build.conf 2>/dev/null || true)" CATALOG_CONF=/etc/systemd/system/sandboxed-sh-prod.service.d/31-catalog.conf diff --git a/scripts/ops/orb-deploy-canary b/scripts/ops/orb-deploy-canary new file mode 100755 index 0000000000..893c9a43e4 --- /dev/null +++ b/scripts/ops/orb-deploy-canary @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""orb-deploy-canary: launch real missions on dev Core before prod is promoted. + +`orb-deploy` runs this after dev is healthy on the new build and promotes prod +only when it exits 0. Every model call goes to Core's own fault-injection +upstream (`/__fault/v1`, `docs/specs/fault-upstream.md`), so the canary costs +nothing and can make providers fail on purpose. Spec: docs/operations/deploy-canaries.md. + +Checks, in order: + 1. restart dev Core, and launch the first mission the moment /api/health answers + 2. one mission per harness x placement on the fault provider: each must reach a + real first turn (an assistant message with the fault upstream's text) + 3. a Pi turn whose first call gets 503 must recover and answer + 4. proxy probes: a cut stream carries [orb:stream_incomplete], a late 429 is a 429, + a stalled first byte still answers + 5. a Mythos request with no marked account is 403 no_cyber_access_account + 6. no ghost missions: a retried create coalesces, and the only canary missions + are the ones the canary created +Canary missions are deleted when everything passed and kept for debugging otherwise. + +Usage: + orb-deploy-canary [--sha SHA] [--no-restart] [--keep] [--report] [--plan] +Environment: + ORB_CANARY_PORT dev Core port (default 3002) + ORB_CANARY_UNIT dev Core unit (default sandboxed-sh-dev) + ORB_CANARY_ENV_FILES env files holding JWT_SECRET and ORB_FAULT_UPSTREAM_KEY, + later overriding earlier (default core.env:dev.env) + ORB_CANARY_MISSIONS_DB dev missions DB (default: found under /var/lib/sandboxed-sh-dev) + ORB_CANARY_NODE remote node for the remote placement (default uruk; "" skips it) + ORB_CANARY_HARNESSES comma list (default claudecode,codex,opencode,pi,antigravity) + ORB_CANARY_TURN_TIMEOUT seconds for a first turn (default 240) +""" +import glob, hashlib, hmac, http.client, json, os, subprocess, sys, time, urllib.error, urllib.request, uuid + +ENV = os.environ.get +PORT = int(ENV("ORB_CANARY_PORT", "3002")) +UNIT = ENV("ORB_CANARY_UNIT", "sandboxed-sh-dev") +BASE = f"http://127.0.0.1:{PORT}" +ENV_FILES = ENV("ORB_CANARY_ENV_FILES", "/etc/orb/environments/core.env:/etc/orb/environments/dev.env:/etc/orb/fault-upstream.env").split(":") +NODE = ENV("ORB_CANARY_NODE", "uruk").strip() +HARNESSES = [h for h in ENV("ORB_CANARY_HARNESSES", "claudecode,codex,opencode,pi,antigravity").split(",") if h] +TURN_TIMEOUT = int(ENV("ORB_CANARY_TURN_TIMEOUT", "240")) +PROVIDER_ID = "prov-orb-fault" +PROVIDER = "orbfault" # the slug models are addressed by: orbfault/fault-ok +FAULT_MODELS = ["fault-ok", "fault-503", "fault-503x1", "fault-cut", "fault-stall-3000", "fault-late429-2000"] +REPLY_TEXT = "Orb fault upstream: ok." +RUN = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:6] +TITLE = f"[canary {RUN}]" + +# What each harness is expected to do per placement. "turn": a real first turn on the +# fault provider. "clean": Antigravity runs on its own Google login, never on the fault +# provider, so the canary only requires a clean outcome (a turn, or a refusal with a code +# and no mission left behind). +EXPECT = {h: "clean" if h == "antigravity" else "turn" for h in HARNESSES} +# Client/locald placement needs a desktop's orb-locald; it is not scriptable from the +# Core host and is reported as not covered. +PLACEMENTS = [("core", None)] + ([("remote", NODE)] if NODE else []) + + +def env_value(key): + val = "" + for path in ENV_FILES: + try: + for line in open(path): + if line.startswith(key + "="): + val = line.split("=", 1)[1].strip().strip('"').strip("'") + except OSError: + pass + return val + + +def missions_db(): + explicit = ENV("ORB_CANARY_MISSIONS_DB", "") + if explicit: + return explicit + found = sorted(glob.glob("/var/lib/sandboxed-sh-dev/**/missions*.db", recursive=True)) + return found[0] if found else "" + + +def admin_token(): + """A ten-minute admin session token minted from dev Core's own secret (as orb-monitor does).""" + import sqlite3 + secret, db = env_value("JWT_SECRET"), missions_db() + if not secret or not db: + raise SystemExit("canary: no JWT_SECRET or dev missions DB; cannot authenticate") + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=10) + row = con.execute("SELECT id, session_epoch FROM users WHERE role='admin' AND disabled=0 ORDER BY id LIMIT 1").fetchone() + con.close() + if not row: + raise SystemExit("canary: dev has no admin user") + payload = f"orb-jwt-v2:{row[0]}:admin:{row[1]}:{int(time.time()) + 3600}" + return payload + "." + hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest() + + +TOKEN = "" + + +def call(method, path, body=None, timeout=30, headers=None): + """(status, parsed JSON or text, response headers). Never raises on HTTP errors.""" + hdrs = {"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"} + hdrs.update(headers or {}) + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(BASE + path, data=data, headers=hdrs, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + status, rh = r.status, dict(r.headers) + try: + raw = r.read() + except http.client.IncompleteRead as cut: # a stream cut on purpose (fault-cut) + raw = cut.partial + except urllib.error.HTTPError as e: + raw, status, rh = e.read(), e.code, dict(e.headers or {}) + except Exception as e: # transport failure: report it as a status-0 result + return 0, f"{type(e).__name__}: {e}", {} + text = raw.decode("utf-8", "replace") + try: + return status, json.loads(text), rh + except ValueError: + return status, text, rh + + +class Result: + def __init__(self): + self.lines, self.failed = [], 0 + + def ok(self, name, detail=""): + self.lines.append(f"PASS {name}" + (f": {detail}" if detail else "")) + + def fail(self, name, detail): + self.failed += 1 + self.lines.append(f"FAIL {name}: {detail}") + + def skip(self, name, why): + self.lines.append(f"SKIP {name}: {why}") + + +def wait_health(deadline_s=120): + start = time.time() + while time.time() - start < deadline_s: + status, body, _ = call("GET", "/api/health", timeout=2) + if status == 200 and isinstance(body, dict) and body.get("status") == "ok": + return body + time.sleep(0.2) + return None + + +def ensure_fault_provider(res): + key = env_value("ORB_FAULT_UPSTREAM_KEY") + if not key: + res.fail("fault provider", "ORB_FAULT_UPSTREAM_KEY is not set for dev Core") + return False + status, body, _ = call("POST", "/api/ai/providers", { + "id": PROVIDER_ID, "provider_type": "custom", "name": PROVIDER, "enabled": True, + "base_url": f"http://127.0.0.1:{PORT}/__fault/v1", "api_key": key, + "custom_models": [{"id": m} for m in FAULT_MODELS]}) + if status not in (200, 201): + res.fail("fault provider", f"register returned {status}: {str(body)[:200]}") + return False + return True + + +def create(harness, model, node, prompt, key): + body = {"title": f"{TITLE} {harness}@{node or 'core'} {model}", "backend": harness, + "prompt": prompt, "idempotency_key": key, "tags": [f"orb-canary:{RUN}"]} + if model: + body["model_override"] = model + if node: + body["remote_node_id"] = node + return call("POST", "/api/control/missions", body, timeout=120) + + +def events(mid): + status, body, _ = call("GET", f"/api/control/missions/{mid}/events?view=transcript&limit=200") + if status != 200: + return [] + return body if isinstance(body, list) else body.get("events", []) if isinstance(body, dict) else [] + + +def event_text(ev): + c = ev.get("content", ev.get("payload", "")) + return c if isinstance(c, str) else json.dumps(c) + + +def wait_first_turn(mid, timeout): + """('turn', text) once an assistant message carries the fault reply; ('error', text) on a + terminal failure; ('timeout', last status) otherwise.""" + deadline = time.time() + timeout + last = "" + while time.time() < deadline: + for ev in events(mid): + if ev.get("event_type") == "assistant_message" and REPLY_TEXT in event_text(ev): + return "turn", event_text(ev)[:120] + status, m, _ = call("GET", f"/api/control/missions/{mid}") + last = (m or {}).get("status", "") if isinstance(m, dict) else str(m)[:80] + if last in ("failed", "cancelled"): + errs = [event_text(e)[:200] for e in events(mid) if e.get("event_type") == "error"] + return "error", f"status={last} {errs[-1] if errs else ''}" + time.sleep(3) + return "timeout", f"status={last}" + + +def launch_matrix(res, created): + model = f"{PROVIDER}/fault-ok" + for placement, node in PLACEMENTS: + for harness in HARNESSES: + name = f"{harness}@{placement}" + key = f"canary-{RUN}-{name}" + status, body, _ = create(harness, None if harness == "antigravity" else model, node, + "Reply with one short sentence.", key) + mid = body.get("id") if isinstance(body, dict) else None + if EXPECT[harness] == "clean" and not mid: + code = body.get("error") if isinstance(body, dict) else None + if status >= 400 and code: + res.ok(name, f"refused cleanly {status} {code}") + else: + res.fail(name, f"refused without a code: {status} {str(body)[:200]}") + continue + if not mid: + res.fail(name, f"create returned {status}: {str(body)[:200]}") + continue + created.append(mid) + # A retried create with the same key must coalesce, never make a second mission. + s2, b2, h2 = create(harness, None if harness == "antigravity" else model, node, + "Reply with one short sentence.", key) + if isinstance(b2, dict) and b2.get("id") not in (None, mid): + created.append(b2["id"]) + res.fail(f"{name} retry", f"a retried create made a second mission {b2['id']}") + outcome, detail = wait_first_turn(mid, TURN_TIMEOUT) + if outcome == "turn" or (EXPECT[harness] == "clean" and outcome == "error"): + res.ok(name, detail) + else: + res.fail(name, f"{outcome}: {detail}") + + +def pi_failover(res, created): + if "pi" not in HARNESSES: + return + status, body, _ = create("pi", f"{PROVIDER}/fault-503x1", None, "Reply with one short sentence.", + f"canary-{RUN}-pi-503") + mid = body.get("id") if isinstance(body, dict) else None + if not mid: + res.fail("pi 503 recovery", f"create returned {status}: {str(body)[:200]}") + return + created.append(mid) + outcome, detail = wait_first_turn(mid, TURN_TIMEOUT + 60) # one 20 s transient retry + recovered = any(e.get("event_type") == "recovered" for e in events(mid)) + if outcome == "turn": + res.ok("pi 503 recovery", "recovered after a 503" if recovered else "answered (failed over in the chain)") + else: + res.fail("pi 503 recovery", f"{outcome}: {detail}") + + +def proxy_probes(res): + def chat(model, stream, timeout=60): + return call("POST", "/v1/chat/completions", {"model": f"{PROVIDER}/{model}", "stream": stream, + "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}, timeout=timeout) + status, body, _ = chat("fault-cut", True) + text = body if isinstance(body, str) else json.dumps(body) + if "[orb:stream_incomplete]" in text: + res.ok("proxy cut stream", "client got a tagged stream_incomplete frame") + else: + res.fail("proxy cut stream", f"{status}: no [orb:stream_incomplete] in {text[-200:]}") + t0 = time.time() + status, body, _ = chat("fault-late429-2000", False) + if status == 429 and time.time() - t0 >= 2: + res.ok("proxy late 429", "429 after the delay") + else: + res.fail("proxy late 429", f"{status} after {time.time() - t0:.1f}s: {str(body)[:200]}") + t0 = time.time() + status, body, _ = chat("fault-stall-3000", False) + if status == 200 and REPLY_TEXT in json.dumps(body): + res.ok("proxy stalled first byte", f"answered after {time.time() - t0:.1f}s") + else: + res.fail("proxy stalled first byte", f"{status}: {str(body)[:200]}") + status, body, _ = chat("fault-503", False) + msg = json.dumps(body) + if status == 503: + res.ok("proxy 503", "503 reaches the client") + else: + res.fail("proxy 503", f"{status}: {msg[:200]}") + + +def mythos_probe(res): + status, body, _ = call("POST", "/v1/chat/completions", {"model": "claude-mythos-1", "max_tokens": 1, + "messages": [{"role": "user", "content": "hi"}]}) + code = body.get("error") if isinstance(body, dict) else None + if isinstance(code, dict): + code = code.get("code") + if status == 403 and code == "no_cyber_access_account": + res.ok("mythos without a marked account", "403 no_cyber_access_account") + else: + res.fail("mythos without a marked account", f"{status} {code}: {str(body)[:200]}") + + +def ghost_check(res, created): + status, body, _ = call("GET", "/api/control/missions?limit=500") + rows = body if isinstance(body, list) else (body or {}).get("missions", []) if isinstance(body, dict) else [] + ours = {m.get("id") for m in rows if isinstance(m, dict) and TITLE in (m.get("title") or "")} + ghosts = ours - set(created) + missing = set(created) - ours + if status != 200: + res.fail("no ghost missions", f"mission list returned {status}") + elif ghosts: + res.fail("no ghost missions", f"{len(ghosts)} canary mission(s) nobody created: {sorted(ghosts)[:5]}") + else: + res.ok("no ghost missions", f"{len(ours)} canary mission(s), all accounted for" + + (f"; {len(missing)} not listed" if missing else "")) + + +def cleanup(created): + for mid in created: + call("POST", f"/api/control/missions/{mid}/cancel", {}) + call("DELETE", f"/api/control/missions/{mid}") + + +def report(text): + """The Orb monitor's Paloma alert and Inbox mission (`orb-monitor --report`).""" + try: + subprocess.run(["/usr/local/sbin/orb-monitor", "--report", text], timeout=60, check=False) + except (OSError, subprocess.SubprocessError) as exc: + print(f"canary: report failed: {exc}", file=sys.stderr) + + +def main(argv): + global TOKEN + if "--plan" in argv: + print(f"harnesses={HARNESSES} placements={PLACEMENTS} expect={EXPECT}") + print("not covered: client/locald placement (needs a desktop orb-locald)") + return 0 + sha = argv[argv.index("--sha") + 1] if "--sha" in argv else "" + res = Result() + TOKEN = admin_token() + created = [] + if "--no-restart" not in argv: + subprocess.run(["systemctl", "restart", UNIT], check=True) + health = wait_health() + if not health: + res.fail("dev health", "dev Core did not answer /api/health within 120 s") + elif sha and health.get("build") != sha: + res.fail("dev health", f"dev runs {health.get('build')}, not {sha}") + elif ensure_fault_provider(res): + res.ok("dev health", f"build {health.get('build', '?')}") + launch_matrix(res, created) + pi_failover(res, created) + proxy_probes(res) + mythos_probe(res) + ghost_check(res, created) + res.skip("client/locald placement", "needs a desktop orb-locald; not scriptable from the Core host") + passed = res.failed == 0 + if passed and "--keep" not in argv: + cleanup(created) + head = f"[orb-deploy-canary] {'PASS' if passed else 'FAIL'} {sha[:12] or 'dev'} run {RUN}: " \ + f"{res.failed} failure(s)" + ("" if passed else f"; canary missions kept on dev: {TITLE}") + text = "\n".join([head] + res.lines) + print(text) + if "--report" in argv: + report(text[:1800]) + return 0 if passed else 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/ops/orb-monitor b/scripts/ops/orb-monitor index a5646a0244..e7e8a27c64 100755 --- a/scripts/ops/orb-monitor +++ b/scripts/ops/orb-monitor @@ -399,7 +399,25 @@ def notify(text, opened=(), cleared=()): print("report reached neither Paloma nor the Inbox", file=sys.stderr) +def load_monitor_env(path="/etc/orb/monitor.env"): + """The unit's EnvironmentFile, for `--report` runs started outside the unit (orb-deploy).""" + try: + for line in open(path): + k, sep, v = line.strip().partition("=") + if sep and k and not k.startswith("#") and k not in os.environ: + os.environ[k] = v.strip().strip('"').strip("'") + except OSError: + pass + + def main(): + if "--report" in sys.argv: + # One message from another tool (orb-deploy's canaries), sent the way alerts are sent. + load_monitor_env() + text = sys.argv[sys.argv.index("--report") + 1] if len(sys.argv) > sys.argv.index("--report") + 1 else "" + if text: + notify(text[:1800]) + return 0 problems, info = {}, {} try: with open(STATE) as state_file: diff --git a/shared/orb-spec/fixtures/error-classes.json b/shared/orb-spec/fixtures/error-classes.json new file mode 100644 index 0000000000..ef69714d15 --- /dev/null +++ b/shared/orb-spec/fixtures/error-classes.json @@ -0,0 +1,58 @@ +{ + "spec": "docs/specs/typed-errors.md", + "source": "lean/Orb/ErrorCode.lean (registry), lean/OrbCore/OrbCore/ErrorClass.lean (parser)", + "tag_format": "[orb:]", + "transient_statuses": { "503": "provider_unavailable", "504": "provider_unavailable", "529": "provider_unavailable" }, + "codes": { + "stream_incomplete": "transient:stream_incomplete", + "upstream_idle_timeout": "transient:idle_timeout", + "idle_timeout": "transient:idle_timeout", + "server_unavailable": "transient:provider_unavailable", + "provider_unavailable": "transient:provider_unavailable", + "model_cooldown": "transient:provider_unavailable", + "overloaded_error": "transient:provider_unavailable", + "harness_exited": "transient:harness_exited", + "no_provider_for_model": "permanent", + "skipped_configuration": "permanent", + "model_not_found": "permanent", + "no_user_enabled_providers": "permanent", + "no_cyber_access_account": "permanent", + "only_reserved_accounts": "permanent", + "context_length_exceeded": "permanent", + "out_of_credit": "permanent", + "client_or_auth_error": "permanent", + "transport_validation": "permanent", + "usage_limit_reached": "permanent", + "insufficient_quota": "permanent", + "rate_limited_or_quota": "permanent", + "cyber_access_store_unavailable": "permanent" + }, + "text_cases": [ + { "name": "new-api 503 no channel (status only)", "text": "503 No available channel for model gemini-4-neon under group default", "expected": "transient:provider_unavailable" }, + { "name": "Orb exhaustion body, OpenAI SDK prints the bare code", "text": "502 \"server_unavailable\"", "expected": "transient:provider_unavailable" }, + { "name": "model cooldown", "text": "503 \"model_cooldown\"", "expected": "transient:provider_unavailable" }, + { "name": "Anthropic overloaded via Claude Code", "text": "API Error: 529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", "expected": "transient:provider_unavailable" }, + { "name": "idle timeout code beats 504 status", "text": "504 \"upstream_idle_timeout\"", "expected": "transient:idle_timeout" }, + { "name": "stream cut frame message", "text": "stream_incomplete: upstream stream ended without a finish_reason [orb:stream_incomplete]", "expected": "transient:stream_incomplete" }, + { "name": "idle cut frame message", "text": "upstream_idle_timeout: the upstream provider stopped sending data before the reply finished [orb:upstream_idle_timeout]", "expected": "transient:idle_timeout" }, + { "name": "Pi driver exit", "text": "Pi RPC process ended before agent_end [orb:harness_exited]", "expected": "transient:harness_exited" }, + { "name": "tagged permanent beats 503", "text": "503 No configured provider account can serve model 'x'. It was not rerouted to another model. [orb:no_provider_for_model]", "expected": "permanent" }, + { "name": "Orb shape-1 permanent", "text": "503 \"skipped_configuration\"", "expected": "permanent" }, + { "name": "client/auth exhaustion", "text": "502 \"client_or_auth_error\"", "expected": "permanent" }, + { "name": "Mythos without a marked account", "text": "403 \"no_cyber_access_account\"", "expected": "permanent" }, + { "name": "context overflow", "text": "400 Prompt exceeds context window [orb:context_length_exceeded]", "expected": "permanent" }, + { "name": "late 429 rate limit is not retried here", "text": "429 \"rate_limited_or_quota\"", "expected": "permanent" }, + { "name": "mission error event payload", "text": "{\"message\":\"Transient upstream failure\",\"code\":\"provider_unavailable\",\"retryable\":true}", "expected": "transient:provider_unavailable" }, + { "name": "phrase alone is not a code", "text": "the server said: overloaded, no available channel, service unavailable", "expected": "none" }, + { "name": "a number in prose is not a status", "text": "tool failed: wrote 503 lines", "expected": "none" }, + { "name": "plain tool failure", "text": "tool failed: permission denied", "expected": "none" }, + { "name": "empty", "text": "", "expected": "none" } + ], + "tag_body_cases": [ + { "name": "OpenAI-shaped Orb body gains the tag", "body": "{\"error\":{\"message\":\"No configured provider account can serve model 'x'.\",\"type\":\"service_unavailable\",\"code\":\"no_provider_for_model\"}}", "message": "No configured provider account can serve model 'x'. [orb:no_provider_for_model]" }, + { "name": "Anthropic overloaded gains the tag", "body": "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", "message": "Overloaded [orb:overloaded_error]" }, + { "name": "unregistered code is left alone", "body": "{\"error\":{\"message\":\"No available channel\",\"type\":\"new_api_error\",\"code\":\"\"}}", "message": null }, + { "name": "Orb shape-1 body already shows its code", "body": "{\"error\":\"server_unavailable\",\"message\":\"All providers failed\"}", "message": null }, + { "name": "already tagged", "body": "{\"error\":{\"message\":\"x [orb:model_cooldown]\",\"code\":\"model_cooldown\"}}", "message": null } + ] +} From ffd908f90a97ccd1d8fa28863a044d4751919018 Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 18:09:08 +0000 Subject: [PATCH 2/4] fix(ops): dev fault-upstream key fits the orb-deploy test sandbox; parity test ignores it --- scripts/ops/orb-deploy | 16 ++++++++-------- scripts/test_orb_dev_autodeploy.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/scripts/ops/orb-deploy b/scripts/ops/orb-deploy index aee57dc3d8..e257db502c 100755 --- a/scripts/ops/orb-deploy +++ b/scripts/ops/orb-deploy @@ -301,6 +301,14 @@ if [[ $ROLLOUT_NODES == 1 ]]; then fi set_catalog sandboxed-sh-dev "$CATALOG" +# Dev only: Core's fault-injection upstream (`docs/specs/fault-upstream.md`) for the canaries. +# Prod never gets this key, so `/__fault/*` does not exist there. +FAULT_ENV="${ORB_DEPLOY_FAULT_ENV:-/etc/orb/fault-upstream.env}" +if [[ ! -s "$FAULT_ENV" ]]; then + install -d -m 755 "$(dirname "$FAULT_ENV")" + (umask 077; printf 'ORB_FAULT_UPSTREAM_KEY=%s\n' "$(LC_ALL=C tr -dc a-f0-9 "$FAULT_ENV") +fi +printf '%s\n' "[Service]" "EnvironmentFile=$FAULT_ENV" > /etc/systemd/system/sandboxed-sh-dev.service.d/32-fault-upstream.conf set_build sandboxed-sh-dev "$SHA"; systemctl daemon-reload TS="$(date -u +%Y%m%dT%H%M%SZ)" install -d -m 755 /usr/local/lib/orb /usr/local/lib/orb/guest /usr/local/sbin /usr/local/libexec @@ -437,14 +445,6 @@ else install -m 755 "$BIN" /usr/local/bin/orb-core-dev.new mv /usr/local/bin/orb-core-dev.new /usr/local/bin/orb-core-dev fi -# Dev only: Core's fault-injection upstream (`docs/specs/fault-upstream.md`) for the canaries. -# Prod never gets this key, so `/__fault/*` does not exist there. -FAULT_ENV=/etc/orb/fault-upstream.env -if [[ ! -s "$FAULT_ENV" ]]; then - (umask 077; printf 'ORB_FAULT_UPSTREAM_KEY=%s\n' "$(head -c 32 /dev/urandom | sha256sum | cut -c1-48)" > "$FAULT_ENV") -fi -printf '%s\n' "[Service]" "EnvironmentFile=$FAULT_ENV" > /etc/systemd/system/sandboxed-sh-dev.service.d/32-fault-upstream.conf -systemctl daemon-reload if [[ $ROLLOUT_NODES == 1 ]]; then DEV_TOUCHED=1; fi systemctl restart sandboxed-sh-dev if ! healthy 3002 30 "$SHA"; then diff --git a/scripts/test_orb_dev_autodeploy.py b/scripts/test_orb_dev_autodeploy.py index 2b79c05e40..12b6d4b3c2 100644 --- a/scripts/test_orb_dev_autodeploy.py +++ b/scripts/test_orb_dev_autodeploy.py @@ -371,6 +371,8 @@ def _run_staged_deploy( **os.environ, "ORB_DEPLOY_TREE": str(tree), "ORB_DEPLOY_LOG": str(root / "deploy.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), "ORB_DEPLOY_SKIP_AARCH64": "1", "ORB_DEPLOY_RELEASES": str(root / "releases"), "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], @@ -453,6 +455,9 @@ def test_plain_deploy_executed_commands_match_master(self): # Added by build-once: the CI release probe and a private self-test HOME. if re.search(r"orb_release\.py|orb-selftest-home|/releases|git rev-parse \S+\^\{tree\}", line): continue + # Added by the deploy canaries: dev's fault-upstream key file. + if "fault-upstream" in line: + continue commands.append(line) traces.append(commands) baseline_trace, current_trace = traces @@ -603,6 +608,8 @@ def test_deploy_nodes_status_and_dry_run_invoke_rolling_upgrade_controller(self) **os.environ, "ORB_DEPLOY_TREE": str(tree), "ORB_DEPLOY_LOG": str(root / "deploy.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), } for flag, expected_mode in [("--nodes-status", "--status"), ("--nodes-dry-run", "--dry-run")]: res = subprocess.run( @@ -697,6 +704,8 @@ def test_deploy_mid_install_failure_rolls_back_via_exit_trap_and_stages_release_ **os.environ, "ORB_DEPLOY_TREE": str(tree), "ORB_DEPLOY_LOG": str(root / "deploy.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], } res = subprocess.run( @@ -785,6 +794,8 @@ def test_release_bin_dir_survives_kill_between_staging_and_switch(self): **os.environ, "ORB_DEPLOY_TREE": str(tree), "ORB_DEPLOY_LOG": str(root / "deploy.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], } res = subprocess.run( @@ -868,6 +879,8 @@ def test_plain_deploy_exact_master_parity_on_stale_catalog_new(self): **os.environ, "ORB_DEPLOY_TREE": str(tree), "ORB_DEPLOY_LOG": str(root / "deploy.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"], } res = subprocess.run( @@ -944,6 +957,8 @@ def _fake_aarch64_elf(label: bytes) -> bytes: **os.environ, "ORB_DEPLOY_TREE": str(root / "tree"), "ORB_DEPLOY_LOG": str(root / "deploy-arm.log"), + "ORB_DEPLOY_CANARY": "skip", + "ORB_DEPLOY_FAULT_ENV": str(root / "fault-upstream.env"), "ORB_DEPLOY_SKIP_AARCH64": "0", "ORB_DEPLOY_AARCH64_HOST": "fake-spark", "ORB_DEPLOY_SSH_CONFIG": str(root / "nonexistent-ssh-cfg"), From 26ad3ed283828000485fd904b28bf4f6e3c5ddd6 Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 18:15:54 +0000 Subject: [PATCH 3/4] ci(kernel-abi): compile Orb/ErrorCode before Orb/PiHarness --- .github/workflows/kernel-abi.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/kernel-abi.yml b/.github/workflows/kernel-abi.yml index 3cfecf0bde..62e9075606 100644 --- a/.github/workflows/kernel-abi.yml +++ b/.github/workflows/kernel-abi.yml @@ -138,6 +138,9 @@ jobs: LEAN_PATH=.lake/build/lib/lean lean -DwarningAsError=true -DautoImplicit=false Orb/ManagedNodeMutants.lean \ -o .lake/build/lib/lean/Orb/ManagedNodeMutants.olean \ -i .lake/build/lib/lean/Orb/ManagedNodeMutants.ilean + LEAN_PATH=.lake/build/lib/lean lean -DwarningAsError=true -DautoImplicit=false Orb/ErrorCode.lean \ + -o .lake/build/lib/lean/Orb/ErrorCode.olean \ + -i .lake/build/lib/lean/Orb/ErrorCode.ilean LEAN_PATH=.lake/build/lib/lean lean -DwarningAsError=true -DautoImplicit=false Orb/PiHarness.lean \ -o .lake/build/lib/lean/Orb/PiHarness.olean \ -i .lake/build/lib/lean/Orb/PiHarness.ilean From 3f2b08e6f7a803219aa71ee92ff2a5e4663cd176 Mon Sep 17 00:00:00 2001 From: "Thomas Marchand (agent)" Date: Mon, 30 Nov 2026 18:52:04 +0000 Subject: [PATCH 4/4] test: every Pi recovery path keeps its typed code end to end; tag leads the message so the 1000-char cut keeps it --- docs/specs/typed-errors.md | 18 ++- lean/Orb/PiHarness.lean | 2 +- lean/OrbCore/OrbCore/ErrorClass.lean | 5 +- lean/OrbCore/OrbCore/Proxy.lean | 2 +- lean/OrbCore/OrbCore/ProxyRoutingTests.lean | 48 +++++- lean/OrbCore/OrbCore/TurnOutcomeTests.lean | 6 +- shared/orb-spec/fixtures/error-classes.json | 155 ++++++++++++++++---- 7 files changed, 197 insertions(+), 39 deletions(-) diff --git a/docs/specs/typed-errors.md b/docs/specs/typed-errors.md index d64de798ba..58a6311f2e 100644 --- a/docs/specs/typed-errors.md +++ b/docs/specs/typed-errors.md @@ -18,13 +18,19 @@ Code as `API Error: `; an SSE error frame by its message alone. A field is lost when the SDK prints only the message. So the code also rides in the message as `[orb:]`: -- **Proxy responses.** Every `/v1/*` error response from Core whose body names a registered code - (`error.code`, `error.type` or `error` as a string) gets `[orb:]` appended to - `error.message` (`Control.lean`, around `handleProxyRequest`). Upstream bodies with unknown - codes are left alone. -- **Stream cuts.** `streamCutErrorFrame` tags `stream_incomplete` / `upstream_idle_timeout`. -- **Harness drivers.** The Pi driver's "ended before `agent_end`" error carries +- **Proxy responses.** Every `/v1/*` error response from Core whose `error` object names a + registered code (`error.code` or `error.type`) gets `[orb:]` put at the start of + `error.message` (`tagProxyErrorResponse` in `Control.lean`). At the start, because harness + drivers cut error text to 1000 characters. Orb's own `{"error":""}` bodies need no tag: + the OpenAI SDK prints them as ` ""`. Upstream bodies with unknown codes are left + alone. +- **Stream cuts.** `streamCutErrorFrame` starts its message with `[orb:stream_incomplete]` or + `[orb:upstream_idle_timeout]`. +- **Harness drivers.** The Pi driver's "ended before `agent_end`" error starts with `[orb:harness_exited]` (`Orb.Kernel.piRpcEndedBeforeAgentEnd`). +- **End to end.** `ProxyRoutingTests.piFailurePathsEndToEnd` runs each real failure (proxy cut, + idle cut, pre-head 504, upstream 503 with no Orb code, Anthropic 529, Pi process death) through + the text Pi reports, both Pi event parsers (Core host and node), and the classifier. ## Classification diff --git a/lean/Orb/PiHarness.lean b/lean/Orb/PiHarness.lean index 3e4135d5a9..57d8815f7c 100644 --- a/lean/Orb/PiHarness.lean +++ b/lean/Orb/PiHarness.lean @@ -67,7 +67,7 @@ def piRpcIsFenced (s : PiRpcSession) : Bool := final `agent_end`. It carries the typed code `harness_exited` (`Orb.ErrorCode`), which Core's turn settlement reads to retry the turn. -/ def piRpcEndedBeforeAgentEnd : String := - s!"Pi RPC process ended before agent_end {Orb.ErrorCode.tag "harness_exited"}" + s!"{Orb.ErrorCode.tag "harness_exited"} Pi RPC process ended before agent_end" /-- True iff an outcome emits assistant text or tool events downstream. -/ def piRpcOutcomeEmitsOutput : PiRpcOutcome → Bool diff --git a/lean/OrbCore/OrbCore/ErrorClass.lean b/lean/OrbCore/OrbCore/ErrorClass.lean index 1cff589b91..ce1e9ffd66 100644 --- a/lean/OrbCore/OrbCore/ErrorClass.lean +++ b/lean/OrbCore/OrbCore/ErrorClass.lean @@ -67,8 +67,9 @@ def classifyText? (raw : String) : Option ErrorClass := let codes := taggedCodes raw ++ ((jsonPart? raw rest).map jsonCodes).getD [] classify status? codes -/-- `error.message` of an error body with `[orb:]` appended, for a body whose code is in the +/-- `error.message` of an error body with `[orb:]` put first, for a body whose code is in the registry, so a harness that prints only the message (OpenAI SDK, Anthropic SDK) keeps the code. + First, not last: harness drivers cut error text to 1000 characters. `none` leaves the body as it is: not JSON, no registered code, no message string, or already tagged. -/ def tagErrorBody? (body : String) : Option String := match (parse body).toOption with @@ -79,7 +80,7 @@ def tagErrorBody? (body : String) : Option String := | some msg => if (msg.splitOn "[orb:").length > 1 then none else - let ekvs' := ekvs.map fun (k, x) => if k == "message" then (k, .str s!"{msg} {tag code}") else (k, x) + let ekvs' := ekvs.map fun (k, x) => if k == "message" then (k, .str s!"{tag code} {msg}") else (k, x) some (renderCompact (.obj (kvs.map fun (k, x) => if k == "error" then (k, .obj ekvs') else (k, x)))) | none => none | _, _ => none diff --git a/lean/OrbCore/OrbCore/Proxy.lean b/lean/OrbCore/OrbCore/Proxy.lean index 3140867911..1054adaeff 100644 --- a/lean/OrbCore/OrbCore/Proxy.lean +++ b/lean/OrbCore/OrbCore/Proxy.lean @@ -2742,7 +2742,7 @@ def streamCutErrorFrame (timedOut : Bool) : String := ("stream_incomplete", "stream_incomplete: upstream stream ended without a finish_reason") -- The tag carries the code to Core's turn settlement: clients report a stream error frame by -- its message alone (`docs/specs/typed-errors.md`). - let message := s!"{message} {Orb.ErrorCode.tag code}" + let message := s!"{Orb.ErrorCode.tag code} {message}" s!"data: \{\"error\":\{\"message\":{jsonEscape message},\"type\":\"upstream_error\",\"code\":{jsonEscape code}}}\n\n" /-- Tail sent to the client when a streamed reply ends without recovery (`stream_incomplete` or diff --git a/lean/OrbCore/OrbCore/ProxyRoutingTests.lean b/lean/OrbCore/OrbCore/ProxyRoutingTests.lean index 6055f54476..a60a66984f 100644 --- a/lean/OrbCore/OrbCore/ProxyRoutingTests.lean +++ b/lean/OrbCore/OrbCore/ProxyRoutingTests.lean @@ -2164,6 +2164,51 @@ private def infistarDirectRouting (store : CoreStore) (chainsRef : IO.Ref (Array s!"without a chain, Infistar's own 503 reaches Pi and is a transient failure: {soloResp.status} {soloMsg}" discard <| execParamQuery store.missionsDb "DELETE FROM ai_providers WHERE id='prov-infistar';" #[] +/-- Every failure Pi recovers from (#2358) still reaches turn settlement with its typed code + (`docs/specs/typed-errors.md`): the body or frame the proxy really sends, through + `tagProxyErrorResponse`, the error text the OpenAI SDK makes of it, Pi's `agent_end` line, both + Pi event parsers (Core host: `Harness.stepPiJsonLine`; node: `ClaudeControl.parsePiRpcEvent`, + which cut the text to 1000 characters), then the classifier. Pi's process death goes through the + driver's own `error` line. -/ +def piFailurePathsEndToEnd : IO Unit := do + let tagged := fun (status : Nat) (body : String) => + (String.fromUTF8? (tagProxyErrorResponse { status, body := body.toUTF8 }).body).getD "" + let frameMessage := fun (frame : String) => + let json := ((frame.splitOn "data: ").getD 1 "").trimAscii.toString + (((OrbBin.Json.parse json).toOption.getD .null).fieldOrNull "error").fieldStr? "message" |>.getD "" + let longModel := "".pushn 'm' 1500 + let cases : Array (String × String × Option OrbCore.Spec.TransientTurnFailureReason) := #[ + ("proxy mid-stream cut", frameMessage (OrbCore.Proxy.streamCutErrorFrame false), some .streamIncomplete), + ("proxy mid-stream idle cut", frameMessage (OrbCore.Proxy.streamCutErrorFrame true), some .idleTimeout), + ("pre-head 504 idle timeout", openAiSdkErrorMessage (some 504) (tagged 504 "{\"error\":\"upstream_idle_timeout\"}"), some .idleTimeout), + ("chain exhausted 502", openAiSdkErrorMessage (some 502) + (tagged 502 (String.fromUTF8? (OrbCore.Proxy.chainExhaustedBody "server_unavailable" "all failed" #[])).get!), some .providerUnavailable), + ("upstream 503 with no Orb code (Infistar)", openAiSdkErrorMessage (some 503) + (tagged 503 ((String.fromUTF8? (infistarNoChannelBody "gemini-4-neon")).getD "")), some .providerUnavailable), + ("Anthropic 529 overloaded", s!"529 {tagged 529 "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}"}", + some .providerUnavailable), + ("no provider for a long model id stays permanent after the 1000-character cut", openAiSdkErrorMessage (some 503) + (tagged 503 (OrbCore.ProxyModelRouting.noProviderBody longModel)), none)] + for (name, sdkMsg, expected) in cases do + let agentEnd := renderCompact (.obj #[("type", .str "agent_end"), ("messages", .arr #[.obj #[ + ("role", .str "assistant"), ("stopReason", .str "error"), ("errorMessage", .str sdkMsg)]])]) + let coreText := ((OrbCore.Harness.stepPiJsonLine { missionId := "m-pi" } agentEnd).emittedEvents.findSome? fun + | .TurnResult _ true msg => some msg + | _ => none).getD "" + let nodeText := ((OrbBin.ClaudeControl.parsePiRpcEvent agentEnd).errorMsg?).getD "" + for (where_, text) in #[("core", coreText), ("node", nodeText)] do + check (OrbCore.RemoteDispatch.classifyTransientTurnFailureText? text == expected) + s!"Pi path '{name}' ({where_} parser) classifies as {repr expected}: {(text.take 160).toString}" + -- Pi's process death: the driver's own error line (`OrbNode.PiRpc`). + let death := renderCompact (.obj #[("type", .str "error"), ("error", .obj #[("message", .str Orb.Kernel.piRpcEndedBeforeAgentEnd)])]) + let deathCore := ((OrbCore.Harness.stepPiJsonLine { missionId := "m-pi" } death).emittedEvents.findSome? fun + | .TurnResult _ true msg => some msg + | _ => none).getD "" + let deathNode := ((OrbBin.ClaudeControl.parsePiRpcEvent death).errorMsg?).getD "" + check (OrbCore.RemoteDispatch.classifyTransientTurnFailureText? deathCore == some .harnessExited && + OrbCore.RemoteDispatch.classifyTransientTurnFailureText? deathNode == some .harnessExited) + s!"Pi process death is harness_exited on both parsers: {deathCore} | {deathNode}" + /-- The fault upstream (`docs/specs/fault-upstream.md`): off without a key, refuses a wrong key, and each model id behaves as documented on every protocol. -/ def faultUpstreamFixture : IO Unit := do @@ -2220,6 +2265,7 @@ def faultUpstreamFixture : IO Unit := do def run : IO Unit := do runStreaming faultUpstreamFixture + piFailurePathsEndToEnd infistarRecoveryFixture runStreamingPumpContracts r26ProviderDisabledIsTerminal @@ -2365,7 +2411,7 @@ def run : IO Unit := do -- Typed errors: the code also rides in the message, so a harness that prints only the -- message keeps it, and turn settlement calls it permanent. let sdkMsg := s!"400 {(error.fieldStr? "message").getD ""}" - if !(((error.fieldStr? "message").getD "").endsWith "[orb:model_not_found]") || + if !(((error.fieldStr? "message").getD "").startsWith "[orb:model_not_found] ") || OrbCore.ErrorClass.classifyText? sdkMsg != some .permanent then failures := failures.push s!"{model}: proxy error message lacks its [orb:model_not_found] tag" -- Exercise every saved id and its compatibility spelling, not an allowlist diff --git a/lean/OrbCore/OrbCore/TurnOutcomeTests.lean b/lean/OrbCore/OrbCore/TurnOutcomeTests.lean index 31608b292b..ed3c72a2ef 100644 --- a/lean/OrbCore/OrbCore/TurnOutcomeTests.lean +++ b/lean/OrbCore/OrbCore/TurnOutcomeTests.lean @@ -1750,19 +1750,19 @@ def run : IO Unit := do -- (2) Third consecutive cut (`stream_incomplete` / `idle_timeout`) ends `failed` with the reason. newMission "m-r28-three-cuts" "[]" - finishStreamCut "m-r28-three-cuts" "stream_incomplete: upstream stream ended without a finish_reason [orb:stream_incomplete]" + finishStreamCut "m-r28-three-cuts" "[orb:stream_incomplete] stream_incomplete: upstream stream ended without a finish_reason" check ((← retries "m-r28-three-cuts") == "transient_turn_retry:1:stream_incomplete/1" && (← recoveredEvents "m-r28-three-cuts") == "1") "r28 cut #1 arms retry 1 and emits recovered #1" let dueEpCut1 := ((← cellOf db "SELECT COALESCE(due_epoch,0) FROM mission_continuations WHERE mission_id='m-r28-three-cuts' ORDER BY rowid DESC LIMIT 1;").toNat?).getD 0 tick (dueEpCut1.toUInt64 + 10) - finishStreamCut "m-r28-three-cuts" "upstream_idle_timeout: stream stalled [orb:upstream_idle_timeout]" + finishStreamCut "m-r28-three-cuts" "[orb:upstream_idle_timeout] upstream_idle_timeout: stream stalled" check ((← retries "m-r28-three-cuts") == "transient_turn_retry:1:stream_incomplete/4,transient_turn_retry:2:idle_timeout/1" && (← recoveredEvents "m-r28-three-cuts") == "2" && (← statusOf "m-r28-three-cuts") == "awaiting_user") s!"r28 cut #2 arms retry 2 and emits recovered #2, got retries='{← retries "m-r28-three-cuts"}'" let dueEpCut2 := ((← cellOf db "SELECT COALESCE(due_epoch,0) FROM mission_continuations WHERE mission_id='m-r28-three-cuts' ORDER BY rowid DESC LIMIT 1;").toNat?).getD 0 tick (dueEpCut2.toUInt64 + 10) let launchesBeforeThirdCut ← launches.get - finishStreamCut "m-r28-three-cuts" "stream_incomplete: upstream stream ended without a finish_reason [orb:stream_incomplete]" + finishStreamCut "m-r28-three-cuts" "[orb:stream_incomplete] stream_incomplete: upstream stream ended without a finish_reason" check ((← statusOf "m-r28-three-cuts") == "failed" && (← termReasonOf "m-r28-three-cuts") == "stream_incomplete") s!"r28 third consecutive cut ends failed with reason stream_incomplete, got status='{← statusOf "m-r28-three-cuts"}' reason='{← termReasonOf "m-r28-three-cuts"}'" check ((← retries "m-r28-three-cuts") == "transient_turn_retry:1:stream_incomplete/4,transient_turn_retry:2:idle_timeout/4" && diff --git a/shared/orb-spec/fixtures/error-classes.json b/shared/orb-spec/fixtures/error-classes.json index ef69714d15..4ca59b2b9f 100644 --- a/shared/orb-spec/fixtures/error-classes.json +++ b/shared/orb-spec/fixtures/error-classes.json @@ -2,7 +2,11 @@ "spec": "docs/specs/typed-errors.md", "source": "lean/Orb/ErrorCode.lean (registry), lean/OrbCore/OrbCore/ErrorClass.lean (parser)", "tag_format": "[orb:]", - "transient_statuses": { "503": "provider_unavailable", "504": "provider_unavailable", "529": "provider_unavailable" }, + "transient_statuses": { + "503": "provider_unavailable", + "504": "provider_unavailable", + "529": "provider_unavailable" + }, "codes": { "stream_incomplete": "transient:stream_incomplete", "upstream_idle_timeout": "transient:idle_timeout", @@ -28,31 +32,132 @@ "cyber_access_store_unavailable": "permanent" }, "text_cases": [ - { "name": "new-api 503 no channel (status only)", "text": "503 No available channel for model gemini-4-neon under group default", "expected": "transient:provider_unavailable" }, - { "name": "Orb exhaustion body, OpenAI SDK prints the bare code", "text": "502 \"server_unavailable\"", "expected": "transient:provider_unavailable" }, - { "name": "model cooldown", "text": "503 \"model_cooldown\"", "expected": "transient:provider_unavailable" }, - { "name": "Anthropic overloaded via Claude Code", "text": "API Error: 529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", "expected": "transient:provider_unavailable" }, - { "name": "idle timeout code beats 504 status", "text": "504 \"upstream_idle_timeout\"", "expected": "transient:idle_timeout" }, - { "name": "stream cut frame message", "text": "stream_incomplete: upstream stream ended without a finish_reason [orb:stream_incomplete]", "expected": "transient:stream_incomplete" }, - { "name": "idle cut frame message", "text": "upstream_idle_timeout: the upstream provider stopped sending data before the reply finished [orb:upstream_idle_timeout]", "expected": "transient:idle_timeout" }, - { "name": "Pi driver exit", "text": "Pi RPC process ended before agent_end [orb:harness_exited]", "expected": "transient:harness_exited" }, - { "name": "tagged permanent beats 503", "text": "503 No configured provider account can serve model 'x'. It was not rerouted to another model. [orb:no_provider_for_model]", "expected": "permanent" }, - { "name": "Orb shape-1 permanent", "text": "503 \"skipped_configuration\"", "expected": "permanent" }, - { "name": "client/auth exhaustion", "text": "502 \"client_or_auth_error\"", "expected": "permanent" }, - { "name": "Mythos without a marked account", "text": "403 \"no_cyber_access_account\"", "expected": "permanent" }, - { "name": "context overflow", "text": "400 Prompt exceeds context window [orb:context_length_exceeded]", "expected": "permanent" }, - { "name": "late 429 rate limit is not retried here", "text": "429 \"rate_limited_or_quota\"", "expected": "permanent" }, - { "name": "mission error event payload", "text": "{\"message\":\"Transient upstream failure\",\"code\":\"provider_unavailable\",\"retryable\":true}", "expected": "transient:provider_unavailable" }, - { "name": "phrase alone is not a code", "text": "the server said: overloaded, no available channel, service unavailable", "expected": "none" }, - { "name": "a number in prose is not a status", "text": "tool failed: wrote 503 lines", "expected": "none" }, - { "name": "plain tool failure", "text": "tool failed: permission denied", "expected": "none" }, - { "name": "empty", "text": "", "expected": "none" } + { + "name": "new-api 503 no channel (status only)", + "text": "503 No available channel for model gemini-4-neon under group default", + "expected": "transient:provider_unavailable" + }, + { + "name": "Orb exhaustion body, OpenAI SDK prints the bare code", + "text": "502 \"server_unavailable\"", + "expected": "transient:provider_unavailable" + }, + { + "name": "model cooldown", + "text": "503 \"model_cooldown\"", + "expected": "transient:provider_unavailable" + }, + { + "name": "Anthropic overloaded via Claude Code", + "text": "API Error: 529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", + "expected": "transient:provider_unavailable" + }, + { + "name": "idle timeout code beats 504 status", + "text": "504 \"upstream_idle_timeout\"", + "expected": "transient:idle_timeout" + }, + { + "name": "stream cut frame message", + "text": "[orb:stream_incomplete] stream_incomplete: upstream stream ended without a finish_reason", + "expected": "transient:stream_incomplete" + }, + { + "name": "idle cut frame message", + "text": "[orb:upstream_idle_timeout] upstream_idle_timeout: the upstream provider stopped sending data before the reply finished", + "expected": "transient:idle_timeout" + }, + { + "name": "Pi driver exit", + "text": "[orb:harness_exited] Pi RPC process ended before agent_end", + "expected": "transient:harness_exited" + }, + { + "name": "tagged permanent beats 503", + "text": "503 [orb:no_provider_for_model] No configured provider account can serve model 'x'. It was not rerouted to another model.", + "expected": "permanent" + }, + { + "name": "Orb shape-1 permanent", + "text": "503 \"skipped_configuration\"", + "expected": "permanent" + }, + { + "name": "client/auth exhaustion", + "text": "502 \"client_or_auth_error\"", + "expected": "permanent" + }, + { + "name": "Mythos without a marked account", + "text": "403 \"no_cyber_access_account\"", + "expected": "permanent" + }, + { + "name": "context overflow", + "text": "400 [orb:context_length_exceeded] Prompt exceeds context window", + "expected": "permanent" + }, + { + "name": "late 429 rate limit is not retried here", + "text": "429 \"rate_limited_or_quota\"", + "expected": "permanent" + }, + { + "name": "mission error event payload", + "text": "{\"message\":\"Transient upstream failure\",\"code\":\"provider_unavailable\",\"retryable\":true}", + "expected": "transient:provider_unavailable" + }, + { + "name": "phrase alone is not a code", + "text": "the server said: overloaded, no available channel, service unavailable", + "expected": "none" + }, + { + "name": "a number in prose is not a status", + "text": "tool failed: wrote 503 lines", + "expected": "none" + }, + { + "name": "plain tool failure", + "text": "tool failed: permission denied", + "expected": "none" + }, + { + "name": "empty", + "text": "", + "expected": "none" + }, + { + "name": "a tagged message cut to 1000 characters by the harness driver keeps its code", + "text": "503 [orb:no_provider_for_model] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "expected": "permanent" + } ], "tag_body_cases": [ - { "name": "OpenAI-shaped Orb body gains the tag", "body": "{\"error\":{\"message\":\"No configured provider account can serve model 'x'.\",\"type\":\"service_unavailable\",\"code\":\"no_provider_for_model\"}}", "message": "No configured provider account can serve model 'x'. [orb:no_provider_for_model]" }, - { "name": "Anthropic overloaded gains the tag", "body": "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", "message": "Overloaded [orb:overloaded_error]" }, - { "name": "unregistered code is left alone", "body": "{\"error\":{\"message\":\"No available channel\",\"type\":\"new_api_error\",\"code\":\"\"}}", "message": null }, - { "name": "Orb shape-1 body already shows its code", "body": "{\"error\":\"server_unavailable\",\"message\":\"All providers failed\"}", "message": null }, - { "name": "already tagged", "body": "{\"error\":{\"message\":\"x [orb:model_cooldown]\",\"code\":\"model_cooldown\"}}", "message": null } + { + "name": "OpenAI-shaped Orb body gains the tag", + "body": "{\"error\":{\"message\":\"No configured provider account can serve model 'x'.\",\"type\":\"service_unavailable\",\"code\":\"no_provider_for_model\"}}", + "message": "[orb:no_provider_for_model] No configured provider account can serve model 'x'." + }, + { + "name": "Anthropic overloaded gains the tag", + "body": "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}", + "message": "[orb:overloaded_error] Overloaded" + }, + { + "name": "unregistered code is left alone", + "body": "{\"error\":{\"message\":\"No available channel\",\"type\":\"new_api_error\",\"code\":\"\"}}", + "message": null + }, + { + "name": "Orb shape-1 body already shows its code", + "body": "{\"error\":\"server_unavailable\",\"message\":\"All providers failed\"}", + "message": null + }, + { + "name": "already tagged", + "body": "{\"error\":{\"message\":\"x [orb:model_cooldown]\",\"code\":\"model_cooldown\"}}", + "message": null + } ] }