Skip to main content

clm_rust_core/fiber/
fibration.rs

1//! Grothendieck Fibration Category: Process -> MCard.
2//! Canonical Path: kernel/clm_rust_core/src/fiber/fibration.rs
3//! Deliverable: DEL-254-01
4//!
5//! Formalizes the total category `Process = \int P` over the base category `MCard`.
6//! Each object in Process is a pair `(M, F)` where:
7//! - `M \in MCard`: Immutable spatial carrier resting state in content-addressed storage (CAS).
8//! - `F \in Fiber(M)`: Active cordis execution fiber equipped with an unwinding stack of
9//!   reversible side-effects (`DisposableList`).
10//!
11//! Cartesian Lifting:
12//! Given an MCard mutation `f: M -> M'`, the Cartesian lift `lift(f): (M, F) -> (M', F')`
13//! unwinds the active fiber's side-effects in strict reverse LIFO order, producing a clean
14//! zero-residual state, before rebinding to the codomain `M'`.
15
16use crate::domain::{MCard, PCardDefinition};
17use crate::fiber::disposable::DisposableList;
18use std::sync::{Arc, Mutex};
19use std::time::{SystemTime, UNIX_EPOCH};
20
21/// Error types occurring during fibration operations or cartesian lifting.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum FibrationError {
24    DisposableUnwindError(Vec<String>),
25    LockError(String),
26    AxiomViolation(String),
27    CarrierMismatch(String),
28}
29
30impl std::fmt::Display for FibrationError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            Self::DisposableUnwindError(errs) => {
34                write!(f, "Fibration LIFO unwinding failed: {}", errs.join("; "))
35            }
36            Self::LockError(msg) => write!(f, "Fibration lock error: {}", msg),
37            Self::AxiomViolation(msg) => write!(f, "Fibration axiom violation: {}", msg),
38            Self::CarrierMismatch(msg) => write!(f, "Fibration carrier mismatch: {}", msg),
39        }
40    }
41}
42
43impl std::error::Error for FibrationError {}
44
45/// The Grothendieck Fibration trait \pi: Process -> MCard.
46pub trait Fibration<M = MCard, P = PCardDefinition>: Send + Sync {
47    /// Projection functor \pi(M, F) = M.
48    /// Maps an active process object to its immutable carrier MCard resting state.
49    fn project(&self) -> &M;
50
51    /// Returns the handle pointer for this process (if bound).
52    fn carrier_handle(&self) -> Option<&str>;
53
54    /// Executes the Cartesian lift of an MCard mutation f: M -> M'.
55    /// Unwinds existing fiber disposables in strict LIFO order, then updates the carrier.
56    fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError>;
57
58    /// Executes Cartesian lift of an alpha-conversion / handle rebinding.
59    fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError>;
60}
61
62/// An object in the Total Category Process (\int P).
63/// Represents the coupled pair (M, F) with thread-safe execution fiber state.
64#[derive(Clone)]
65pub struct ProcessObject<M = MCard, P = PCardDefinition> {
66    /// Immutable carrier MCard resting state.
67    pub carrier: M,
68    /// Optional handle pointer (e.g. "assets:notes.txt").
69    pub carrier_handle: Option<String>,
70    /// Thread-safe stack of reversible side-effects for zero residual state.
71    pub disposables: Arc<Mutex<DisposableList>>,
72    /// Optional PCard definition governing execution rules.
73    pub pcard: Option<P>,
74    /// Millisecond timestamp of process creation.
75    pub created_at: u64,
76    /// Whether the fiber is currently active.
77    pub is_active: bool,
78}
79
80impl<M> ProcessObject<M, PCardDefinition> {
81    /// Constructs a new ProcessObject coupled with an empty disposable stack.
82    pub fn new(carrier: M) -> Self {
83        let now = SystemTime::now()
84            .duration_since(UNIX_EPOCH)
85            .map(|d| d.as_millis() as u64)
86            .unwrap_or(0);
87
88        Self {
89            carrier,
90            carrier_handle: None,
91            disposables: Arc::new(Mutex::new(DisposableList::new())),
92            pcard: None,
93            created_at: now,
94            is_active: true,
95        }
96    }
97}
98
99impl<M, P> ProcessObject<M, P> {
100    /// Constructs a ProcessObject with an explicit PCard.
101    pub fn new_with_pcard(carrier: M, pcard: P) -> Self {
102        let now = SystemTime::now()
103            .duration_since(UNIX_EPOCH)
104            .map(|d| d.as_millis() as u64)
105            .unwrap_or(0);
106
107        Self {
108            carrier,
109            carrier_handle: None,
110            disposables: Arc::new(Mutex::new(DisposableList::new())),
111            pcard: Some(pcard),
112            created_at: now,
113            is_active: true,
114        }
115    }
116
117    /// Binds an initial handle pointer.
118    pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
119        self.carrier_handle = Some(handle.into());
120        self
121    }
122
123    /// Attaches an executable PCard definition.
124    pub fn with_pcard(mut self, pcard: P) -> Self {
125        self.pcard = Some(pcard);
126        self
127    }
128
129    /// Registers a reversible cleanup callback onto the fiber's LIFO stack.
130    pub fn register_disposable<F>(&self, cleanup: F) -> Result<(), FibrationError>
131    where
132        F: FnOnce() -> Result<(), String> + Send + 'static,
133    {
134        let mut list = self
135            .disposables
136            .lock()
137            .map_err(|e| FibrationError::LockError(e.to_string()))?;
138        list.push(cleanup);
139        Ok(())
140    }
141
142    /// Returns the number of registered disposers awaiting unwinding.
143    pub fn pending_disposers_count(&self) -> Result<usize, FibrationError> {
144        let list = self
145            .disposables
146            .lock()
147            .map_err(|e| FibrationError::LockError(e.to_string()))?;
148        Ok(list.len())
149    }
150
151    /// Unwinds all registered disposers in strict LIFO order.
152    pub fn unwind(&self) -> Result<(), FibrationError> {
153        let mut list = self
154            .disposables
155            .lock()
156            .map_err(|e| FibrationError::LockError(e.to_string()))?;
157        let active_list = std::mem::take(&mut *list);
158        active_list
159            .dispose()
160            .map_err(FibrationError::DisposableUnwindError)
161    }
162}
163
164impl<M: Send + Sync, P: Send + Sync> Fibration<M, P> for ProcessObject<M, P> {
165    fn project(&self) -> &M {
166        &self.carrier
167    }
168
169    fn carrier_handle(&self) -> Option<&str> {
170        self.carrier_handle.as_deref()
171    }
172
173    fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError> {
174        // Step 1: Unwind all fiber disposables in strict LIFO order
175        self.unwind()?;
176
177        // Step 2: Rebind carrier resting state
178        self.carrier = next_carrier;
179
180        // Step 3: Re-arm clean disposable list
181        let mut list = self
182            .disposables
183            .lock()
184            .map_err(|e| FibrationError::LockError(e.to_string()))?;
185        *list = DisposableList::new();
186        self.is_active = true;
187
188        Ok(())
189    }
190
191    fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError> {
192        self.carrier_handle = Some(new_handle.into());
193        Ok(())
194    }
195}
196
197/// Cartesian Lift Engine verifying Grothendieck fibration category laws.
198pub struct CartesianLiftEngine;
199
200impl CartesianLiftEngine {
201    /// Lifts mutation f: M -> M' on a process object.
202    pub fn lift_mutation<M: Send + Sync, P: Send + Sync>(
203        process: &mut ProcessObject<M, P>,
204        next_carrier: M,
205    ) -> Result<(), FibrationError> {
206        process.lift_mutation(next_carrier)
207    }
208
209    /// Lifts alpha-conversion handle rebind.
210    pub fn lift_handle_rebind<M: Send + Sync, P: Send + Sync>(
211        process: &mut ProcessObject<M, P>,
212        new_handle: impl Into<String>,
213    ) -> Result<(), FibrationError> {
214        process.lift_handle_rebind(new_handle)
215    }
216}
217
218/// Validates Grothendieck fibration axioms:
219/// 1. Base Projection Commutativity: \pi(lift(f)) == cod(f).
220/// 2. Zero Residual State: Fiber disposables after lift == 0.
221pub fn verify_fibration_axioms<M: PartialEq + Send + Sync, P: Send + Sync>(
222    initial: &ProcessObject<M, P>,
223    lifted: &ProcessObject<M, P>,
224    target_carrier: &M,
225) -> Result<(), FibrationError> {
226    // Axiom 1: Base projection commutativity
227    if lifted.project() != target_carrier {
228        return Err(FibrationError::AxiomViolation(
229            "Projection commutativity failed: pi(lift(f)) != cod(f)".to_string(),
230        ));
231    }
232
233    // Axiom 2: Zero residual state after mutation lift
234    if lifted.pending_disposers_count()? != 0 {
235        return Err(FibrationError::AxiomViolation(
236            "Zero-residual state failed: lifted fiber retained pending disposers".to_string(),
237        ));
238    }
239
240    // Verify initial is unaffected
241    let _ = initial.project();
242
243    Ok(())
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::domain::{MCard, MCardPayload};
250    use crate::types::AgentDid;
251
252    #[test]
253    fn test_fibration_projection_and_lifo_unwind() {
254        let author = AgentDid::new("did:key:alice").unwrap();
255        let card1 = MCard::new(
256            "mcard:test/1",
257            MCardPayload::Text("Initial".to_string()),
258            author.clone(),
259            1,
260        );
261        let card2 = MCard::new(
262            "mcard:test/2",
263            MCardPayload::Text("Updated".to_string()),
264            author,
265            2,
266        );
267
268        let mut process = ProcessObject::new(card1.clone()).with_handle("assets:doc.md");
269
270        // Verify initial projection \pi(M, F) = M
271        assert_eq!(process.project().uri, "mcard:test/1");
272        assert_eq!(process.carrier_handle(), Some("assets:doc.md"));
273
274        // Register 3 disposables that push their indices into an unwinding log
275        let log = Arc::new(Mutex::new(Vec::new()));
276        let log1 = log.clone();
277        let log2 = log.clone();
278        let log3 = log.clone();
279
280        process
281            .register_disposable(move || {
282                log1.lock().unwrap().push(1);
283                Ok(())
284            })
285            .unwrap();
286
287        process
288            .register_disposable(move || {
289                log2.lock().unwrap().push(2);
290                Ok(())
291            })
292            .unwrap();
293
294        process
295            .register_disposable(move || {
296                log3.lock().unwrap().push(3);
297                Ok(())
298            })
299            .unwrap();
300
301        assert_eq!(process.pending_disposers_count().unwrap(), 3);
302
303        // Execute Cartesian lift of mutation f: card1 -> card2
304        process.lift_mutation(card2.clone()).unwrap();
305
306        // 1. Verify projection commutativity: \pi(lift(f)) == card2
307        assert_eq!(process.project().uri, "mcard:test/2");
308
309        // 2. Verify strict LIFO unwinding order [3, 2, 1]
310        let recorded = log.lock().unwrap().clone();
311        assert_eq!(recorded, vec![3, 2, 1], "Unwinding order must be strict reverse LIFO");
312
313        // 3. Verify zero residual state in fiber
314        assert_eq!(process.pending_disposers_count().unwrap(), 0);
315
316        // Test axiom verification helper
317        verify_fibration_axioms(&ProcessObject::new(card1), &process, &card2).unwrap();
318    }
319
320    #[test]
321    fn test_handle_rebinding() {
322        let author = AgentDid::new("did:key:alice").unwrap();
323        let card = MCard::new(
324            "mcard:test/rebind",
325            MCardPayload::Text("Hello".to_string()),
326            author,
327            1,
328        );
329
330        let mut process = ProcessObject::new(card);
331        assert_eq!(process.carrier_handle(), None);
332
333        process.lift_handle_rebind("assets:renamed.txt").unwrap();
334        assert_eq!(process.carrier_handle(), Some("assets:renamed.txt"));
335    }
336}