Skip to content

errors: thiserror across the repo, with variants that name the fault - #707

Open
tcoratger wants to merge 6 commits into
mainfrom
errors-thiserror-signatures
Open

tcoratger wants to merge 6 commits into
mainfrom
errors-thiserror-signatures

Conversation

@tcoratger

@tcoratger tcoratger commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Every error in the repo now derives thiserror::Error (as on riscv-exploration), with variants that carry what a reader needs to find the fault, and messages that say it in one sentence. crates/verifier alone keeps hand-written Display, so that it stays dependency-free.

  • Dependency: thiserror = { version = "2", default-features = false }, the same line as riscv-exploration. thiserror 2 is no_std and implements core::error::Error, which is std::error::Error.
  • AGENTS.md states the convention:
    • a variant carries the layer, index, size and limit involved;
    • public error enums are #[non_exhaustive];
    • a wrapper is either transparent with #[from], or "context: {0}" with no source, so no message prints twice;
    • public functions document their errors under # Errors.
  • No Result<_, String> is left outside private compiler internals that panic anyway, and no hand-written Display outside crates/verifier.

What changes, crate by crate

crate type before after (examples)
signatures LeanXmssSignError NoAdmissibleEncoding { layer, trials }: "no randomizer among the first 4294967296 makes layer 1's message digest a codeword"
LeanXmssVerifyError InvalidEncoding, InvalidMerklePath { layer, leaf_index }, { leaf_index }: "layer 0 of the signature at leaf 5: the message digest is not a codeword"
LeanSphincsSignError / VerifyError unit variants { layer, attempts }, { layer, counter }, RootMismatch { leaf_index }
pcs WhirConfigError (new) Result<_, String> in 10 functions 25 variants with the level, rate, shape, bits and target: "level 0: no Johnson slack gives 128-bit soundness at rate 1/2^1 with 2^6 message columns"
lean_compiler ParseError { line, kind } (new) Result<_, String> in 18 functions ~55 kinds such as Expected { expected, found }, Arity { call, expected, got }, InconsistentIndent { expected, got }: "line 6: inconsistent indentation: the block is at 8, this line at 10"
leanvm_core Fault WildPointer { value }, NotInK { what, value }, NotAGPower { what, value }, Witness(String) each names its cell: "loop bound in cell 812 is not a g-power in range (...)"; MissingWitnessStream, WitnessExhausted { name, entry, supplied }, WitnessLength { name, entry, expected, got }
Fault::MemoryTooLarge (new) an assert! whose doubling could wrap first { min_log_committed, max_log_mem }
ProveError, CpuError CpuError had no Display at all UnconstrainedReads { cells }, PublicInputNotDigest { half }, BytecodeNotPowerOfTwo { len }; Execution and Verifier transparent
rec_aggregation AggregationError MalformedSignerSet, NotCovered, TooLarge, InvalidChild(e), ChildOutOfRange TooManySigners { xmss, lean_sphincs, limit }, UnsortedSigners { scheme, index }, NotCovered { scheme, uncovered }, TooManyChildren { children, max }, TooManyClaims { slots, limit }, InvalidChild { child, error } ("child 1 is invalid: the snark did not verify: Merkle root mismatch"), ChildOutOfRange { child, log_committed, min, max } plus a new ChildOverCapacity, InvalidBlobSize { symbols, blob_symbols, max_blobs }
SnarkVerifyError, SnarkProveError hand-written transparent, still opaque (no From from internal types)
verifier VerifierError #[non_exhaustive], still hand-written

Messages fixed in passing:

  • ChildOutOfRange described only the size check, though it also covered a child too big for the guest's buffers; that case is now ChildOverCapacity.
  • InvalidBlobSize claimed at least one blob, though an empty payload is accepted.
  • The aggregate docs said an invalid raw signature makes it panic; it is refused.

Public API change: the variant shapes change, and the enums are #[non_exhaustive] from now on, so the next field is not a breaking change. One new public enum, SignatureScheme, names the scheme in signer errors.

