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 == crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_CREATE_RECORD {
88                hash_res = stmt.query_row([crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD], |row| row.get(0));
89            } else if function_id == crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD {
90                hash_res = stmt.query_row([crate::layer0::vocabulary::HANDLE_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 card_raw = crate::layer0::record_port::RecordStorePort::read_record(&conn, &pcard_hash)
97            .map_err(|error| error.to_string())?.ok_or("root card is missing")?.content;
98
99        let root_val: serde_json::Value = serde_json::from_slice(&card_raw)
100            .map_err(|e| format!("Failed to parse root card JSON: {}", e))?;
101
102        let faces = root_val
103            .get("payload")
104            .and_then(|p| p.get("faces"))
105            .and_then(|f| f.as_object())
106            .ok_or_else(|| "PCard missing required faces object".to_string())?;
107
108        let mut resolved_faces: HashMap<String, serde_json::Value> = HashMap::new();
109
110        for (aspect, q_hash_val) in faces {
111            let q_hash = q_hash_val.as_str().unwrap_or("");
112            if let Some(record) = crate::layer0::record_port::RecordStorePort::read_record(&conn, q_hash)
113                .map_err(|error| error.to_string())? {
114                let f_raw = record.content;
115                if let Ok(f_val) = serde_json::from_slice(&f_raw) {
116                    resolved_faces.insert(aspect.clone(), f_val);
117                }
118            }
119        }
120
121        Ok(PcardData {
122            function_id: function_id.to_string(),
123            pcard_hash,
124            abstract_face: resolved_faces.remove("abstract").unwrap_or(serde_json::Value::Null),
125            concrete_face: resolved_faces.remove("concrete").unwrap_or(serde_json::Value::Null),
126            balanced_face: resolved_faces.remove("balanced").unwrap_or(serde_json::Value::Null),
127        })
128    }
129
130    /// Invokes create_record directly in-process.
131    pub fn invoke_create_record(
132        &self,
133        content: &[u8],
134        algorithm: Option<&str>,
135    ) -> Result<MCardRecord, String> {
136        create_record(content, algorithm)
137    }
138
139    /// Validates that the PetriNet strictly satisfies bipartite invariants.
140    pub fn validate_bipartite(net: &PetriNet) -> Result<(), String> {
141        let place_ids: HashSet<&str> = net.places.iter().map(|p| p.id.as_str()).collect();
142        let trans_ids: HashSet<&str> = net.transitions.iter().map(|t| t.id.as_str()).collect();
143
144        let overlap: Vec<&&str> = place_ids.intersection(&trans_ids).collect();
145        if !overlap.is_empty() {
146            return Err(format!("Partition overlap: {:?} declared as both Place and Transition", overlap));
147        }
148
149        for trans in &net.transitions {
150            for inp in &trans.inputs {
151                if trans_ids.contains(inp.as_str()) {
152                    return Err(format!(
153                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
154                        trans.id, inp
155                    ));
156                }
157                if !place_ids.contains(inp.as_str()) {
158                    return Err(format!(
159                        "Transition '{}' references unknown input Place '{}'",
160                        trans.id, inp
161                    ));
162                }
163            }
164            for outp in &trans.outputs {
165                if trans_ids.contains(outp.as_str()) {
166                    return Err(format!(
167                        "Bipartite violation: Transition '{}' connects directly to Transition '{}'",
168                        trans.id, outp
169                    ));
170                }
171                if !place_ids.contains(outp.as_str()) {
172                    return Err(format!(
173                        "Transition '{}' references unknown output Place '{}'",
174                        trans.id, outp
175                    ));
176                }
177            }
178        }
179
180        Ok(())
181    }
182
183    /// Fires a transition in-process within a Cordis Fiber lifecycle.
184    pub fn fire_transition(
185        &self,
186        net: &PetriNet,
187        marking: &mut Marking,
188        transition_id: &str,
189        input_payload: &[u8],
190        planted_error: bool,
191    ) -> Result<TransitionExecutionOutcome, String> {
192        Self::validate_bipartite(net)?;
193
194        let trans = net
195            .transitions
196            .iter()
197            .find(|t| t.id == transition_id)
198            .ok_or_else(|| format!("Transition '{}' not found in net", transition_id))?;
199
200        // 1. Check token enablement in input places
201        for in_place in &trans.inputs {
202            let count = marking.get(in_place).copied().unwrap_or(0);
203            if count < 1 {
204                return Err(format!(
205                    "Transition '{}' not enabled: input place '{}' has 0 tokens",
206                    transition_id, in_place
207                ));
208            }
209        }
210
211        // 2. Instantiate Cordis Fiber (Pending)
212        let fiber = Fiber::new(
213            format!("fiber_{}_{}", transition_id, uuid::Uuid::new_v4()),
214            vec!["@Inject::Context".to_string()],
215        );
216        let mut state_history = vec![fiber.get_state()];
217
218        let start_time = Instant::now();
219
220        // Pending -> Loading
221        fiber.transition_to(FiberState::Loading)?;
222        state_history.push(fiber.get_state());
223
224        // Loading -> Active
225        fiber.transition_to(FiberState::Active)?;
226        state_history.push(fiber.get_state());
227
228        if planted_error {
229            // ZERO TOKEN LEAKAGE:
230            // Input tokens remain untouched.
231            // Output tokens not deposited.
232            // Unload and dispose fiber.
233            fiber.transition_to(FiberState::Unloading)?;
234            state_history.push(fiber.get_state());
235            fiber.transition_to(FiberState::Disposed)?;
236            state_history.push(fiber.get_state());
237
238            let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
239            return Ok(TransitionExecutionOutcome {
240                transition_id: transition_id.to_string(),
241                function_id: crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD.to_string(),
242                success: false,
243                record_hash: None,
244                latency_ms,
245                state_history,
246                error: Some("Planted failure in transition execution".to_string()),
247            });
248        }
249
250        // Execute function in-process while Active
251        let record = create_record(input_payload, None)?;
252
253        // Active -> Unloading
254        fiber.transition_to(FiberState::Unloading)?;
255        state_history.push(fiber.get_state());
256
257        // Decrement input tokens
258        for in_place in &trans.inputs {
259            let count = marking.get_mut(in_place).unwrap();
260            *count -= 1;
261        }
262
263        // Increment output tokens
264        for outp in &trans.outputs {
265            let count = marking.entry(outp.clone()).or_insert(0);
266            *count += 1;
267        }
268
269        // Unloading -> Disposed
270        fiber.transition_to(FiberState::Disposed)?;
271        state_history.push(fiber.get_state());
272
273        let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
274
275        Ok(TransitionExecutionOutcome {
276            transition_id: transition_id.to_string(),
277            function_id: crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD.to_string(),
278            success: true,
279            record_hash: Some(record.hash),
280            latency_ms,
281            state_history,
282            error: None,
283        })
284    }
285}