CodeSampleX

Exemple

anyhow 1.0.104: Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions

Échantillon vérifié pour cargo anyhow 1.0.104: Downcast concrete error types and custom context through anyhow::Error without losing concrete types across…

sha256:111c5fe00d1de4f527fc0ae3c444b12d048965ac957370eb4630a2a4a08b239f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré rust linux x64 rust rust cargo

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-16
rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18

Cas

HOW
Objectif
Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions
Paquets
Symboles
  • anyhow::Error::downcast_ref
  • anyhow::Error::downcast_mut
  • anyhow::Error::downcast
  • anyhow::Error::from_boxed
  • anyhow::Error::is
  • anyhow::Context::context
Environnement
rust
Créé
2026-08-16T07:54:47Z

Contrat

  1. assert converting Box<dyn StdError> via from_boxed prevents recovering the concrete error with downcast_ref because TypeId tracks the boxed trait object
  2. assert converting a concrete StdError via From/into enables downcast_ref and is::<E>
  3. assert anyhow::Error::downcast_ref recursively searches through all attached context frames to find the root error
  4. assert std::error::Error::downcast_ref called via Deref on &dyn StdError fails on context-wrapped errors because std downcast does not traverse causes
  5. assert downcast_ref recovers custom context structs implementing Display and Debug even if they do not implement std::error::Error
  6. assert downcast_ref and downcast_mut on duplicate context types target the outermost most recently attached context frame
  7. assert downcast by value extracts the root error out of context layers, while mismatched downcast preserves the entire context chain intact
  8. assert context on Option None creates a root error with source None, whereas context on Result Err chains the previous error as source

Fichiers

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • csx.json
  • src/lib.rs

Télécharger l’artefact source (tar.gz)

Code source

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"

[[package]]
name = "cargo-anyhow-api"
version = "0.1.0"
dependencies = [
 "anyhow",
]
Cargo.toml
[package]
name = "cargo-anyhow-api"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1.0.104"
NOTES.md
# Notes

## Prior Sample Found
`search_known_solution` returned existing published sample `sha256:709971847660bb4f230ee832aa66da4263481bd8d5e0a498178ee3b789c53404` ("Handle errors in a Rust application with anyhow: attach context, keep the cause chain, log it without losing the cause, and recover the concrete error"), which focused on `{}` vs `{:#}` Display formatting loss, `chain()` iteration order, and basic `thiserror` downcasting.

## What a Model Would Have Written Instead
A competent model would assume `anyhow::Error::from_boxed(boxed_dyn_err).downcast_ref::<ConcreteError>()` recovers the concrete error from boxed trait objects returned by external libraries, and that calling `downcast_ref::<ConcreteError>()` on `&dyn std::error::Error` (via `anyhow::Error`'s `Deref` coercion) searches the cause chain just like `anyhow::Error::downcast_ref`.

## How the Wrong Version Fails
Silently at runtime: `downcast_ref::<ConcreteError>()` returns `None` without any compile warning or panic, silently disabling error recovery branches and fallback handling while passing compilation.
csx.json
{"case":{"caseId":"case:sha256:364d3ddc0312b1f6ceff0b194764a1226e2700090a99d6b9afe439c61a559717","contract":["assert converting Box\u003cdyn StdError\u003e via from_boxed prevents recovering the concrete error with downcast_ref because TypeId tracks the boxed trait object","assert converting a concrete StdError via From/into enables downcast_ref and is::\u003cE\u003e","assert anyhow::Error::downcast_ref recursively searches through all attached context frames to find the root error","assert std::error::Error::downcast_ref called via Deref on \u0026dyn StdError fails on context-wrapped errors because std downcast does not traverse causes","assert downcast_ref recovers custom context structs implementing Display and Debug even if they do not implement std::error::Error","assert downcast_ref and downcast_mut on duplicate context types target the outermost most recently attached context frame","assert downcast by value extracts the root error out of context layers, while mismatched downcast preserves the entire context chain intact","assert context on Option None creates a root error with source None, whereas context on Result Err chains the previous error as source"],"goal":"Downcast concrete error types and custom context through anyhow::Error without losing concrete types across Box trait object boundaries or Deref std::error::Error coercions","kind":"HOW","packages":["pkg:cargo/anyhow@1.0.104"],"schemaVersion":1,"symbols":["anyhow::Error::downcast_ref","anyhow::Error::downcast_mut","anyhow::Error::downcast","anyhow::Error::from_boxed","anyhow::Error::is","anyhow::Context::context"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/anyhow@1.0.104"],"schemaVersion":1,"symbols":["anyhow::Error::downcast_ref","anyhow::Error::downcast_mut","anyhow::Error::downcast","anyhow::Error::from_boxed","anyhow::Error::is","anyhow::Context::context"],"verifierAdapter":"cargo@1"}
src/lib.rs
use std::error::Error as StdError;
use std::fmt;
use anyhow::{Context, Result};

/// Concrete error type implementing `std::error::Error`.
#[derive(Debug, PartialEq, Eq)]
pub struct QueryError {
    pub query_id: u64,
    pub reason: &'static str,
}

impl fmt::Display for QueryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "query {} failed: {}", self.query_id, self.reason)
    }
}

impl StdError for QueryError {}

/// Custom metadata / diagnostic context that implements `Display` and `Debug`
/// but deliberately DOES NOT implement `std::error::Error`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceMetadata {
    pub trace_id: &'static str,
    pub attempt: u32,
}

