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
//! Bridge between god-graph's [`EditOperation`] and tokitai's
//! [`WitnessSample`].
//!
//! god-graph's `tensor::differentiable` module represents
//! neural-architecture-search edits (edge / node add / remove / modify)
//! as a discrete enum; tokitai's `verify::witnesses` module defines
//! `WitnessSample<T>` (label, observed, expected) as a first-class
//! sample type. The bridge turns each [`EditOperation`] into a
//! concrete `WitnessSample<i64>` that downstream code can pass through a
//! `ValuationAdditivityWitness` / `UltrametricWitness` /
//! `PrecisionPreservationWitness` batch.
//!
//! The numeric `observed` / `expected` values are produced by
//! hashing the edit fields with [`std::collections::hash_map::DefaultHasher`].
//! god-graph edits are *structural* — they don't carry natural numeric values
//! — so the hash is the only compact numeric value we can extract. The exact
//! hash value is not a stable public contract across Rust releases; use the
//! label and original edit fields for persistent identity. The bridge
//! deliberately writes `observed == expected`: the result is a traceability /
//! self-consistency sample, not evidence that an optimization edit is correct.
//! The label is a human-readable description of the edit kind.
//!
//! This module is gated on both the `graph` and the `operator`
//! features, since the witness is consumed by the tokitai verify
//! layer.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use god_graph::tensor::differentiable::{EdgeEditOp, EditOperation, NodeEditOp};
use tokitai_operator::verify::witnesses::WitnessSample;

use crate::BridgeError;

/// Convert a god-graph [`EditOperation`] into a traceability
/// [`WitnessSample<i64>`].
///
/// The label describes the edit; `observed` and `expected` are both
/// set to a hash of the edit fields, so the sample is always
/// self-consistent (i.e. `is_satisfied()` is always `true`). The value is
/// suitable for same-build traceability and deterministic replay of bridge
/// metadata, but it is not a stable cross-Rust-version identifier. It is not
/// a witness that an optimizer's proposed edit is mathematically correct.
///
/// # Errors
///
/// Always returns `Ok` for the variants of `EditOperation` that exist
/// in god-graph v0.6.0-alpha. We keep the `Result` return type so
/// future edits (e.g. `EditOperation::Custom`) can fail without
/// breaking the public signature.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "graph", feature = "operator"))]
/// # fn demo() {
/// use god_graph::tensor::differentiable::{EdgeEditOp, EditOperation};
/// use tokitai_dl::witness_bridge::traceability_sample_of_edit_op;
///
/// let edit = EditOperation::EdgeEdit(0, 1, EdgeEditOp::Add);
/// let witness = traceability_sample_of_edit_op(&edit).unwrap();
/// assert_eq!(witness.label, "edge_add:0->1");
/// // The bridge records a self-consistent traceability sample.
/// assert!(witness.is_satisfied());
/// # }
/// ```
pub fn traceability_sample_of_edit_op(
    edit: &EditOperation,
) -> Result<WitnessSample<i64>, BridgeError> {
    match edit {
        EditOperation::EdgeEdit(src, dst, kind) => {
            let label = match kind {
                EdgeEditOp::Add => format!("edge_add:{src}->{dst}"),
                EdgeEditOp::Remove => format!("edge_remove:{src}->{dst}"),
                EdgeEditOp::Modify => format!("edge_modify:{src}->{dst}"),
                _ => format!("edge_unknown:{src}->{dst}"),
            };
            let value = hash_fields(&[
                b"edge",
                kind.label().as_bytes(),
                &src.to_le_bytes(),
                &dst.to_le_bytes(),
            ]);
            Ok(WitnessSample::new(label, value, value))
        }
        EditOperation::NodeEdit(node_id, kind) => {
            let label = match kind {
                NodeEditOp::Add => format!("node_add:{node_id}"),
                NodeEditOp::Remove => format!("node_remove:{node_id}"),
                NodeEditOp::Modify => format!("node_modify:{node_id}"),
                _ => format!("node_unknown:{node_id}"),
            };
            let value = hash_fields(&[b"node", kind.label().as_bytes(), &node_id.to_le_bytes()]);
            Ok(WitnessSample::new(label, value, value))
        }
    }
}

/// Compatibility wrapper for [`traceability_sample_of_edit_op`].
///
/// The historical name is kept for callers that already depend on it.
/// Despite the `witness` wording, this function only emits a
/// traceability / self-consistency sample with `observed == expected`;
/// it does not verify optimization correctness.
///
/// # Errors
///
/// Same as [`traceability_sample_of_edit_op`].
pub fn witness_of_edit_op(edit: &EditOperation) -> Result<WitnessSample<i64>, BridgeError> {
    traceability_sample_of_edit_op(edit)
}

/// Hash a sequence of byte fields into an `i64`.
///
/// `DefaultHasher` is enough for same-build traceability samples, but its
/// algorithm is not a stable public contract across Rust releases. We do not
/// use `Hasher::finish()` directly because we want the result to fit in `i64`
/// for the `WitnessSample<i64>` payload.
fn hash_fields(fields: &[&[u8]]) -> i64 {
    let mut hasher = DefaultHasher::new();
    for f in fields {
        f.hash(&mut hasher);
    }
    let h = hasher.finish();
    // Resize u64 -> i64 by reinterpreting the bit pattern.
    i64::from_ne_bytes(h.to_ne_bytes())
}

trait EditKindLabel {
    fn label(&self) -> String;
}

impl EditKindLabel for EdgeEditOp {
    fn label(&self) -> String {
        match self {
            Self::Add => "add".to_string(),
            Self::Remove => "remove".to_string(),
            Self::Modify => "modify".to_string(),
            _ => "unknown".to_string(),
        }
    }
}

impl EditKindLabel for NodeEditOp {
    fn label(&self) -> String {
        match self {
            Self::Add => "add".to_string(),
            Self::Remove => "remove".to_string(),
            Self::Modify => "modify".to_string(),
            _ => "unknown".to_string(),
        }
    }
}