Skip to main content

cbcl_core/
repeat.rs

1//! Runtime interpretation of install-time repeat copies (SPEC-015 REQ-704).
2//!
3//! Wire verbs stay unindexed. A copy is established by its causal ancestry,
4//! not by arrival order, a mutable counter, or a sender-supplied index. Dynamic
5//! programming over the finite expanded DAG avoids recursive store traversal;
6//! missing ancestry stays Unknown. No state fold is read by this module.
7#![forbid(unsafe_code)]
8use crate::message::CausedBy;
9use crate::protocol::{
10    allowed_single_predecessors, predecessor_type, repeat_base_name, CausalProtocol,
11    CausalViolation, NodeRef, StepDecl, VerificationResult, BEGIN_KEYWORD, REPEAT_SEPARATOR,
12};
13use crate::store::{ContentHash, MessageStore, ThreadId};
14use alloc::borrow::Cow;
15use alloc::collections::{BTreeMap, BTreeSet};
16use alloc::string::String;
17use alloc::sync::Arc;
18use alloc::vec::Vec;
19
20// Native and state causal identities use the same multihash spelling.
21fn native_reference(id: &str) -> Cow<'_, str> {
22    Cow::Borrowed(id)
23}
24
25pub(crate) fn has_repeat(protocol: &CausalProtocol) -> bool {
26    protocol.steps.keys().any(|s| s.contains(REPEAT_SEPARATOR))
27}
28
29// Safety-level position resolution needs only authenticated causal metadata.
30// Full payloads are still required by the separate occupant-completion check.
31fn metadata<S: MessageStore>(
32    store: &S,
33    hash: &ContentHash,
34    thread: &ThreadId,
35) -> Option<(String, Option<CausedBy>)> {
36    if let Some(message) = store.lookup_in_thread(hash, thread) {
37        let simple = message.innermost_simple()?;
38        return Some((
39            String::from(simple.performative()?.name()),
40            simple.caused_by().cloned(),
41        ));
42    }
43    if let Some(envelope) = store.envelope_in_thread(hash, thread) {
44        return Some((
45            envelope.header.performative.clone(),
46            envelope.header.caused_by.clone(),
47        ));
48    }
49    let opened = store.opened_in_thread(hash, thread)?;
50    Some((
51        String::from(opened.performative()?),
52        opened.causal_reference()?,
53    ))
54}
55
56/// A finite evidence table, scoped to a thread and to the referenced closure.
57/// Entries say whether a particular message inhabits a particular expanded step.
58/// The topological step order makes every lookup depend only on earlier rows.
59pub(crate) struct Resolution<'a, S> {
60    store: &'a S,
61    protocol: &'a CausalProtocol,
62    thread: &'a ThreadId,
63    root: Option<&'a ContentHash>,
64    pub(crate) order: Vec<&'a str>,
65    rows: BTreeMap<(String, String), VerificationResult>,
66    materialized: Option<&'a MaterializedPositions>,
67}
68impl<'a, S: MessageStore> Resolution<'a, S> {
69    pub(crate) fn new(
70        store: &'a S,
71        protocol: &'a CausalProtocol,
72        thread: &'a ThreadId,
73        root: Option<&'a ContentHash>,
74        hashes: impl IntoIterator<Item = String>,
75    ) -> Self {
76        let materialized = store
77            .materialized_positions()
78            .filter(|p| p.matches(protocol, thread, root));
79        let mut messages = BTreeMap::new();
80        let mut seen = BTreeSet::new();
81        let mut todo: Vec<String> = hashes.into_iter().collect();
82        while let Some(hash) = todo.pop() {
83            if !seen.insert(hash.clone()) {
84                continue;
85            }
86            if materialized
87                .is_some_and(|p| p.entries.contains_key(native_reference(&hash).as_ref()))
88            {
89                continue;
90            }
91            if let Some((verb, cause)) = metadata(store, &ContentHash(hash.clone()), thread) {
92                match &cause {
93                    Some(CausedBy::Single(h)) => todo.push(h.clone()),
94                    Some(CausedBy::Multiple(hs)) => todo.extend(hs.iter().cloned()),
95                    _ => {}
96                }
97                messages.insert(hash, (verb, cause));
98            }
99        }
100
101        if messages.is_empty() {
102            return Self {
103                store,
104                protocol,
105                thread,
106                root,
107                order: Vec::new(),
108                rows: BTreeMap::new(),
109                materialized,
110            };
111        }
112        let mut order = Vec::new();
113        let mut done = BTreeSet::new();
114        // Installed protocols are acyclic. A malformed programmatic protocol
115        // leaves cyclic rows absent, which fails closed rather than looping.
116        loop {
117            let ready: Vec<&str> = protocol
118                .steps
119                .iter()
120                .filter(|(name, step)| {
121                    !done.contains(name.as_str())
122                        && step
123                            .predecessors
124                            .iter()
125                            .all(|nr| nr.performatives().all(|p| done.contains(p)))
126                })
127                .map(|(name, _)| name.as_str())
128                .collect();
129            if ready.is_empty() {
130                break;
131            }
132            for name in ready {
133                done.insert(name);
134                order.push(name);
135            }
136        }
137        let mut result = Self {
138            store,
139            protocol,
140            thread,
141            root,
142            order,
143            rows: BTreeMap::new(),
144            materialized,
145        };
146        for name in result.order.clone() {
147            if name == BEGIN_KEYWORD {
148                continue;
149            }
150            for (hash, (verb, cause)) in &messages {
151                if verb != repeat_base_name(name) {
152                    continue;
153                }
154                let value = result.step(&protocol.steps[name], cause.as_ref());
155                result
156                    .rows
157                    .insert((hash.clone(), String::from(name)), value);
158            }
159        }
160
161        result
162    }
163    fn kind(&self, hash: &str) -> Option<&str> {
164        self.materialized
165            .and_then(|p| p.entries.get(native_reference(hash).as_ref()))
166            .map(|f| f.metadata.verb.as_str())
167            .or_else(|| predecessor_type(self.store, &ContentHash(String::from(hash)), self.thread))
168    }
169    pub(crate) fn at(&self, hash: &str, step: &str) -> VerificationResult {
170        if let Some(fact) = self
171            .materialized
172            .and_then(|p| p.entries.get(native_reference(hash).as_ref()))
173        {
174            let repeated =
175                self.protocol.steps.keys().any(|s| {
176                    s.contains(REPEAT_SEPARATOR) && repeat_base_name(s) == fact.metadata.verb
177                });
178            let ordinary = !step.contains(REPEAT_SEPARATOR)
179                && !repeated
180                && repeat_base_name(step) == fact.metadata.verb;
181            return if ordinary || fact.steps.contains(step) {
182                VerificationResult::Valid
183            } else {
184                self.wrong(hash, alloc::vec![String::from(step)])
185            };
186        }
187        let key = ContentHash(String::from(hash));
188        let Some(found) = self.kind(hash) else {
189            return VerificationResult::Unknown;
190        };
191        if found != repeat_base_name(step) {
192            return self.wrong(hash, alloc::vec![String::from(step)]);
193        }
194        // Ordinary types retain their pre-repeat interpretation. Only indexed
195        // types (and plain copies of a repeated base) need ancestry evidence.
196        let repeated = self
197            .protocol
198            .steps
199            .keys()
200            .any(|s| s.contains(REPEAT_SEPARATOR) && repeat_base_name(s) == found);
201        if !step.contains(REPEAT_SEPARATOR) && !repeated {
202            return VerificationResult::Valid;
203        }
204        if metadata(self.store, &key, self.thread).is_none() {
205            // A sealed causal opening cannot establish a repeat position.
206            return VerificationResult::Unknown;
207        }
208        self.rows
209            .get(&(String::from(hash), String::from(step)))
210            .cloned()
211            .unwrap_or_else(|| self.wrong(hash, alloc::vec![String::from(step)]))
212    }
213    fn wrong(&self, hash: &str, expected: Vec<String>) -> VerificationResult {
214        VerificationResult::Violation(CausalViolation::InvalidPredecessor {
215            caused_by: String::from(hash),
216            expected,
217            found: String::from(self.kind(hash).unwrap_or("")),
218        })
219    }
220    fn alternatives(&self, hash: &str, allowed: &[String]) -> VerificationResult {
221        // Copy alternatives are existential: a wrong copy must not eclipse a
222        // still-missing candidate. This is deliberately NOT eager lattice join.
223        let mut missing = self.kind(hash).is_none();
224        for name in allowed {
225            match self.at(hash, name) {
226                VerificationResult::Valid => return VerificationResult::Valid,
227                VerificationResult::Unknown => missing = true,
228                VerificationResult::Violation(_) => {}
229            }
230        }
231        if missing {
232            VerificationResult::Unknown
233        } else {
234            self.wrong(hash, allowed.to_vec())
235        }
236    }
237    pub(crate) fn step(&self, step: &StepDecl, caused_by: Option<&CausedBy>) -> VerificationResult {
238        let rewritten;
239        let caused_by = match (caused_by, self.root) {
240            (Some(CausedBy::Single(h)), Some(root)) if h == &root.0 => {
241                rewritten = CausedBy::Begin;
242                Some(&rewritten)
243            }
244            _ => caused_by,
245        };
246        match caused_by {
247            None if step.predecessors.is_empty() => VerificationResult::Valid,
248            None => VerificationResult::Violation(CausalViolation::MissingCausedBy),
249            Some(CausedBy::Begin) => {
250                let allowed = allowed_single_predecessors(step);
251                if allowed.iter().any(|n| n == BEGIN_KEYWORD) {
252                    VerificationResult::Valid
253                } else {
254                    self.wrong(BEGIN_KEYWORD, allowed)
255                }
256            }
257            Some(CausedBy::Single(h)) => self.alternatives(h, &allowed_single_predecessors(step)),
258            Some(CausedBy::Multiple(hashes)) => {
259                let Some(all) = step.predecessors.iter().find_map(|nr| {
260                    if let NodeRef::All(s) = nr {
261                        Some(s)
262                    } else {
263                        None
264                    }
265                }) else {
266                    return VerificationResult::Violation(CausalViolation::FanInWithoutAllDecl {
267                        performative: step.performative.clone(),
268                    });
269                };
270                let mut found = BTreeSet::new();
271                let mut possible = BTreeSet::new();
272                let mut missing = false;
273                for h in hashes {
274                    let mut matched = false;
275                    let mut unknown = self.kind(h).is_none();
276                    for name in all {
277                        match self.at(h, name) {
278                            VerificationResult::Valid => {
279                                found.insert(name.clone());
280                                matched = true;
281                            }
282                            VerificationResult::Unknown => {
283                                possible.insert(name.clone());
284                                unknown = true;
285                            }
286                            VerificationResult::Violation(_) => {}
287                        }
288                    }
289                    if !matched && !unknown {
290                        return self.wrong(h, all.iter().cloned().collect());
291                    }
292                    missing |= !matched && unknown;
293                }
294                let absent: Vec<String> = all.difference(&found).cloned().collect();
295                if missing || absent.iter().any(|n| possible.contains(n)) {
296                    VerificationResult::Unknown
297                } else if absent.is_empty() {
298                    VerificationResult::Valid
299                } else {
300                    VerificationResult::Violation(CausalViolation::IncompleteFanIn {
301                        missing_types: absent,
302                    })
303                }
304            }
305        }
306    }
307    pub(crate) fn verify(&self, verb: &str, cause: Option<&CausedBy>) -> VerificationResult {
308        let mut unknown = false;
309        let mut error = VerificationResult::Violation(CausalViolation::MissingCausedBy);
310        for (name, step) in &self.protocol.steps {
311            if name == BEGIN_KEYWORD || repeat_base_name(name) != verb {
312                continue;
313            }
314            match self.step(step, cause) {
315                VerificationResult::Valid => return VerificationResult::Valid,
316                VerificationResult::Unknown => unknown = true,
317                invalid => error = invalid,
318            }
319        }
320        if unknown {
321            VerificationResult::Unknown
322        } else {
323            error
324        }
325    }
326}
327
328pub(crate) fn verify<S: MessageStore>(
329    verb: &str,
330    cause: Option<&CausedBy>,
331    store: &S,
332    protocol: &CausalProtocol,
333    thread: &ThreadId,
334    root: Option<&ContentHash>,
335) -> VerificationResult {
336    // Preserve the legacy route only for genuinely non-protocol verbs. A
337    // repeated base IS a protocol verb, even when it has no unindexed key.
338    if !protocol
339        .steps
340        .keys()
341        .any(|name| repeat_base_name(name) == verb)
342    {
343        return VerificationResult::Valid;
344    }
345    let hashes = match cause {
346        Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
347        Some(CausedBy::Multiple(hs)) => hs.clone(),
348        _ => Vec::new(),
349    };
350    Resolution::new(store, protocol, thread, root, hashes).verify(verb, cause)
351}
352
353/// Ordered occurrences of a verb in the finite protocol. Every consecutive
354/// pair must be causally comparable; an arbitrary topological tie-break is
355/// never allowed to invent progress between independent branches.
356pub(crate) fn position_chain<'a>(
357    protocol: &'a CausalProtocol,
358    verb: &str,
359) -> Result<Vec<&'a str>, String> {
360    let mut ancestors: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
361    let mut positions = Vec::new();
362    loop {
363        let ready: Vec<&str> = protocol
364            .steps
365            .iter()
366            .filter(|(name, step)| {
367                !ancestors.contains_key(name.as_str())
368                    && step
369                        .predecessors
370                        .iter()
371                        .all(|nr| nr.performatives().all(|p| ancestors.contains_key(p)))
372            })
373            .map(|(name, _)| name.as_str())
374            .collect();
375        if ready.is_empty() {
376            break;
377        }
378        for name in ready {
379            let mut inherited = BTreeSet::new();
380            for parent in protocol.steps[name]
381                .predecessors
382                .iter()
383                .flat_map(NodeRef::performatives)
384            {
385                inherited.insert(parent);
386                inherited.extend(ancestors[parent].iter().copied());
387            }
388            if name != BEGIN_KEYWORD && repeat_base_name(name) == verb {
389                if positions
390                    .last()
391                    .is_some_and(|previous| !inherited.contains(previous))
392                {
393                    return Err(alloc::format!(
394                        "progress '{verb}' has incomparable protocol positions"
395                    ));
396                }
397                positions.push(name);
398            }
399            ancestors.insert(name, inherited);
400        }
401    }
402    if ancestors.len() != protocol.steps.len() || positions.is_empty() {
403        return Err(alloc::format!(
404            "progress '{verb}' requires positions in an acyclic protocol"
405        ));
406    }
407    Ok(positions)
408}
409
410/// Select established protocol ranks from accepted evidence. Data-domain filters
411/// do not change causal progress. The fold owns the max reduction, including 0.
412pub(crate) fn accepted_positions(
413    protocol: &CausalProtocol,
414    verb: &str,
415    acts: &[&crate::state::Act],
416) -> Vec<usize> {
417    let Ok(chain) = position_chain(protocol, verb) else {
418        return Vec::new();
419    };
420    let mut store = crate::store::ThreadedMessageStore::new();
421    let mut threads: BTreeMap<String, Vec<&crate::state::Act>> = BTreeMap::new();
422    for act in acts {
423        let Some(thread) = act.simple().thread() else {
424            continue;
425        };
426        // Fold acts use the state/wire address spelling, whereas native causal
427        // headers historically use the simple-message hash. Retain that lookup
428        // alias, but resolve pinned role roots using their actual state identity.
429        // Never change the supplied act or its causal edges.
430        store.append(
431            ContentHash(crate::equivocation::message_content_hash(act.simple())),
432            ThreadId(String::from(thread)),
433            act.message.clone(),
434        );
435        store.append(
436            ContentHash(act.address.clone()),
437            ThreadId(String::from(thread)),
438            act.message.clone(),
439        );
440        threads.entry(String::from(thread)).or_default().push(act);
441    }
442    let mut positions = Vec::new();
443    for (thread, members) in threads {
444        let thread = ThreadId(thread);
445        let root = members
446            .iter()
447            .filter(|a| crate::state::is_role_root(a))
448            .min_by(|a, b| a.address.cmp(&b.address))
449            .map(|a| ContentHash(a.address.clone()));
450        let resolution = Resolution::new(
451            &store,
452            protocol,
453            &thread,
454            root.as_ref(),
455            members.iter().map(|a| a.address.clone()),
456        );
457        for act in members.iter().filter(|a| a.verb == verb) {
458            for (index, name) in chain.iter().enumerate() {
459                if matches!(
460                    resolution
461                        .rows
462                        .get(&(act.address.clone(), String::from(*name))),
463                    Some(VerificationResult::Valid)
464                ) {
465                    positions.push(index + 1);
466                }
467            }
468        }
469    }
470    positions
471}
472
473/// Immutable installation binding. The context digest binds the entire native
474/// dialect/address/authentication schema; root and thread are explicit as well.
475#[derive(Clone, Debug, PartialEq, Eq)]
476pub struct PositionContext {
477    pub code: [u8; 32],
478    pub root: ContentHash,
479    pub thread: ThreadId,
480}
481/// Payload-free authenticated causal metadata. No sender-supplied rank exists.
482#[derive(Clone, Debug, PartialEq, Eq)]
483pub struct PositionMetadata {
484    pub id: String,
485    pub verb: String,
486    pub cause: Option<CausedBy>,
487}
488#[derive(Clone, Debug, PartialEq, Eq)]
489struct PositionFact {
490    metadata: PositionMetadata,
491    steps: BTreeSet<String>,
492}
493// Persistent treap: cloning a cut shares every unchanged native fact. Priorities
494// are SHA-256 of immutable identity bytes, with identity as deterministic tie-break.
495// Neither admission deltas nor borrowed resolver ports clone the covered prefix.
496#[derive(Clone, Debug, Default, PartialEq, Eq)]
497struct PositionIndex {
498    root: Option<Arc<PositionNode>>,
499}
500#[derive(Debug, PartialEq, Eq)]
501struct PositionNode {
502    fact: Arc<PositionFact>,
503    priority: [u8; 32],
504    size: usize,
505    left: Option<Arc<PositionNode>>,
506    right: Option<Arc<PositionNode>>,
507}
508impl PositionIndex {
509    fn get(&self, id: &str) -> Option<&PositionFact> {
510        let mut next = self.root.as_deref();
511        while let Some(n) = next {
512            match id.cmp(&n.fact.metadata.id) {
513                core::cmp::Ordering::Equal => return Some(&n.fact),
514                core::cmp::Ordering::Less => next = n.left.as_deref(),
515                core::cmp::Ordering::Greater => next = n.right.as_deref(),
516            }
517        }
518        None
519    }
520    fn contains_key(&self, id: &str) -> bool {
521        self.get(id).is_some()
522    }
523    fn values(&self) -> alloc::vec::IntoIter<&PositionFact> {
524        fn visit<'a>(n: Option<&'a PositionNode>, out: &mut Vec<&'a PositionFact>) {
525            if let Some(n) = n {
526                visit(n.left.as_deref(), out);
527                out.push(&n.fact);
528                visit(n.right.as_deref(), out);
529            }
530        }
531        let mut out = Vec::new();
532        visit(self.root.as_deref(), &mut out);
533        out.into_iter()
534    }
535    fn insert(&mut self, fact: PositionFact) {
536        use sha2::{Digest, Sha256};
537        let priority: [u8; 32] = Sha256::digest(fact.metadata.id.as_bytes()).into();
538        fn node(
539            fact: Arc<PositionFact>,
540            priority: [u8; 32],
541            left: Option<Arc<PositionNode>>,
542            right: Option<Arc<PositionNode>>,
543        ) -> Arc<PositionNode> {
544            let size =
545                1 + left.as_ref().map_or(0, |n| n.size) + right.as_ref().map_or(0, |n| n.size);
546            Arc::new(PositionNode {
547                fact,
548                priority,
549                size,
550                left,
551                right,
552            })
553        }
554        fn split(
555            root: Option<&Arc<PositionNode>>,
556            id: &str,
557        ) -> (Option<Arc<PositionNode>>, Option<Arc<PositionNode>>) {
558            let Some(n) = root else { return (None, None) };
559            if n.fact.metadata.id.as_str() < id {
560                let (l, r) = split(n.right.as_ref(), id);
561                (Some(node(n.fact.clone(), n.priority, n.left.clone(), l)), r)
562            } else {
563                let (l, r) = split(n.left.as_ref(), id);
564                (
565                    l,
566                    Some(node(n.fact.clone(), n.priority, r, n.right.clone())),
567                )
568            }
569        }
570        fn put(
571            root: Option<&Arc<PositionNode>>,
572            f: Arc<PositionFact>,
573            p: [u8; 32],
574        ) -> Arc<PositionNode> {
575            let Some(n) = root else {
576                return node(f, p, None, None);
577            };
578            if (p, f.metadata.id.as_str()) < (n.priority, n.fact.metadata.id.as_str()) {
579                let (l, r) = split(Some(n), &f.metadata.id);
580                return node(f, p, l, r);
581            }
582            if f.metadata.id < n.fact.metadata.id {
583                node(
584                    n.fact.clone(),
585                    n.priority,
586                    Some(put(n.left.as_ref(), f, p)),
587                    n.right.clone(),
588                )
589            } else {
590                node(
591                    n.fact.clone(),
592                    n.priority,
593                    n.left.clone(),
594                    Some(put(n.right.as_ref(), f, p)),
595                )
596            }
597        }
598        self.root = Some(put(self.root.as_ref(), Arc::new(fact), priority));
599    }
600}
601
602/// Native-computed position cache. Facts have private fields and no deserialize
603/// implementation. This is an accepted-evidence port, not authentication itself.
604#[derive(Clone, Debug, PartialEq, Eq)]
605pub struct MaterializedPositions {
606    context: PositionContext,
607    protocol: Option<Arc<CausalProtocol>>,
608    entries: PositionIndex,
609    ranks: Arc<BTreeMap<String, BTreeMap<String, usize>>>,
610    progress: BTreeMap<String, usize>,
611}
612impl MaterializedPositions {
613    pub fn new(
614        context: PositionContext,
615        protocol: Option<&CausalProtocol>,
616    ) -> Result<Self, String> {
617        let mut ranks = BTreeMap::new();
618        if let Some(p) = protocol {
619            if !p.check_acyclicity().is_empty() || !p.check_reachability().is_empty() {
620                return Err(String::from("invalid resume protocol"));
621            }
622            let verbs: BTreeSet<_> = p
623                .steps
624                .keys()
625                .filter(|n| n.as_str() != BEGIN_KEYWORD)
626                .map(|n| String::from(repeat_base_name(n)))
627                .collect();
628            for verb in verbs {
629                // Incomparable positions have native progress zero, but may
630                // still be used for native R5 resolution.
631                if let Ok(chain) = position_chain(p, &verb) {
632                    ranks.insert(
633                        verb,
634                        chain
635                            .iter()
636                            .enumerate()
637                            .map(|(i, n)| (String::from(*n), i + 1))
638                            .collect(),
639                    );
640                }
641            }
642        }
643        Ok(Self {
644            context,
645            protocol: protocol.map(|p| Arc::new(p.clone())),
646            entries: PositionIndex::default(),
647            ranks: Arc::new(ranks),
648            progress: BTreeMap::new(),
649        })
650    }
651    pub fn context(&self) -> &PositionContext {
652        &self.context
653    }
654    pub fn protocol(&self) -> Option<&CausalProtocol> {
655        self.protocol.as_deref()
656    }
657    pub fn metadata(&self) -> impl DoubleEndedIterator<Item = &PositionMetadata> {
658        self.entries.values().map(|f| &f.metadata)
659    }
660    pub fn len(&self) -> usize {
661        self.entries.root.as_ref().map_or(0, |n| n.size)
662    }
663    pub fn is_empty(&self) -> bool {
664        self.entries.root.is_none()
665    }
666    pub fn contains(&self, id: &str) -> bool {
667        self.entries.contains_key(native_reference(id).as_ref())
668    }
669    pub fn progress(&self, verb: &str) -> usize {
670        self.progress.get(verb).copied().unwrap_or(0)
671    }
672    fn matches(
673        &self,
674        protocol: &CausalProtocol,
675        thread: &ThreadId,
676        root: Option<&ContentHash>,
677    ) -> bool {
678        self.protocol.as_deref() == Some(protocol)
679            && &self.context.thread == thread
680            && root.map_or(true, |r| r == &self.context.root)
681    }
682    /// Called after native signature/context/admission checks. Requires exact
683    /// native identity and thread, and computes positions with the native R5
684    /// evaluator. No full message is retained.
685    pub fn apply_accepted(&mut self, message: &crate::message::Message) -> Result<(), String> {
686        let simple = message.innermost_simple().ok_or("resume simple")?;
687        let id = crate::equivocation::message_content_hash(simple);
688        self.apply_accepted_with_id(message, id)
689    }
690    /// Apply an accepted message under its authenticated state identity. This
691    /// differs from the simple-message hash only for sealed role roots.
692    pub fn apply_accepted_with_id(
693        &mut self,
694        message: &crate::message::Message,
695        id: String,
696    ) -> Result<(), String> {
697        let simple = message.innermost_simple().ok_or("resume simple")?;
698        if simple.thread() != Some(self.context.thread.0.as_str()) {
699            return Err(String::from("resume thread"));
700        }
701        let data = PositionMetadata {
702            id,
703            verb: String::from(simple.performative().ok_or("resume verb")?.name()),
704            cause: simple.caused_by().cloned(),
705        };
706        self.apply_metadata(data)
707    }
708    /// Restore *externally authenticated accepted* metadata, never arbitrary
709    /// claimed positions. Hosts must verify snapshot truth/scope before calling;
710    /// checkpoint's safe wrapper performs that verification. Native relation is
711    /// recomputed here, so even an attested rank cannot override R5.
712    pub fn restore_attested(
713        context: PositionContext,
714        protocol: Option<&CausalProtocol>,
715        records: Vec<PositionMetadata>,
716    ) -> Result<Self, String> {
717        let mut out = Self::new(context, protocol)?;
718        let mut todo: BTreeMap<String, PositionMetadata> = BTreeMap::new();
719        let mut waiting: BTreeMap<String, Vec<String>> = BTreeMap::new();
720        let mut remaining = BTreeMap::new();
721        let mut ready = Vec::new();
722        for r in records {
723            if todo.insert(r.id.clone(), r).is_some() {
724                return Err(String::from("duplicate resume identity"));
725            }
726        }
727        for (id, r) in &todo {
728            let parents = match &r.cause {
729                Some(CausedBy::Single(h)) => alloc::vec![h.clone()],
730                Some(CausedBy::Multiple(hs)) => hs.clone(),
731                _ => Vec::new(),
732            };
733            for parent in &parents {
734                if !todo.contains_key(native_reference(parent).as_ref()) {
735                    return Err(String::from("missing resume ancestor"));
736                }
737                waiting
738                    .entry(native_reference(parent).into_owned())
739                    .or_default()
740                    .push(id.clone());
741            }
742            remaining.insert(id.clone(), parents.len());
743            if parents.is_empty() {
744                ready.push(id.clone());
745            }
746        }
747        while let Some(id) = ready.pop() {
748            let r = todo.remove(&id).ok_or("resume cycle")?;
749            out.apply_metadata(r)?;
750            for child in waiting.remove(&id).unwrap_or_default() {
751                let count = remaining.get_mut(&child).ok_or("resume child")?;
752                *count -= 1;
753                if *count == 0 {
754                    ready.push(child);
755                }
756            }
757        }
758        if !todo.is_empty() {
759            return Err(String::from("cyclic resume ancestry"));
760        }
761        Ok(out)
762    }
763    fn apply_metadata(&mut self, data: PositionMetadata) -> Result<(), String> {
764        if let Some(old) = self.entries.get(&data.id) {
765            return if old.metadata == data {
766                Ok(())
767            } else {
768                Err(String::from("conflicting resume identity"))
769            };
770        }
771        let parents: &[String] = match &data.cause {
772            Some(CausedBy::Single(h)) => core::slice::from_ref(h),
773            Some(CausedBy::Multiple(hs)) => hs,
774            _ => &[],
775        };
776        if parents
777            .iter()
778            .any(|h| !self.entries.contains_key(native_reference(h).as_ref()))
779        {
780            return Err(String::from("missing resume ancestor"));
781        }
782        let root = data.id == self.context.root.0;
783        if root {
784            if !matches!(data.cause, Some(CausedBy::Begin)) {
785                return Err(String::from("resume root cause"));
786            }
787        } else if self.protocol.is_some()
788            && (parents.is_empty() || !self.entries.contains_key(&self.context.root.0))
789        {
790            return Err(String::from("resume root required"));
791        }
792        let mut steps = BTreeSet::new();
793        if let Some(p) = &self.protocol {
794            struct Port<'a>(&'a MaterializedPositions);
795            impl MessageStore for Port<'_> {
796                fn materialized_positions(&self) -> Option<&MaterializedPositions> {
797                    Some(self.0)
798                }
799                fn lookup(&self, _: &ContentHash) -> Option<&crate::message::Message> {
800                    None
801                }
802                fn lookup_in_thread(
803                    &self,
804                    _: &ContentHash,
805                    _: &ThreadId,
806                ) -> Option<&crate::message::Message> {
807                    None
808                }
809                fn contains(&self, h: &ContentHash, t: &ThreadId) -> bool {
810                    t == &self.0.context.thread && self.0.contains(&h.0)
811                }
812                fn append(
813                    &mut self,
814                    _: ContentHash,
815                    _: ThreadId,
816                    _: crate::message::Message,
817                ) -> bool {
818                    false
819                }
820                fn frontier(&self, _: &ThreadId) -> Vec<&ContentHash> {
821                    Vec::new()
822                }
823                fn causal_closure(&self, _: &ContentHash, _: &ThreadId) -> Vec<ContentHash> {
824                    Vec::new()
825                }
826            }
827            // Empty closure: all accepted parents are already materialized.
828            let port = Port(self);
829            let resolution = Resolution {
830                store: &port,
831                protocol: p,
832                thread: &self.context.thread,
833                root: Some(&self.context.root),
834                order: Vec::new(),
835                rows: BTreeMap::new(),
836                materialized: Some(self),
837            };
838            let mut declared = false;
839            for (name, step) in &p.steps {
840                if name == BEGIN_KEYWORD || repeat_base_name(name) != data.verb {
841                    continue;
842                }
843                declared = true;
844                if resolution.step(step, data.cause.as_ref()) == VerificationResult::Valid {
845                    steps.insert(name.clone());
846                }
847            }
848            if declared && !root && steps.is_empty() {
849                return Err(String::from("invalid resume position"));
850            }
851        }
852        if let Some(ranks) = self.ranks.get(&data.verb) {
853            let rank = steps
854                .iter()
855                .filter_map(|s| ranks.get(s))
856                .copied()
857                .max()
858                .unwrap_or(0);
859            self.progress
860                .entry(data.verb.clone())
861                .and_modify(|v| *v = (*v).max(rank))
862                .or_insert(rank);
863        }
864        self.entries.insert(PositionFact {
865            metadata: data,
866            steps,
867        });
868        Ok(())
869    }
870}
871
872#[cfg(test)]
873mod materialized_tests {
874    use super::*;
875    use crate::message::{Message, Performative, WrapperType};
876    use crate::sexpr::SExpr;
877    use alloc::{boxed::Box, format, vec};
878    use core::cell::Cell;
879    fn protocol(depth: usize) -> CausalProtocol {
880        let mut steps = BTreeMap::new();
881        for (name, parent, next) in [
882            (String::from("begin"), None, Some(String::from("open"))),
883            ("open".into(), Some("begin".into()), Some("tick#1".into())),
884        ] {
885            steps.insert(
886                name.clone(),
887                StepDecl {
888                    performative: name,
889                    predecessors: parent.into_iter().map(NodeRef::Single).collect(),
890                    successors: next.into_iter().map(NodeRef::Single).collect(),
891                },
892            );
893        }
894        for i in 1..=depth {
895            let name = format!("tick#{i}");
896            steps.insert(
897                name.clone(),
898                StepDecl {
899                    performative: name,
900                    predecessors: vec![NodeRef::Single(if i == 1 {
901                        "open".into()
902                    } else {
903                        format!("tick#{}", i - 1)
904                    })],
905                    successors: if i == depth {
906                        vec![]
907                    } else {
908                        vec![NodeRef::Single(format!("tick#{}", i + 1))]
909                    },
910                },
911            );
912        }
913        CausalProtocol { steps }
914    }
915    fn message(v: &str, cause: CausedBy, nonce: usize) -> Message {
916        let simple = Message::Simple {
917            performative: Performative::Custom(v.into()),
918            recipient: None,
919            content: format!("\"{nonce}\"").parse::<SExpr>().unwrap(),
920            params: vec![],
921            sender: Some("@a".into()),
922            thread: Some("resume".into()),
923            caused_by: Some(cause),
924        };
925        if v == "hello" {
926            Message::Wrapped {
927                wrapper: WrapperType::WithRoles,
928                params: vec![],
929                content: Box::new(simple),
930            }
931        } else {
932            simple
933        }
934    }
935    fn id(m: &Message) -> String {
936        crate::equivocation::message_content_hash(m.innermost_simple().unwrap())
937    }
938    struct Port<'a>(&'a MaterializedPositions, Cell<usize>);
939    impl MessageStore for Port<'_> {
940        fn materialized_positions(&self) -> Option<&MaterializedPositions> {
941            Some(self.0)
942        }
943        fn lookup(&self, _: &ContentHash) -> Option<&Message> {
944            self.1.set(self.1.get() + 1);
945            None
946        }
947        fn lookup_in_thread(&self, _: &ContentHash, _: &ThreadId) -> Option<&Message> {
948            self.1.set(self.1.get() + 1);
949            None
950        }
951        fn contains(&self, _: &ContentHash, _: &ThreadId) -> bool {
952            false
953        }
954        fn append(&mut self, _: ContentHash, _: ThreadId, _: Message) -> bool {
955            false
956        }
957        fn frontier(&self, _: &ThreadId) -> Vec<&ContentHash> {
958            vec![]
959        }
960        fn causal_closure(&self, _: &ContentHash, _: &ThreadId) -> Vec<ContentHash> {
961            panic!("ancestor replay")
962        }
963    }
964    #[test]
965    fn native_progress_oracle_and_compact_tail() {
966        let p = protocol(8);
967        let root = message("hello", CausedBy::Begin, 0);
968        let rootid = id(&root);
969        let mut cache = MaterializedPositions::new(
970            PositionContext {
971                code: [1; 32],
972                root: ContentHash(rootid.clone()),
973                thread: ThreadId("resume".into()),
974            },
975            Some(&p),
976        )
977        .unwrap();
978        cache.apply_accepted(&root).unwrap();
979        let open = message("open", CausedBy::Single(rootid.clone()), 1);
980        cache.apply_accepted(&open).unwrap();
981        let mut acts = vec![
982            crate::state::Act::from_message(root, "@a").unwrap(),
983            crate::state::Act::from_message(open.clone(), "@a").unwrap(),
984        ];
985        let mut previous = id(&open);
986        for i in 1..=8 {
987            let m = message("tick", CausedBy::Single(previous), i + 1);
988            previous = id(&m);
989            cache.apply_accepted(&m).unwrap();
990            acts.push(crate::state::Act::from_message(m, "@a").unwrap());
991            assert_eq!(cache.progress("tick"), i);
992            assert_eq!(
993                accepted_positions(&p, "tick", &acts.iter().collect::<Vec<_>>())
994                    .into_iter()
995                    .max()
996                    .unwrap_or(0),
997                i
998            );
999            if i < 8 {
1000                let port = Port(&cache, Cell::new(0));
1001                assert_eq!(
1002                    verify(
1003                        "tick",
1004                        Some(&CausedBy::Single(previous.clone())),
1005                        &port,
1006                        &p,
1007                        &ThreadId("resume".into()),
1008                        Some(&ContentHash(rootid.clone()))
1009                    ),
1010                    VerificationResult::Valid
1011                );
1012                assert_eq!(port.1.get(), 0);
1013            }
1014        }
1015    }
1016    #[test]
1017    fn future_tail_after_5000_metadata_facts_no_body_reads() {
1018        let p = protocol(32);
1019        let root = message("hello", CausedBy::Begin, 0);
1020        let rid = id(&root);
1021        let mut c = MaterializedPositions::new(
1022            PositionContext {
1023                code: [2; 32],
1024                root: ContentHash(rid.clone()),
1025                thread: ThreadId("resume".into()),
1026            },
1027            Some(&p),
1028        )
1029        .unwrap();
1030        c.apply_accepted(&root).unwrap();
1031        let open = message("open", CausedBy::Single(rid.clone()), 1);
1032        let oid = id(&open);
1033        c.apply_accepted(&open).unwrap();
1034        let mut previous = oid.clone();
1035        for i in 0..5000 {
1036            if i % 32 == 0 {
1037                previous = oid.clone();
1038            }
1039            let m = message("tick", CausedBy::Single(previous), i + 2);
1040            previous = id(&m);
1041            c.apply_accepted(&m).unwrap();
1042        }
1043        let frozen = c.clone();
1044        assert!(Arc::ptr_eq(
1045            c.entries.root.as_ref().unwrap(),
1046            frozen.entries.root.as_ref().unwrap()
1047        ));
1048        assert!(Arc::ptr_eq(
1049            c.protocol.as_ref().unwrap(),
1050            frozen.protocol.as_ref().unwrap()
1051        ));
1052        assert!(Arc::ptr_eq(&c.ranks, &frozen.ranks));
1053        assert_eq!(c.len(), 5002);
1054        let restored = MaterializedPositions::restore_attested(
1055            c.context.clone(),
1056            Some(&p),
1057            c.metadata().cloned().rev().collect(),
1058        )
1059        .unwrap();
1060        assert_eq!(c, restored);
1061        assert_eq!(c.progress("tick"), 32);
1062        let port = Port(&restored, Cell::new(0));
1063        assert_eq!(
1064            verify(
1065                "tick",
1066                Some(&CausedBy::Single(previous)),
1067                &port,
1068                &p,
1069                &ThreadId("resume".into()),
1070                Some(&ContentHash(rid))
1071            ),
1072            VerificationResult::Valid
1073        );
1074        assert_eq!(port.1.get(), 0);
1075    }
1076    #[test]
1077    fn out_of_order_and_foreign_context_do_not_install_facts() {
1078        let p = protocol(3);
1079        let root = message("hello", CausedBy::Begin, 0);
1080        let rid = id(&root);
1081        let mut c = MaterializedPositions::new(
1082            PositionContext {
1083                code: [3; 32],
1084                root: ContentHash(rid.clone()),
1085                thread: ThreadId("resume".into()),
1086            },
1087            Some(&p),
1088        )
1089        .unwrap();
1090        let m = message("open", CausedBy::Single(rid.clone()), 1);
1091        assert!(c.apply_accepted(&m).is_err());
1092        assert_eq!(c.metadata().count(), 0);
1093        c.apply_accepted(&root).unwrap();
1094        c.apply_accepted(&m).unwrap();
1095        let frozen = c.clone();
1096        let missing = message("tick", CausedBy::Single("missing".into()), 2);
1097        assert!(c.apply_accepted(&missing).is_err());
1098        assert_eq!(c, frozen);
1099        let port = Port(&c, Cell::new(0));
1100        assert!(!matches!(
1101            verify(
1102                "tick",
1103                Some(&CausedBy::Single(id(&m))),
1104                &port,
1105                &p,
1106                &ThreadId("foreign".into()),
1107                Some(&ContentHash(rid.clone()))
1108            ),
1109            VerificationResult::Valid
1110        ));
1111        assert!(!matches!(
1112            verify(
1113                "tick",
1114                Some(&CausedBy::Single(id(&m))),
1115                &port,
1116                &p,
1117                &ThreadId("resume".into()),
1118                Some(&ContentHash("foreign".into()))
1119            ),
1120            VerificationResult::Valid
1121        ));
1122        assert!(MaterializedPositions::restore_attested(
1123            c.context.clone(),
1124            Some(&p),
1125            vec![PositionMetadata {
1126                id: "a".into(),
1127                verb: "tick".into(),
1128                cause: Some(CausedBy::Single("a".into()))
1129            }]
1130        )
1131        .is_err());
1132        let mut no = MaterializedPositions::new(c.context.clone(), None).unwrap();
1133        no.apply_accepted(&root).unwrap();
1134        no.apply_accepted(&m).unwrap();
1135        assert_eq!(no.progress("open"), 0);
1136    }
1137    /// Regression evidence: old accepted_positions indexed only state aliases,
1138    /// so native causal headers incorrectly rendered progress zero. Both valid
1139    /// digest spellings must resolve to the same accepted native position.
1140    #[test]
1141    fn native_progress_indexes_native_causal_ids_and_state_aliases() {
1142        let p = protocol(3);
1143        for state_alias in [false, true] {
1144            let root = message("hello", CausedBy::Begin, 0);
1145            let reference = |m: &Message| {
1146                if state_alias {
1147                    crate::state::wire_address(m.innermost_simple().unwrap())
1148                } else {
1149                    id(m)
1150                }
1151            };
1152            let open = message("open", CausedBy::Single(reference(&root)), 1);
1153            let mut cache = MaterializedPositions::new(
1154                PositionContext {
1155                    code: [9; 32],
1156                    root: ContentHash(id(&root)),
1157                    thread: ThreadId("resume".into()),
1158                },
1159                Some(&p),
1160            )
1161            .unwrap();
1162            cache.apply_accepted(&root).unwrap();
1163            cache.apply_accepted(&open).unwrap();
1164            let mut history = vec![
1165                crate::state::Act::from_message(root, "@a").unwrap(),
1166                crate::state::Act::from_message(open.clone(), "@a").unwrap(),
1167            ];
1168            let mut previous = open;
1169            for i in 1..=3 {
1170                let m = message("tick", CausedBy::Single(reference(&previous)), i + 1);
1171                cache.apply_accepted(&m).unwrap();
1172                history.push(crate::state::Act::from_message(m.clone(), "@a").unwrap());
1173                assert_eq!(
1174                    accepted_positions(&p, "tick", &history.iter().collect::<Vec<_>>())
1175                        .into_iter()
1176                        .max()
1177                        .unwrap_or(0),
1178                    i
1179                );
1180                assert_eq!(cache.progress("tick"), i);
1181                previous = m;
1182            }
1183        }
1184    }
1185}