Skip to main content

clm_rust_core/layer2/sync/
validation.rs

1// Stateless outbox and inbound validation, split out of `service.rs` (Sprint 532).
2// Behaviour is unchanged; these are inherent methods on `MCardSyncEngine`.
3
4use crate::layer2::sync::codec::unframe_record;
5use crate::layer2::sync::petri::evaluate_lifecycle_guard;
6use crate::layer2::sync::service::{kind_to_lifecycle, normalize_qualified_hash, MCardSyncEngine};
7use crate::layer2::sync::types::{MCardRecord, RecordFrame, SyncOutboxEntry, TransferAttempt};
8use std::collections::BTreeMap;
9
10impl MCardSyncEngine {
11    pub(crate) fn is_durably_queued(&self, entry: &SyncOutboxEntry) -> bool {
12        let Some(port) = self.outbox_port.as_ref() else { return true };
13        let persisted = match port.load_outbox() {
14            Ok(entries) => entries,
15            Err(_) => return false,
16        };
17        persisted.iter().any(|candidate| {
18            candidate.delivery_id == entry.delivery_id
19                && candidate.transfer_id == entry.transfer_id
20                && candidate.status == entry.status
21                && candidate.records == entry.records
22                && candidate.transitions == entry.transitions
23        })
24    }
25
26    pub(crate) fn validate_inbound_attempt(
27        &self,
28        attempt: &TransferAttempt,
29        records: &[RecordFrame],
30    ) -> Result<Vec<(String, MCardRecord, String)>, (String, String)> {
31        if attempt.target_node_id != self.node_id {
32            return Err((
33                "guard-rejected".to_string(),
34                format!("Target node mismatch: {}", attempt.target_node_id),
35            ));
36        }
37        let mut verified: Vec<(String, MCardRecord, String)> = Vec::new();
38        for frame in records {
39            let (rec, q_hash) = unframe_record(frame, crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3)?;
40            let bare = q_hash.split(':').nth(1).unwrap_or("").to_string();
41            verified.push((bare, rec, q_hash));
42        }
43        let mut expected: Vec<String> =
44            attempt.record_hashes.iter().map(|h| normalize_qualified_hash(h)).collect();
45        expected.sort();
46        let mut actual: Vec<String> =
47            verified.iter().map(|(_, _, q)| q.clone()).collect();
48        actual.sort();
49        if expected != actual {
50            return Err((
51                "declared-mismatch".to_string(),
52                "record hash set does not match supplied frames".to_string(),
53            ));
54        }
55        let mut simulated: BTreeMap<String, BTreeMap<String, i64>> = BTreeMap::new();
56        for transition in &attempt.transitions {
57            let current = simulated
58                .get(&transition.handle)
59                .cloned()
60                .or_else(|| self.handle_markings.get(&transition.handle).cloned())
61                .unwrap_or_else(Self::default_lifecycle_marking);
62            let Some(lifecycle_id) = kind_to_lifecycle(&transition.kind) else {
63                return Err((
64                    "guard-rejected".to_string(),
65                    format!("Unknown lifecycle transition for kind {}", transition.kind),
66                ));
67            };
68            let gate = evaluate_lifecycle_guard(&current, lifecycle_id, Some(transition));
69            if !gate.enabled {
70                return Err((
71                    gate.error_code.unwrap_or_else(|| "guard-rejected".to_string()),
72                    gate.reason.unwrap_or_else(|| "transition rejected".to_string()),
73                ));
74            }
75            simulated.insert(transition.handle.clone(), gate.post_marking);
76            if transition.kind == "RELOCATE" || transition.kind == "FORK" {
77                if let Some(to_handle) = &transition.to_handle {
78                    if to_handle != &transition.handle {
79                        let target = simulated
80                            .get(to_handle)
81                            .cloned()
82                            .or_else(|| self.handle_markings.get(to_handle).cloned())
83                            .unwrap_or_else(Self::default_lifecycle_marking);
84                        let target_tid = if transition.kind == "FORK" { "t_fork_in" } else { "t_relocate_in" };
85                        let target_gate =
86                            evaluate_lifecycle_guard(&target, target_tid, Some(transition));
87                        if !target_gate.enabled {
88                            return Err((
89                                target_gate
90                                    .error_code
91                                    .unwrap_or_else(|| "guard-rejected".to_string()),
92                                target_gate
93                                    .reason
94                                    .unwrap_or_else(|| "target handle rejected".to_string()),
95                            ));
96                        }
97                        simulated.insert(to_handle.clone(), target_gate.post_marking);
98                    }
99                }
100            }
101        }
102        Ok(verified)
103    }
104}