qualia_audio/models/loader/fail_closed.rs
1//! THE fail-closed gate (ADR 007) — every learned head routes weight access through this
2//! (AU-LEARNED).
3//!
4//! The invariant this module enforces: **with no weights, a learned head returns
5//! `AudioError::BackendUnavailable` — it never fabricates an output.** The gate is a plain,
6//! auditable function so the fail-closed decision is impossible to miss or bypass: a head holds a
7//! [`WeightState`], and the only sanctioned way to reach the weights is [`require_weights`], which
8//! is `Err(BackendUnavailable)` whenever the state is `Absent`.
9
10use super::weight_file::WeightBlob;
11use crate::types::AudioError;
12
13/// Whether a learned head has usable weights. Default construction is `Absent` (fail closed).
14#[derive(Debug, Clone, PartialEq, Default)]
15pub enum WeightState {
16 /// No weights loaded — the head must abstain.
17 #[default]
18 Absent,
19 /// Weights present — the reference forward pass may run.
20 Loaded(WeightBlob),
21}
22
23impl WeightState {
24 #[inline]
25 /// `true` when loaded.
26 pub fn is_loaded(&self) -> bool {
27 matches!(self, WeightState::Loaded(_))
28 }
29}
30
31/// The fail-closed gate. Returns the loaded weights, or `BackendUnavailable` when absent.
32///
33/// This is the single choke point ADR 007 requires: a head that cannot obtain weights here must
34/// propagate the error and produce nothing.
35#[inline]
36pub fn require_weights(state: &WeightState) -> Result<&WeightBlob, AudioError> {
37 match state {
38 WeightState::Loaded(blob) => Ok(blob),
39 WeightState::Absent => Err(AudioError::BackendUnavailable),
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::super::weight_file::make_blob;
46 use super::*;
47
48 #[test]
49 fn absent_fails_closed() {
50 let state = WeightState::Absent;
51 assert_eq!(require_weights(&state), Err(AudioError::BackendUnavailable));
52 assert!(!state.is_loaded());
53 }
54
55 #[test]
56 fn default_is_absent() {
57 assert_eq!(WeightState::default(), WeightState::Absent);
58 }
59
60 #[test]
61 fn loaded_is_ok() {
62 let blob = make_blob(vec![1], vec![0.5]);
63 let state = WeightState::Loaded(blob.clone());
64 assert_eq!(require_weights(&state), Ok(&blob));
65 assert!(state.is_loaded());
66 }
67}