Skip to main content

clm_rust_core/layer0/
function_pcard_enriched.rs

1//! Layer 0: Enriched Function PCard Deserialization & Zero-Allocation Parser
2//! Canonical Path: kernel/clm_rust_core/src/layer0/function_pcard_enriched.rs
3//! Governed by: EPIC-CRD Sprint CRD-01 (DoD-CRD-01-06)
4
5use serde::{Deserialize, Serialize};
6
7fn default_true() -> bool {
8    true
9}
10
11fn default_cleanup_policy() -> String {
12    "lifo_unwind".to_string()
13}
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum CoeffectAccessMode {
18    ReadOnly,
19    ReadWrite,
20    Execute,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct RequiredService {
25    pub service_name: String,
26    pub interface: String,
27    pub access_mode: CoeffectAccessMode,
28    #[serde(default)]
29    pub optional: bool,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct CoeffectsRecord {
34    #[serde(default)]
35    pub required_services: Vec<RequiredService>,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum FiberExecutionMode {
41    SynchronousAtomic,
42    AsynchronousStream,
43    AsynchronousBatch,
44    CooperativeTurn,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum FiberContextIsolation {
50    None,
51    Shared,
52    IsolatedScratchpad,
53    IsolatedWorkspace,
54    IsolatedProcess,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct FiberSpec {
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub context_isolation: Option<FiberContextIsolation>,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub execution_mode: Option<FiberExecutionMode>,
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub memory_quota_bytes: Option<u64>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct SavepointGuardContract {
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub max_rollback_timeout_us: Option<u32>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub max_rollback_latency_us: Option<u32>,
73    #[serde(default = "default_true")]
74    pub lifo_disposers: bool,
75    #[serde(default = "default_cleanup_policy")]
76    pub cleanup_policy: String,
77}
78
79impl SavepointGuardContract {
80    pub fn effective_timeout_us(&self) -> Option<u32> {
81        self.max_rollback_timeout_us.or(self.max_rollback_latency_us)
82    }
83
84    pub fn validate_bound(&self) -> Result<(), &'static str> {
85        match self.effective_timeout_us() {
86            Some(t) if t <= 1000 => Ok(()),
87            Some(_) => Err("SavepointGuard timeout exceeds 1000µs bound"),
88            None => Err("SavepointGuard requires max_rollback_timeout_us or max_rollback_latency_us"),
89        }
90    }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94pub struct FacesRecord {
95    pub r#abstract: String,
96    pub concrete: String,
97    pub balanced: String,
98}
99
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub struct DependencyEdge {
102    pub target_function_id: String,
103    pub target_pcard_ref: String,
104    pub kind: String,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub source: Option<String>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub confidence: Option<f64>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub observed_at: Option<String>,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct EnrichedPCard {
115    pub function_id: String,
116    pub domain: String,
117    pub operation: String,
118    pub pcard_ref: String,
119    pub faces: FacesRecord,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub dependencies: Option<Vec<DependencyEdge>>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub coeffects: Option<CoeffectsRecord>,
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub fiber_spec: Option<FiberSpec>,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub savepoint_guard: Option<SavepointGuardContract>,
128}
129
130pub fn parse_enriched_pcard(json_str: &str) -> Result<EnrichedPCard, serde_json::Error> {
131    serde_json::from_str(json_str)
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn test_enriched_pcard_deserialization() {
140        let minimal_json = r#"{
141            "function_id": "urn:mcard:codec/canonical-json",
142            "domain": "codec",
143            "operation": "canonical-json",
144            "pcard_ref": "blake3:1111111111111111111111111111111111111111111111111111111111111111",
145            "faces": {
146                "abstract": "blake3:2222222222222222222222222222222222222222222222222222222222222222",
147                "concrete": "blake3:3333333333333333333333333333333333333333333333333333333333333333",
148                "balanced": "blake3:4444444444444444444444444444444444444444444444444444444444444444"
149            }
150        }"#;
151
152        let pcard = parse_enriched_pcard(minimal_json).expect("Minimal PCard must deserialize cleanly");
153        assert_eq!(pcard.function_id, "urn:mcard:codec/canonical-json");
154        // Zero allocation overhead: optional fields are None
155        assert!(pcard.coeffects.is_none());
156        assert!(pcard.fiber_spec.is_none());
157        assert!(pcard.savepoint_guard.is_none());
158
159        let enriched_json = r#"{
160            "function_id": "urn:mcard:storage/create-record",
161            "domain": "storage",
162            "operation": "create-record",
163            "pcard_ref": "blake3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
164            "faces": {
165                "abstract": "blake3:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
166                "concrete": "blake3:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
167                "balanced": "blake3:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
168            },
169            "coeffects": {
170                "required_services": [
171                    {
172                        "service_name": "sqlite_pool",
173                        "interface": "clm.layer0.storage.ISQLitePool",
174                        "access_mode": "read_write"
175                    },
176                    {
177                        "service_name": "crypto_hasher",
178                        "interface": "clm.layer0.hash.IHasher",
179                        "access_mode": "execute"
180                    }
181                ]
182            },
183            "fiber_spec": {
184                "context_isolation": "isolated_workspace",
185                "execution_mode": "synchronous_atomic",
186                "memory_quota_bytes": 1048576
187            },
188            "savepoint_guard": {
189                "max_rollback_timeout_us": 500,
190                "lifo_disposers": true,
191                "cleanup_policy": "lifo_unwind"
192            }
193        }"#;
194
195        let enriched = parse_enriched_pcard(enriched_json).expect("Enriched PCard must deserialize");
196        let coeffects = enriched.coeffects.expect("Must have coeffects");
197        assert_eq!(coeffects.required_services.len(), 2);
198        assert_eq!(coeffects.required_services[0].service_name, "sqlite_pool");
199        assert_eq!(coeffects.required_services[0].access_mode, CoeffectAccessMode::ReadWrite);
200
201        let fiber_spec = enriched.fiber_spec.expect("Must have fiber_spec");
202        assert_eq!(fiber_spec.context_isolation, Some(FiberContextIsolation::IsolatedWorkspace));
203        assert_eq!(fiber_spec.execution_mode, Some(FiberExecutionMode::SynchronousAtomic));
204        assert_eq!(fiber_spec.memory_quota_bytes, Some(1048576));
205
206        let sp_guard = enriched.savepoint_guard.expect("Must have savepoint_guard");
207        assert_eq!(sp_guard.max_rollback_timeout_us, Some(500));
208        assert!(sp_guard.lifo_disposers);
209        assert!(sp_guard.validate_bound().is_ok());
210
211        // Verify bound rejection on invalid timeout
212        let invalid_guard = SavepointGuardContract {
213            max_rollback_timeout_us: Some(5000),
214            max_rollback_latency_us: None,
215            lifo_disposers: true,
216            cleanup_policy: "lifo_unwind".to_string(),
217        };
218        assert!(invalid_guard.validate_bound().is_err());
219    }
220}