tokitai-dl 0.1.2

Vendored, additive bridge between tokitai-operator (verified DL kernels) and god-graph (DL model analysis). 100% non-invasive position was deliberately broken in 0.1.1 — see ADR-0004 for the rationale.
Documentation
//! # tokitai-dl
//!
//! An **additive** bridge crate connecting two deep-learning libraries:
//!
//! - `tokitai-operator` — a DL kernel compiler with selected formally checked
//!   kernels and theorem bindings. Edition 2024. Paper-artifact grade.
//! - `god-graph` — a DL model analysis toolbox (differentiable structures, VGI, CAD-LLM, Safetensors I/O). Edition 2021. v0.6.0-alpha.
//!
//! ## What this crate does
//!
//! Treats a `tokitai_operator::ir::SemanticGraph` (an operator DAG) as a
//! `god_graph::graph::Graph<String, ()>` so that god-graph's algorithm library
//! — BFS, DFS, topological sort, connected components, MST, PageRank, shortest
//! path, etc. — can inspect the operator DAG shape. This is graph analysis, not
//! a new proof that those algorithms or their outputs are formally verified.
//!
//! ## What this crate does NOT do
//!
//! - It does not modify `tokitai-operator` (paper-artifact claim boundary is closed).
//! - It does not modify `god-graph` (v0.6 release cadence is independent).
//! - It does not require a workspace root Cargo.toml.
//! - It does not bump either crate's edition.
//! - It does not re-export `pub use` from either crate; types are referenced by full path.
//!
//! ## Features
//!
//! | Feature     | Brings in                              |
//! |-------------|----------------------------------------|
//! | `graph`     | god-graph (default-features = false)   |
//! | `operator`  | tokitai-operator                        |
//! | `llm`       | god-graph Safetensors loader; use with `operator` for `llm_bridge` |
//!
//! Default features are empty. This is also the docs.rs-safe baseline because it
//! avoids optional dependencies such as the local-development
//! `tokitai-operator` sibling path dependency.
//!
//! ## Quickstart
//!
//! ```rust
//! # #[cfg(all(feature = "graph", feature = "operator"))]
//! use tokitai_dl::op_dag_graph::semantic_to_god_graph;
//! ```

#![deny(missing_docs)]
#![warn(rust_2018_idioms)]
#![forbid(unsafe_code)]

#[cfg(feature = "operator")]
pub mod op_dag_graph;

#[cfg(feature = "operator")]
pub mod sheaf_partitioner;

#[cfg(all(feature = "graph", feature = "operator"))]
pub mod witness_bridge;

#[cfg(all(feature = "graph", feature = "operator"))]
pub mod cad_bridge;

#[cfg(all(feature = "graph", feature = "operator"))]
pub mod lean_proof_bridge;

#[cfg(all(feature = "llm", feature = "operator"))]
pub mod llm_bridge;

/// Errors that the bridge's adapter functions can return.
///
/// The `Unsupported` arm is used when an input is a variant we
/// explicitly don't know how to map (currently reserved for
/// future `EditOperation::Custom` / `DefectType::Custom`).
/// The `Upstream` arm wraps a god-graph error (e.g. a failed
/// Safetensors load). The `Io` arm wraps a std::io error.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "graph", feature = "operator"))]
/// # fn demo() {
/// use tokitai_dl::BridgeError;
/// // Pattern-match on the variant to recover the underlying cause.
/// let err = BridgeError::Upstream("safetensors header malformed".to_string());
/// match err {
///     BridgeError::Unsupported(msg)  => println!("unsupported: {msg}"),
///     BridgeError::Upstream(msg)     => println!("upstream: {msg}"),
///     BridgeError::Io(msg)           => println!("io: {msg}"),
///     BridgeError::Context { source, context } => println!("{context}: {source}"),
/// }
/// # }
/// ```
#[cfg(all(feature = "graph", feature = "operator"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BridgeError {
    /// The input is a variant we explicitly don't know how to map.
    /// Currently reserved for `EditOperation::Custom` / `DefectType::Custom`.
    ///
    /// # No example
    ///
    /// `Unsupported` is the *catch-all* arm that the bridge reserves
    /// for future input variants. It is currently never constructed
    /// by the bridge, so a runnable example would have no realistic
    /// call site. Constructing one by hand (`BridgeError::Unsupported("x".into())`)
    /// is the intended downstream use, but adds no testable value
    /// over the source code itself.
    Unsupported(String),
    /// An upstream crate (god-graph) returned an error. The string
    /// carries the formatted upstream error so downstream code can
    /// still log / report it.
    Upstream(String),
    /// A `std::io` error occurred (file open, read, etc.). The
    /// string carries the formatted error.
    Io(String),
    /// An error wrapped with caller-supplied context. The `source` is the
    /// original error; the `context` is a human-readable string the caller
    /// attached (e.g. "while loading model 'foo.safetensors'").
    Context {
        /// The underlying error.
        source: Box<BridgeError>,
        /// Caller-supplied context. Displayed alongside the source in
        /// the outer Display impl.
        context: String,
    },
}

#[cfg(all(feature = "graph", feature = "operator"))]
impl BridgeError {
    /// Wrap `self` with caller-supplied context, producing a
    /// `Context { source, context }` variant. Useful for attaching
    /// high-level context (e.g. which file was being processed) to a
    /// lower-level error from one of the bridge adapters.
    pub fn with_context(self, ctx: impl Into<String>) -> Self {
        Self::Context {
            source: Box::new(self),
            context: ctx.into(),
        }
    }
}

#[cfg(all(feature = "graph", feature = "operator"))]
impl std::fmt::Display for BridgeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unsupported(msg) => write!(f, "unsupported bridge input: {msg}"),
            Self::Upstream(msg) => write!(f, "upstream error: {msg}"),
            Self::Io(msg) => write!(f, "io error: {msg}"),
            Self::Context { source, context } => write!(f, "{context}: {source}"),
        }
    }
}

#[cfg(all(feature = "graph", feature = "operator"))]
impl std::error::Error for BridgeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Context { source, .. } => Some(source.as_ref()),
            _ => None,
        }
    }
}

#[cfg(all(test, feature = "graph", feature = "operator"))]
mod bridge_error_tests {
    use super::BridgeError;
    #[test]
    fn context_wraps_underlying() {
        let inner = BridgeError::Upstream("header malformed".into());
        let outer = inner.with_context("while loading model 'foo.safetensors'");
        match &outer {
            BridgeError::Context { source, context } => {
                assert_eq!(context, "while loading model 'foo.safetensors'");
                assert!(matches!(source.as_ref(), BridgeError::Upstream(_)));
            }
            _ => panic!("expected Context variant"),
        }
        let chain: String = outer.to_string();
        assert!(chain.contains("loading model"));
        assert!(chain.contains("header malformed"));
    }
}