Refusal conditions and their order are unchanged, except that MemoryTooLarge replaces an assert.

Checks

  • Tests that pin the new fields, each shown red before green:
    • one per signature scheme (a swapped layer turns it red);
    • pcs config_refusal_names_the_level_and_the_target;
    • lean_compiler a_parse_error_carries_its_line_and_the_values_that_disagree;
    • leanvm_core a_floor_past_the_largest_memory_is_an_error and prove_carries_the_execution_fault;
    • rec_aggregation an_unsorted_signer_set_names_the_first_claim_out_of_order.
  • cargo test --release on signatures, pcs, lean_compiler, leanvm_core, rec_aggregation, verifier and leanvm: pass.
  • Clippy -D warnings passes on every ISA of CI's matrix, cargo machete --with-metadata is clean, and the harness gate passes.
  • Independent reviews, two rounds: they spot-checked field values at raise sites, integer conversions, double printing, refusal order and the public API. Every finding is applied.
  • No performance change: the interpreter loop was touched, and the Execute program span measured 127 vs 130 ms median over 5 interleaved pairs, inside the noise.

🤖 Generated with Claude Code

Ubuntu and others added 6 commits November 6, 2026 13:49
The workspace takes `thiserror` 2 (no default features, as the riscv-exploration branch does), and AGENTS.md states riscv-exploration's convention: errors derive `thiserror::Error` (only `crates/verifier` hand-writes `Display`, to stay dependency-free), a variant carries what a reader needs to find the fault, public error enums are `#[non_exhaustive]`, a wrapper is either `transparent` with `#[from]` or `"context: {0}"` with no source so no message prints twice, and a public function documents its variants under `# Errors`.

The four signature errors are the first: each variant now says which layer refused and, when signing, how many randomizers or counters were tried.

  LeanXmssSignError::NoAdmissibleEncoding { layer, trials }
    "no randomizer among the first 4294967296 makes layer 1's message digest a codeword"
  LeanXmssVerifyError::InvalidEncoding { layer, leaf_index }, InvalidMerklePath { leaf_index }
    "layer 0 of the signature at leaf 17: the message digest is not a codeword"
  LeanSphincsSignError::NoAdmissibleEncoding { layer, attempts }
  LeanSphincsVerifyError::InadmissibleEncoding { layer, counter }, RootMismatch { leaf_index }

