Skip to main content

clm_rust_core/layer1/
transition_loader.rs

1//! Layer 1: In-Process PCard-to-Fiber Transition Loader & Dispatcher (CRD-02).
2//! Canonical Path: kernel/clm_rust_core/src/layer1/transition_loader.rs
3//!
4//! Implements:
5//! - PCard resolution from SQLite CAS storage (layer0_function_memory.mcard.db)
6//! - In-process native execution of Layer 0 functions (e.g. create_record)
7//! - Execution governed by Cordis 5-state Fiber lifecycle (Pending -> Loading -> Active -> Unloading -> Disposed)
8//! - Strict Bipartite net invariant enforcement
9//! - Token decrement from inputs and increment to outputs (x^T ยท D = 0)
10//! - Sub-millisecond execution latency
11//! - Zero token leakage on failure
12
13use std::collections::{HashMap, HashSet};
14use std::path::PathBuf;
15use std::time::Instant;
16
17use crate::fiber::{Fiber, FiberState};
18use crate::layer0::mcard_record::{create_record, MCardRecord};
19use crate::layer1::types::{Marking, PetriNet};
20
21/// Tripartite PCard data loaded from CAS storage.
22#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
23pub struct PcardData {
24    pub function_id: String,
25    pub pcard_hash: String,
26    pub abstract_face: serde_json::Value,
27    pub concrete_face: serde_json::Value,
28    pub balanced_face: serde_json::Value,
29}
30
31/// Execution outcome for an in-process CPN transition firing.
32#[derive(Debug, Clone)]
33pub struct TransitionExecutionOutcome {
34    pub transition_id: String,
35    pub function_id: String,
36    pub success: bool,
37    pub record_hash: Option<String>,
38    pub latency_ms: f64,
39    pub state_history: Vec<FiberState>,
40    pub error: Option<String>,
41}
42
43/// In-process PCard-to-Fiber Transition Loader.
44pub struct TransitionLoader {
45    pub pool_db_path: PathBuf,
46}
47
48impl TransitionLoader {
49    pub fn new(pool_db_path: impl Into<PathBuf>) -> Self {
50        Self {
51            pool_db_path: pool_db_path.into(),
52        }
53    }
54
55    pub fn default_pool() -> Self {
56        let candidates = [
57            PathBuf::from("clm/db/layer0_function_memory.mcard.db"),
58            PathBuf::from("../../db/layer0_function_memory.mcard.db"),
59            PathBuf::from("../db/layer0_function_memory.mcard.db"),
60        ];
61        let found = candidates.into_iter().find(|p| p.exists()).unwrap_or_else(|| {
62            PathBuf::from("clm/db/layer0_function_memory.mcard.db")
63        });
64        Self::new(found)
65    }
66
67    /// Resolves tripartite PCard by handle from SQLite CAS database.
68    pub fn resolve_pcard(&self, function_id: &str) -> Result<PcardData, String> {
69        if !self.pool_db_path.exists() {
70            return Err(format!("Function memory DB not found: {:?}", self.pool_db_path));
71        }
72
73        let conn = rusqlite::Connection::open_with_flags(
74            &self.pool_db_path,
75            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
76        )
77        .map_err(|e| format!("Failed to open DB: {}", e))?;
78
79        let mut stmt = conn
80            .prepare("SELECT current_hash FROM handle_registry WHERE handle = ?")
81            .map_err(|e| format!("Prepare error: {}", e))?;
82
83        let mut hash_res: Result<String, _> = stmt.query_row([function_id], |row| row.get(0));
84
85        // Alias fallback if handle is one of the dual names
86        if hash_res.is_err() {
87            if function_id == "urn:mcard:cas/mcard/create-record" {
88                hash_res = stmt.query_row(["urn:mcard:cas/mcard-record/create-record"], |row| row.get(0));
89            } else if function_id == "urn:mcard:cas/mcard-record/create-record" {
90                hash_res = stmt.query_row(["urn:mcard:cas/mcard/create-record"], |row| row.get(0));
91            }
92        }
93
94        let pcard_hash = hash_res.map_err(|_| format!("Function handle '{}' not found in handle_registry", function_id))?;
95
96        let mut card_stmt = conn
97            .prepare("SELECT content FROM card WHERE hash = ?")
98            .map_err(|e| format!("Card prepare error: {}", e))?;
99
100        let card_raw: Vec<u8> = card_stmt
101            .query_row([&pcard_hash], |row| row.get(0))
102            .map_err(|e| format!("Root card '{}' missing: {}", pcard_hash, e))?;
103
104        let root_val: serde_json::Value = serde_json::from_slice(&card_raw)
105            .map_err(|e| format!("Failed to parse root card JSON: {}", e))?;
106
107        let faces = root_val
108            .get("payload")
109            .and_then(|p| p.get("faces"))
110            .and_then(|f| f.as_object())
111            .ok_or_else(|| "PCard missing required faces object".to_string())?;
112
113        let mut resolved_faces: HashMap<String, serde_json::Value> = HashMap::new();
114
115        for (aspect, q_hash_val) in faces {
116            let q_hash = q_hash_val.as_str().unwrap_or("");
117            let bare_hash = if let Some((_, h)) = q_hash.split_once(':') {
118                h
119            } else {
120                q_hash
121            };
122
123            if let Ok(f_raw) = card_stmt.query_row([bare_hash], |row| row.get::<_, Vec<u8>>(0)) {
124                if let Ok(f_val) = serde_json::from_slice(&f_raw) {
125                    resolved_faces.insert(aspect.clone(), f_val);
126                }
127            }
128        }
129
130        Ok(PcardData {
131            function_id: function_id.to_string(),
132            pcard_hash,
133            abstract_face: resolved_faces.remove("abstract").unwrap_or(serde_json::Value::Null),
134            concrete_face: resolved_faces.remove("concrete").unwrap_or(serde_json::Value::Null),
135            balanced_face: resolved_faces.remove("balanced").unwrap_or(serde_json::Value::Null),
136        })
137    }
138
139    /// Invokes create_record directly in-process.
140    pub fn invoke_create_record(
141        &self,
142        content: &[u8],
143        algorithm: Option<&str>,
144    ) -> Result<MCardRecord, String> {
145        create_record(content, algorithm)
146    }
147
148    /// Validates that the PetriNet strictly satisfies bipartite invariants.
149    pub fn validate_bipartite(net: &PetriNet) -> Result<(), String> {
150        let place_ids: HashSet<&str> = net.places.iter().map(|p| p.id.as_str()).collect();
151        let trans_ids: HashSet<&str> = net.transitions.iter().map(|t| t.id.as_str()).collect();
152
153        let overlap: Vec<&&str> = place_ids.intersection(&trans_ids).collect();
154        if !overlap.is_empty() {
155            return Err(format!("Partition overlap: {:?} declared as both Place and Transition", overlap));
156        }
157
158        for trans in &net.transitions {
159            for inp in &trans.inputs {
160                if trans_ids.contains(inp.as_str()) {
161                    return Err(format!(
162                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
163                        trans.id, inp
164                    ));
165                }
166                if !place_ids.contains(inp.as_str()) {
167                    return Err(format!(
168                        "Transition '{}' references unknown input Place '{}'",
169                        trans.id, inp
170                    ));
171                }
172            }
173            for outp in &trans.outputs {
174                if trans_ids.contains(outp.as_str()) {
175                    return Err(format!(
176                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
177                        trans.id, outp
178                    ));
179                }
180                if !place_ids.contains(outp.as_str()) {
181                    return Err(format!(
182                        "Transition '{}' references unknown output Place '{}'",
183                        trans.id, outp
184                    ));
185                }
186            }
187        }
188
189        Ok(())
190    }
191
192    /// Fires a transition in-process within a Cordis Fiber lifecycle.
193    pub fn fire_transition(
194        &self,
195        net: &PetriNet,
196        marking: &mut Marking,
197        transition_id: &str,
198        input_payload: &[u8],
199        planted_error: bool,
200    ) -> Result<TransitionExecutionOutcome, String> {
201        Self::validate_bipartite(net)?;
202
203        let trans = net
204            .transitions
205            .iter()
206            .find(|t| t.id == transition_id)
207            .ok_or_else(|| format!("Transition '{}' not found in net", transition_id))?;
208
209        // 1. Check token enablement in input places
210        for in_place in &trans.inputs {
211            let count = marking.get(in_place).copied().unwrap_or(0);
212            if count < 1 {
213                return Err(format!(
214                    "Transition '{}' not enabled: input place '{}' has 0 tokens",
215                    transition_id, in_place
216                ));
217            }
218        }
219
220        // 2. Instantiate Cordis Fiber (Pending)
221        let fiber = Fiber::new(
222            format!("fiber_{}_{}", transition_id, uuid::Uuid::new_v4()),
223            vec!["@Inject::Context".to_string()],
224        );
225        let mut state_history = vec![fiber.get_state()];
226
227        let start_time = Instant::now();
228
229        // Pending -> Loading
230        fiber.transition_to(FiberState::Loading)?;
231        state_history.push(fiber.get_state());
232
233        // Loading -> Active
234        fiber.transition_to(FiberState::Active)?;
235        state_history.push(fiber.get_state());
236
237        if planted_error {
238            // ZERO TOKEN LEAKAGE:
239            // Input tokens remain untouched.
240            // Output tokens not deposited.
241            // Unload and dispose fiber.
242            let _ = fiber.transition_to(FiberState::Unloading);
243            state_history.push(fiber.get_state());
244            let _ = fiber.transition_to(FiberState::Disposed);
245            state_history.push(fiber.get_state());
246
247            let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
248            return Ok(TransitionExecutionOutcome {
249                transition_id: transition_id.to_string(),
250                function_id: "urn:mcard:cas/mcard-record/create-record".to_string(),
251                success: false,
252                record_hash: None,
253                latency_ms,
254                state_history,
255                error: Some("Planted failure in transition execution".to_string()),
256            });
257        }
258
259        // Execute function in-process while Active
260        let record = create_record(input_payload, None)?;
261
262        // Active -> Unloading
263        fiber.transition_to(FiberState::Unloading)?;
264        state_history.push(fiber.get_state());
265
266        // Decrement input tokens
267        for in_place in &trans.inputs {
268            let count = marking.get_mut(in_place).unwrap();
269            *count -= 1;
270        }
271
272        // Increment output tokens
273        for outp in &trans.outputs {
274            let count = marking.entry(outp.clone()).or_insert(0);
275            *count += 1;
276        }
277
278        // Unloading -> Disposed
279        fiber.transition_to(FiberState::Disposed)?;
280        state_history.push(fiber.get_state());
281
282        let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
283
284        Ok(TransitionExecutionOutcome {
285            transition_id: transition_id.to_string(),
286            function_id: "urn:mcard:cas/mcard-record/create-record".to_string(),
287            success: true,
288            record_hash: Some(record.hash),
289            latency_ms,
290            state_history,
291            error: None,
292        })
293    }
294}