impl fmt::Display for TraceMetadata {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "trace_id={}, attempt={}", self.trace_id, self.attempt)
    }
}

/// Demonstrates how anyhow interacts with standard trait objects,
/// nested context chains, and downcasting semantics.
pub fn execute_query(id: u64) -> Result<String> {
    if id == 0 {
        return Err(QueryError {
            query_id: 0,
            reason: "invalid query id",
        })
        .context("validating query input")
        .context("dispatching execution");
    }
    Ok(format!("result for {id}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    #[test]
    fn test_from_boxed_vs_direct_into_downcast_trap() {
        // TRAP 1: When receiving Box<dyn StdError + Send + Sync + 'static> (e.g. from generic crates),
        // callers use anyhow::Error::from_boxed. But from_boxed wraps the trait object itself.
        // Calling downcast_ref::<QueryError>() SILENTLY returns None because the internal TypeId
        // is for Box<dyn StdError + Send + Sync>, not QueryError.
        let concrete = QueryError {
            query_id: 42,
            reason: "connection reset",
        };
        let boxed: Box<dyn StdError + Send + Sync + 'static> = Box::new(concrete);
        let err_from_boxed = anyhow::Error::from_boxed(boxed);

        // A naive caller expects to recover QueryError from the anyhow::Error, but it fails:
        assert!(!err_from_boxed.is::<QueryError>());
        assert!(err_from_boxed.downcast_ref::<QueryError>().is_none());

        // In contrast, direct conversion via From/into preserves the concrete TypeId:
        let err_from_concrete: anyhow::Error = QueryError {
            query_id: 42,
            reason: "connection reset",
        }
        .into();
        assert!(err_from_concrete.is::<QueryError>());
        assert_eq!(
            err_from_concrete.downcast_ref::<QueryError>(),
            Some(&QueryError {
                query_id: 42,
                reason: "connection reset"
            })
        );
    }

    #[test]
    fn test_anyhow_downcast_traversal_vs_stderror_deref_downcast() {
        // TRAP 2: anyhow::Error::downcast_ref traverses the entire cause chain through attached contexts.
        // However, anyhow::Error implements Deref<Target = dyn StdError + Send + Sync + 'static>.
        // When passed to functions taking &dyn StdError, calling std::error::Error::downcast_ref
        // checks ONLY the outermost context frame and does NOT traverse causes.
        let err = execute_query(0).unwrap_err();

        // anyhow::Error::downcast_ref traverses context layers and successfully finds the root QueryError:
        let found_anyhow = err.downcast_ref::<QueryError>();
        assert_eq!(
            found_anyhow,
            Some(&QueryError {
                query_id: 0,
                reason: "invalid query id"
            })
        );

        // std::error::Error::downcast_ref via Deref looks ONLY at the outer context frame and returns None:
        let std_dyn: &(dyn StdError + 'static) = &*err;
        let found_std = std_dyn.downcast_ref::<QueryError>();
        assert!(found_std.is_none());
    }

    #[test]
    fn test_non_error_context_payload_downcast_and_precedence() {
        // TRAP 3: Context attached via .context(C) only requires C: Display + Debug + Send + Sync + 'static.
        // It does NOT require std::error::Error, and custom context structs CAN be downcasted.
        // When multiple contexts of the same type are chained, downcast_ref and downcast_mut resolve
        // to the OUTERMOST (most recently attached) frame, not the first one.
        let base_err = QueryError {
            query_id: 10,
            reason: "timeout",
        };
        let mut err = anyhow::Error::from(base_err)
            .context(TraceMetadata {
                trace_id: "inner-trace",
                attempt: 1,
            })
            .context(TraceMetadata {
                trace_id: "outer-trace",
                attempt: 2,
            });

        // downcast_ref returns the outermost context frame:
        assert_eq!(
            err.downcast_ref::<TraceMetadata>(),
            Some(&TraceMetadata {
                trace_id: "outer-trace",
                attempt: 2,
            })
        );

        // downcast_mut modifies the outermost matching context frame in place:
        if let Some(meta) = err.downcast_mut::<TraceMetadata>() {
            meta.attempt = 3;
        }
        assert_eq!(
            err.downcast_ref::<TraceMetadata>(),
            Some(&TraceMetadata {
                trace_id: "outer-trace",
                attempt: 3,
            })
        );

        // Root error is still accessible despite multiple non-error context layers:
        assert_eq!(
            err.downcast_ref::<QueryError>(),
            Some(&QueryError {
                query_id: 10,
                reason: "timeout"
            })
        );
    }

    #[test]
    fn test_downcast_by_value_extracts_root_and_preserves_on_mismatch() {
        // TRAP 4: err.downcast::<E>() extracts the root error by value, consuming all context wrappers.
        // If the downcast fails (mismatched type), the returned Err variant retains the FULL original
        // error with all context frames intact.
        let err = execute_query(0).unwrap_err();

        // Failed downcast returns the full error intact:
        let mismatch_res = err.downcast::<io::Error>();
        assert!(mismatch_res.is_err());
        let preserved_err = mismatch_res.unwrap_err();
        assert_eq!(preserved_err.chain().count(), 3);
        assert_eq!(preserved_err.to_string(), "dispatching execution");

        // Successful downcast unwraps the root error:
        let success_res = preserved_err.downcast::<QueryError>();
        assert!(success_res.is_ok());
        let root = success_res.unwrap();
        assert_eq!(
            root,
            QueryError {
                query_id: 0,
                reason: "invalid query id"
            }
        );
    }

    #[test]
    fn test_option_context_source_asymmetry() {
        // TRAP 5: Context on Option<T>::None creates a standalone error with no underlying cause.
        // err.source() is None and chain().count() is 1.
        // In contrast, Context on Result::Err(E) wraps the error, making source() Some(E) and chain().count() 2.
        let opt: Option<u64> = None;
        let opt_err = opt.context("missing config key").unwrap_err();
        assert!(opt_err.source().is_none());
        assert_eq!(opt_err.chain().count(), 1);
        assert_eq!(opt_err.to_string(), "missing config key");

        let res: std::result::Result<u64, QueryError> = Err(QueryError {
            query_id: 1,
            reason: "aborted",
        });
        let res_err = res.context("missing config key").unwrap_err();
        assert!(res_err.source().is_some());
        assert_eq!(res_err.chain().count(), 2);
        assert_eq!(res_err.to_string(), "missing config key");
        assert_eq!(
            res_err.source().unwrap().to_string(),
            "query 1 failed: aborted"
        );
    }
}

Seeder d'origine

csx-seed