Public API change: the unit variants become struct variants and the enums `#[non_exhaustive]` (no caller in the workspace matched on them). `sign`, `verify` and `mock::sign` document their errors (and the mock's panic). A new test per scheme pins the exact variant and fields of a tampered counter or message and of a tampered top path node; swapping the layer at a raise site turns it red. The tests of signatures and leanvm pass (release), clippy -D warnings passes on the workspace, cargo machete finds nothing unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every refusal of the WHIR configuration (the rate check, the ladder derivation, the per-level Johnson search and the validation of a security config) was a `String`. They are now one `thiserror` enum, `pcs::whir::WhirConfigError` (`#[non_exhaustive]`), whose variants carry what was asked and what the limit is: the level, the rate, the shape, the computed soundness bits and the target.

  validate_log_inv_rate(5)
    before: "log_inv_rate must be in 1..=4, got 5"
    after:  RateOutOfRange { log_inv_rate: 5, min: 1, max: 4 }
            "log_inv_rate 5 is outside the supported range 1..=4"
  config_for_rate(12, 1)
    before: "L0: no eta candidate satisfies 128-bit Johnson/OOD soundness at rate 1/2^1"
    after:  NoJohnsonSlack { level: 0, log_inv_rate: 1, log_msg_cols: 6, target_bits: 128 }
            "level 0: no Johnson slack gives 128-bit soundness at rate 1/2^1 with 2^6 message columns"
  WhirSecurityConfig::validate, a level short of its query soundness
    after:  QueriesBelowTarget { level, bits, target, grinding_bits }
            "level {level}: queries give {bits:.2} bits, below the target of {target} less {grinding_bits} ground bits"

The other variants: WitnessBelowPacking, NothingAfterLaneFold, NoLevelFold, FoldBelowDomainReduction, PackingMismatch, FoldsMismatch, NoLevels, LaneFoldMismatch, LaneInterleavingMismatch, RateOne, SingleColumn, LevelDimensionMismatch, DomainReductionTooLarge, RateLadderMismatch, EtaOutOfRange, OodAtLaneLevel, MissingOod, OodBelowTarget, ProximityGapBelowTarget (with the analysis field's size), AlgebraicBelowTarget, LevelTargetBelowGlobal, ResidualMismatch, and the test-only BlockBelowQueries of the ad-hoc unique-decoding config.

Public API change: `config_for_rate`, `validate_log_inv_rate`, `WhirSecurityConfig::{validate, derive_config_with_log_inv_rate, to_config}` return `Result<_, WhirConfigError>` instead of `Result<_, String>`. Every caller in the workspace only displays, `expect`s or `is_err`s the error, so none changes. The checks, their order and every success path are unchanged.

Gate: fmt; clippy --release -D warnings on pcs, leanvm_core, keccak_gkr, rec_aggregation (all targets); tests --release of pcs, leanvm_core, keccak_gkr pass; cargo machete --with-metadata finds nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The zkDSL parser refused a program with a `String`, so a tool could only grep it and the line number was a "line N: " prefix spliced on by string inspection. It now returns `lean_compiler::ParseError` (`#[non_exhaustive]`), a struct holding the 1-based source line (`None` for a whole-program refusal such as a function defined twice, and for a lone `parse_const`) and a `ParseErrorKind`, a `#[non_exhaustive]` `thiserror` enum whose variants carry the offending text and, where the parser knows it, what it expected there and the values that disagree. The display keeps the `line N: ` prefix, so a guest author reads the same shape of message.

  inconsistent indentation
    before: "line 6: inconsistent indentation"
    after:  ParseError { line: Some(6), kind: InconsistentIndent { expected: 8, got: 10 } }
            "line 6: inconsistent indentation: the block is at 8, this line at 10"
  a malformed `for`
    before: "line 3: `for` needs `in`"
    after:  Expected { expected: "`in` in a `for`", found: "for i mul_range(1, 8):" }
            "line 3: expected `in` in a `for`, got `for i mul_range(1, 8):`"
  a wrong argument count
    before: "line 4: mul_range needs `start, stop`"
    after:  Arity { call: "mul_range", expected: "`start, stop`", got: 3 }
            "line 4: `mul_range` takes `start, stop`, got 3 argument(s)"
  a global constant whose value does not parse
    after:  InConstant { name, kind: Box<ParseErrorKind> }, printing "global constant `M`: <the inner message>" with no source, so nothing prints twice

The other variants name one refusal each (DuplicateConstant, ConstantOverflow, DuplicateFunction, ReservedFunctionName, StackBufParamTooLarge { function, size, max }, MulRangeBackwards { start, stop }, UnreachableStop { stop }, MatchGap { expected, got }, MissingOperand { op, side }, BufferTooLarge { buffer, size }, and so on). Most texts are unchanged; the "expected X, got Y" ones now quote the text found, and a header missing `)` reads "expected `)` after `(` in the function header, got `def f)(:`" (the one test substring that moved).

The column is not reported: the parser works on lines already trimmed and with constants substituted, so no column of the written source survives to the raise sites; the indentation variants carry the indents instead.

Public API change: `parse`, `parse_with_replacements` and `parse_const` return `Result<_, ParseError>` instead of `Result<_, String>`, and `ParseError` and `ParseErrorKind` are new exports. Callers in rec_aggregation, leanvm_core's tests and the CLI only `expect` or `unwrap` the result, so none changes; the suite's message checks now call `to_string()`. Only the error arms changed: every success path, and so the emitted bytecode, is untouched (the suite's determinism tests pass).

Gate: fmt; clippy --release -D warnings on lean_compiler, rec_aggregation, leanvm_core, leanvm, leanvm-cli (all targets); cargo test --release -p lean_compiler (130 pass, with a new test pinning the line and both indents of one refusal, which fails when the raise site reports the block's indent as the line's); cargo machete --with-metadata finds nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…he cell

`ExecError`, `Fault`, `ProveError` and `CpuError` derive `thiserror::Error` and are `#[non_exhaustive]`. Each fault now carries the cell it read where one exists, witness faults are typed rather than formatted strings, and `verify`'s one malformed-statement variant says which half or which length broke. `prove` wraps the interpreter's error as `#[error(transparent)]` and `#[from]`, and `verify` wraps `verifier::VerifierError` the same way.

Public API changes (variant shapes):

  Fault::WildPointer { value }             -> { cell, value }
    "DEREF pointer in cell 7 is not a small g-power: a wild pointer, or a failed range check (value 0:0:5)"
  Fault::NotInK { what, value }            -> { what, cell, value }
    "JUMP target in cell 3 is not a K-valued word (0:1:0)"
  Fault::NotCanonical { cell, value }      -> { cell, address, value }
    "KECCAK input cell 0 (address 2) is not a canonical 128-bit embedding (1:0:0)"
  Fault::BackSolveThroughZero              -> { operand }
    "cannot back-solve MUL through the zero operand in cell 4"
  Fault::Witness(String)                   -> MissingWitnessStream { name }, WitnessExhausted { name, needed, supplied }, WitnessLength { name, entry, expected, got }
    "witness stream `sigs` exhausted (needs entry 3, has 2)"
  Fault::MemoryTooLarge { min_log_committed, max_log_mem } (new)
    "a committed witness of 2^64 words needs more than 2^32 memory cells"
  ProveError::UnconstrainedReads(Vec<u32>) -> { cells }
  ProveError::InvalidRate message names the range: "log_inv_rate 5 is outside the supported 1..=4"
  CpuError::PublicInput                    -> PublicInputNotDigest { half }, BytecodeNotPowerOfTwo { len }
    "the bytecode has 7 instructions, not a power of two"
  CpuError now has a `Display` and an `Error` impl (it had neither); `Verifier` is transparent.

`ExecError` keeps its fields (`pc`, `site`, `fault`) and its message ("{fault} at pc {pc} (in {site})"). The other messages are unchanged but for the added cell.

One panic becomes an error: `execute` asserted that padding memory up to `Program::min_log_committed` stays within 2^MAX_LOG_MEM cells, and with a large enough floor the doubling could wrap first. The loop now stops past the limit and the run returns `Fault::MemoryTooLarge` at the halt pc. The refusal condition is the same.

`verify` checks the public input before the bytecode length, as the one combined condition evaluated them.

Tests: `keccak_requires_zero_third_limb` asserts the whole fault and pc, `a_floor_past_the_largest_memory_is_an_error` pins the new refusal (red with the check removed: the run succeeds), `prove_carries_the_execution_fault` pins that `prove` returns the interpreter's error unflattened, and `a_bytecode_that_is_not_a_power_of_two_is_an_error` asserts the length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e scheme and the limit

`AggregateVerifyError`, `AggregationError`, `SnarkVerifyError` and `SnarkProveError` derive `thiserror::Error`; the two enums are `#[non_exhaustive]`. The opaque wrappers are `#[error(transparent)]` over `verifier::VerifierError` and `leanvm_core::cpu::ProveError`, with `#[from]`. `AggregateVerifyError::Snark`, `AggregationError::InvalidChild` and `AggregationError::ProofError` add context ("the snark did not verify: {0}", "child {child} is invalid: {error}", "proving failed: {0}") and so declare no source, and the hand-written `source()` goes. A new `SignatureScheme` enum (leanXMSS, leanSPHINCS) names the list a claim error is about, and `leanvm` re-exports it.

Public API changes (variant shapes):

  AggregateVerifyError::MalformedSignerSet -> TooManySigners { xmss, lean_sphincs, limit }, UnsortedSigners { scheme, index }
    "the signer set holds 65535 leanXMSS and 1 leanSPHINCS claims, not below the limit of 65536"
    "leanXMSS claim 3 is not strictly above the one before it"
  AggregateVerifyError::MalformedClaim     -> PointLength { expected, got }, DeferredClaimMismatch
    "the deferred claim's point has 22 coordinates, the stacked bytecode 23 variables"
  AggregationError::InvalidChild(e)        -> InvalidChild { child, error }
    "child 1 is invalid: the snark did not verify: Merkle root mismatch"
  AggregationError::NotCovered             -> NotCovered { scheme, uncovered }
    "1 declared leanXMSS claim(s) are not covered by the children and raw signatures"
  AggregationError::MalformedRawSignature  -> MalformedRawSignature { scheme, layer }
    "a raw leanSPHINCS signature's layer 0 does not decode to a target-sum encoding"
  AggregationError::TooLarge               -> TooManyChildren { children, max }, TooManyClaims { slots, limit }
    "65536 claim slots, duplicates included, not below the limit of 65536"
  AggregationError::InvalidBlobSize { symbols } -> { symbols, blob_symbols, max_blobs }
    "16385 blob symbols are not a whole number of 16384-symbol blobs, at most 1024"
  AggregationError::ChildOutOfRange { log_committed } -> ChildOutOfRange { child, log_committed, min, max }, ChildOverCapacity { child, log_side, stream_len, max_log_side, max_stream_len }

`InvalidBlobSize` carries the payload's symbols, a blob's symbols and the blob limit: the field and the two constants the `lean_da::BlobSizeError` of #705 prints, so the two can be joined later. Its message drops "1..=": `aggregate` accepts an empty payload.

`ChildOutOfRange` used to cover two refusals, a committed size outside the guest's arms and a bus side or stream past its fixed buffers, with one message about the first; the second is now its own variant, so neither message can lie. The refusal conditions and their order are unchanged: the signer-set check still tests the count, then the leanXMSS order, then the leanSPHINCS order.

`aggregate`, `EthereumProof::verify`, `from_bytes` and `from_bytes_without_pubkeys` document their variants under `# Errors`.

Tests: the existing refusal tests assert the new fields (`max_keys_bound_is_exclusive`, `invalid_blob_sizes_are_rejected`, the narrowing test, both malformed raw signature tests), and `an_unsorted_signer_set_names_the_first_claim_out_of_order` pins the index (red with `index: i`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The two opaque wrappers, `SnarkVerifyError` and `SnarkProveError`, stay transparent but lose `#[from]`: the impls would have put `verifier::VerifierError` and `leanvm_core::cpu::ProveError` back into `leanvm`'s public API, which "no internal types in the API" removed, and nothing used them.
- `Fault::NotAGPower` names the cell it read, at all nine raise sites, as `NotInK` already did: "loop bound in cell 812 is not a g-power in range (...)".
- `f192()` reports 0 arguments, not 1, through the parser's own `arity` helper.
- `WitnessExhausted` counts `entry` from 0, as `WitnessLength` does.
- The rate refusal reads "log_inv_rate N is outside 1..=4" in leanvm_core, rec_aggregation and pcs alike.
- An operator label the splitters never emit is `unreachable!` rather than silently `%`.
- `VerifierError` is `#[non_exhaustive]` too (it stays hand-written: the verifier has no dependencies).

Message change not listed before: a global constant array's parse error reads "global constant `NAME`: ..." where it read "global constant array `NAME`: ...".

The tests of leanvm_core, lean_compiler, rec_aggregation, pcs, verifier and leanvm pass (release); clippy -D warnings passes on the workspace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tcoratger tcoratger changed the title errors: thiserror for the workspace, starting with the signature errors errors: thiserror across the repo, with variants that name the fault Nov 6, 2026
@tcoratger
tcoratger added this pull request to stack #714 November 6, 2026 13:15

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant