Skip to main content

bb_runtime/contracts/
codec.rs

1//! `bb::Codec` — bidirectional storage-type bridge.
2//!
3//! Each method takes the engine's `&mut RuntimeResourceRef<'_>` ctx
4//! plus a [`CompletionHandle`] AND returns [`ContractResponse`]. See
5//! [`crate::contracts::index`] for the sync (Now) vs async (Later)
6//! semantics.
7//!
8//! `ctx` exposes `ctx.dependency::<T>("<slot>")` so a codec impl can
9//! reach any concrete declared in `#[depends(...)]` (e.g. a Backend
10//! that materializes a quantizer's calibration tensors on-device).
11//!
12//! Library makers implement `Codec` when they want to bridge two
13//! positions in the storage tree (f32 ↔ u8 quantization, f32 ↔ f16
14//! half-precision lift, f32 ↔ opaque-bytes compression, …).
15
16use crate::completion::{CompletionHandle, ContractResponse};
17use crate::runtime::RuntimeResourceRef;
18
19/// User-facing Contract trait for a typed in/out storage codec.
20pub trait Codec: Send + Sync {
21    /// Input storage. Position-in-tree declaration via [`bb_ir::types::Storage`].
22    type In: ?Sized + bb_ir::types::Storage;
23
24    /// Output storage. Different position in the tree from `In`
25    /// (otherwise the codec is identity and the author should remove it).
26    type Out: ?Sized + bb_ir::types::Storage;
27
28    /// Library-maker-defined error type.
29    type Error: std::error::Error + std::fmt::Display + Send + Sync + 'static;
30
31    /// Optional training pass — quantizers need scale/zero-point
32    /// calibration, PQ codebooks need k-means, plain dtype casts
33    /// (f32 ↔ f16) skip this. Default returns `Now(Ok(()))`.
34    fn train(
35        &mut self,
36        _ctx: &mut RuntimeResourceRef<'_>,
37        _samples: &[&Self::In],
38        _completion: CompletionHandle<(), Self::Error>,
39    ) -> ContractResponse<(), Self::Error> {
40        ContractResponse::Now(Ok(()))
41    }
42
43    /// `In → Out`. `ctx` is the per-dispatch runtime surface; impls
44    /// reach their declared `#[depends(...)]` siblings through
45    /// [`RuntimeResourceRef::dependency`].
46    fn encode(
47        &self,
48        ctx: &mut RuntimeResourceRef<'_>,
49        input: &Self::In,
50        completion: CompletionHandle<Box<Self::Out>, Self::Error>,
51    ) -> ContractResponse<Box<Self::Out>, Self::Error>;
52
53    /// `Out → In`. Lossy codecs implement the best-effort inverse.
54    /// `ctx` is the per-dispatch runtime surface; impls reach their
55    /// declared `#[depends(...)]` siblings through
56    /// [`RuntimeResourceRef::dependency`].
57    fn decode(
58        &self,
59        ctx: &mut RuntimeResourceRef<'_>,
60        encoded: &Self::Out,
61        completion: CompletionHandle<Box<Self::In>, Self::Error>,
62    ) -> ContractResponse<Box<Self::In>, Self::Error>;
63}
64