Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## What and why

<!-- What changes for the user, and why. Link the issue or incident. -->

## How it was tested

<!-- Tests added or run, with the commands. Performance changes: numbers before and after. -->

## Not verified live

<!--
Each item is something that only a running system can show (a deploy, a device, a real
provider). Every box must be closed before or right after merge, by one of:
- the deploy canaries (docs/operations/deploy-canaries.md): name the check, e.g. "canary: pi@remote";
- a named follow-up: an issue or PR link and who owns it.
Delete the section only when the change has nothing to verify live.
-->

- [ ] <!-- e.g. Codex on a remote node reaches a first turn after a Core restart — closed by: canary codex@remote -->

## Platforms

- [ ] Desktop
- [ ] iOS and Android at parity (or why not), version bumped
- [ ] Not user-visible
3 changes: 3 additions & 0 deletions .github/workflows/kernel-abi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,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
Expand Down
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,8 @@ published them (still running, docs-only push, no token) does it build with the
CI-parity Lean command (`orb-core`, `sandboxed-node`, `sandboxed-mcp`) and run
`orb-core-test` and `orb-node-test` itself; `ORB_DEPLOY_BUILD=1` forces that and
`ORB_DEPLOY_SELFTEST=1` re-runs the tests on CI binaries. Wait for the PR's Test
job before deploying a fresh merge. It then installs and health-checks `dev`, stages
job before deploying a fresh merge. It then 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`).
Expand Down
23 changes: 13 additions & 10 deletions docs/INFERENCE_PROTOCOLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<code>]` 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":"<code>","message":"…"}`, so an OpenAI-SDK client such as Pi
reports `"<status> \"<code>\""` 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)

Expand Down
42 changes: 42 additions & 0 deletions docs/operations/deploy-canaries.md
Original file line number Diff line number Diff line change
@@ -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 <deployed 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 <run>]`.

`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.
39 changes: 39 additions & 0 deletions docs/specs/fault-upstream.md
Original file line number Diff line number Diff line change
@@ -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": "<ORB_FAULT_UPSTREAM_KEY>",
"custom_models": [{"id": "fault-ok"}, {"id": "fault-503x1"}]}
```

and address models as `orbfault/<model>`.

## 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<n>` | `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-<ms>` | nothing for `<ms>` (max 600000), then `fault-ok` |
| `fault-late429-<ms>` | nothing for `<ms>`, then `429` with `Retry-After: 30` |

Tests: `ProxyRoutingTests.faultUpstreamFixture`. Live use: `docs/operations/deploy-canaries.md`.
56 changes: 56 additions & 0 deletions docs/specs/typed-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 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
`"<status> <error.message>"`, or `"<status> <JSON of error>"` when `error` is a string; Claude
Code as `API Error: <status> <body>`; 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:<code>]`:

- **Proxy responses.** Every `/v1/*` error response from Core whose `error` object names a
registered code (`error.code` or `error.type`) gets `[orb:<code>]` 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":"<code>"}` bodies need no tag:
the OpenAI SDK prints them as `<status> "<code>"`. 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

`ErrorClass.classifyText?` reads, in order: `[orb:<code>]` 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).
80 changes: 80 additions & 0 deletions lean/Orb/ErrorCode.lean
Original file line number Diff line number Diff line change
@@ -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:<code>]`,
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
9 changes: 6 additions & 3 deletions lean/Orb/PiHarness.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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`) -/
Expand Down Expand Up @@ -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!"{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
Expand Down
2 changes: 2 additions & 0 deletions lean/OrbCore/OrbCore.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 38 additions & 1 deletion lean/OrbCore/OrbCore/ConformanceRunner.lean
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import Orb.Kernel
import LeanSys.Spec
import OrbBin.Json
import OrbCore.ErrorClass

namespace OrbCore.ConformanceRunner

Expand Down Expand Up @@ -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:<reason>"`, `"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 <dir>`). -/
def runSharedFixtures (fixturesDir : String) : IO UInt32 := do
Expand Down Expand Up @@ -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`. -/
Expand Down
Loading
Loading