Skip to main content

cbcl_core/
policy.rs

1//! Unknown predecessor policy: maps verification results to policy outcomes (REQ-305).
2//!
3//! Two policies govern how `VerificationResult::Unknown` is handled:
4//!
5//! - **Reject** — returns `Pending` with retry-after hint; zero mutable state (NFR-204, NFR-302).
6//! - **Buffer** — enqueues the message in a bounded, per-thread [`PendingQueue`] with TTL expiry
7//!   and re-evaluation on store growth (NFR-301, max_pending default 64).
8//!
9//! `Violation` results are *never* buffered regardless of policy. Per
10//! SPEC-003 REQ-315 (resolution-gated rejection), a `Violation` should only
11//! reach [`apply_policy`] once the message is *resolved* — every hash its
12//! `:caused-by` names present in the store; the agent layer downgrades a
13//! provisional `Violation` to `Unknown` before applying policy (see
14//! `Agent::causal_verdict`).
15
16#![forbid(unsafe_code)]
17
18use alloc::collections::VecDeque;
19use alloc::vec::Vec;
20use hashbrown::HashMap;
21
22use crate::message::{CausedBy, Message};
23use crate::protocol::{verify_causal, CausalProtocol, CausalViolation, VerificationResult};
24use crate::store::{ContentHash, MessageStore, ThreadId};
25
26// ---------------------------------------------------------------------------
27// Policy enum
28// ---------------------------------------------------------------------------
29
30/// Policy for handling `VerificationResult::Unknown` (predecessor not yet in store).
31#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub enum UnknownPredecessorPolicy {
33    /// Reject unknown predecessors immediately. Returns `Pending` with retry hint.
34    /// Preserves zero mutable state (NFR-204, NFR-302).
35    #[default]
36    Reject,
37    /// Buffer messages with unknown predecessors for later re-evaluation.
38    Buffer {
39        /// Maximum number of pending messages per thread (NFR-301, default 64).
40        max_pending: usize,
41        /// Time-to-live in seconds for buffered entries. Expired entries yield `CausalTimeout`.
42        ttl: u64,
43    },
44}
45
46impl UnknownPredecessorPolicy {
47    /// Create a `Buffer` policy with default settings (max_pending=64).
48    pub fn buffer(ttl: u64) -> Self {
49        UnknownPredecessorPolicy::Buffer {
50            max_pending: 64,
51            ttl,
52        }
53    }
54}
55
56// ---------------------------------------------------------------------------
57// Policy outcome
58// ---------------------------------------------------------------------------
59
60/// Reason a message is pending under the Reject policy.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum PendingReason {
63    /// Causal predecessor not yet in the local store.
64    CausalPending,
65}
66
67/// Reason a buffered message was dropped.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum DropReason {
70    /// TTL expired while waiting for predecessor.
71    CausalTimeout,
72    /// Buffer was full; this entry was the oldest and got evicted.
73    Evicted,
74}
75
76/// Result of applying a policy to a verification result.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum PolicyOutcome {
79    /// Message passed causal verification.
80    Accept,
81    /// Message violated causal constraints — never buffered.
82    Reject(CausalViolation),
83    /// Under Reject policy: predecessor unknown, sender should retry.
84    Pending(PendingReason),
85    /// Under Buffer policy: message enqueued for later re-evaluation.
86    Buffered,
87}
88
89// ---------------------------------------------------------------------------
90// apply_policy — stateless mapping  (CON-302)
91// ---------------------------------------------------------------------------
92
93/// Map a `VerificationResult` + `UnknownPredecessorPolicy` to a `PolicyOutcome`.
94///
95/// This function is pure: it does not mutate any state. Under the `Buffer` policy
96/// the caller is responsible for actually inserting the message into a [`PendingQueue`].
97///
98/// `Violation` maps to `Reject` unconditionally, so per SPEC-003 REQ-315 the
99/// caller must apply the resolution gate first — a provisional `Violation`
100/// (some named `:caused-by` hash absent from the store) can be superseded by
101/// `Valid` at resolution under an `(any …)` clause, and must be handed in as
102/// `Unknown` so action waits for resolution. A resolved `Violation` still
103/// maps to `Reject`.
104pub fn apply_policy(
105    result: &VerificationResult,
106    policy: &UnknownPredecessorPolicy,
107) -> PolicyOutcome {
108    match result {
109        VerificationResult::Valid => PolicyOutcome::Accept,
110        VerificationResult::Violation(v) => PolicyOutcome::Reject(v.clone()),
111        VerificationResult::Unknown => match policy {
112            UnknownPredecessorPolicy::Reject => {
113                PolicyOutcome::Pending(PendingReason::CausalPending)
114            }
115            UnknownPredecessorPolicy::Buffer { .. } => PolicyOutcome::Buffered,
116        },
117    }
118}
119
120// ---------------------------------------------------------------------------
121// PendingQueue — per-thread bounded buffer (NFR-301)
122// ---------------------------------------------------------------------------
123
124/// A buffered entry awaiting re-evaluation.
125#[derive(Debug, Clone)]
126pub struct PendingEntry {
127    /// Content hash of the buffered message.
128    pub hash: ContentHash,
129    /// The buffered message.
130    pub message: Message,
131    /// Thread the message belongs to.
132    pub thread: ThreadId,
133    /// Performative type string for re-verification.
134    pub performative: alloc::string::String,
135    /// Caused-by reference for re-verification.
136    pub caused_by: Option<CausedBy>,
137    /// Timestamp (seconds since epoch) when the entry was inserted.
138    pub inserted_at: u64,
139}
140
141/// Per-thread bounded queue for messages with unknown predecessors.
142///
143/// Each thread has an independent bounded queue with `max_pending` capacity (NFR-301).
144/// Entries expire after `ttl` seconds. When a thread's queue is full the oldest entry
145/// is evicted. Re-evaluation happens when the caller signals store growth.
146#[derive(Debug, Clone)]
147pub struct PendingQueue {
148    /// Maximum entries per thread.
149    max_pending: usize,
150    /// TTL in seconds.
151    ttl: u64,
152    /// Per-thread queues.
153    queues: HashMap<ThreadId, VecDeque<PendingEntry>>,
154}
155
156impl PendingQueue {
157    /// Create a new `PendingQueue` with the given bounds.
158    pub fn new(max_pending: usize, ttl: u64) -> Self {
159        PendingQueue {
160            max_pending,
161            ttl,
162            queues: HashMap::new(),
163        }
164    }
165
166    /// Create from a `Buffer` policy. Panics if given `Reject`.
167    pub fn from_policy(policy: &UnknownPredecessorPolicy) -> Self {
168        match policy {
169            UnknownPredecessorPolicy::Buffer { max_pending, ttl } => {
170                PendingQueue::new(*max_pending, *ttl)
171            }
172            UnknownPredecessorPolicy::Reject => {
173                panic!("PendingQueue::from_policy called with Reject policy")
174            }
175        }
176    }
177
178    /// Enqueue a pending message. If the thread's queue is at capacity,
179    /// the oldest entry is evicted and returned as `DropReason::Evicted`.
180    pub fn enqueue(&mut self, entry: PendingEntry) -> Option<(PendingEntry, DropReason)> {
181        let queue = self.queues.entry(entry.thread.clone()).or_default();
182        let evicted = if queue.len() >= self.max_pending {
183            queue.pop_front().map(|e| (e, DropReason::Evicted))
184        } else {
185            None
186        };
187        queue.push_back(entry);
188        evicted
189    }
190
191    /// Remove and return all entries whose TTL has expired at the given `now` timestamp.
192    pub fn expire(&mut self, now: u64) -> Vec<(PendingEntry, DropReason)> {
193        let mut expired = Vec::new();
194        for queue in self.queues.values_mut() {
195            // Entries are insertion-ordered, so drain from front while expired.
196            while let Some(front) = queue.front() {
197                if now.saturating_sub(front.inserted_at) >= self.ttl {
198                    let entry = queue.pop_front().unwrap();
199                    expired.push((entry, DropReason::CausalTimeout));
200                } else {
201                    break;
202                }
203            }
204        }
205        expired
206    }
207
208    /// Re-evaluate all pending entries against the (grown) store.
209    ///
210    /// Returns entries that now resolve to `Accept` or `Reject`. Entries still
211    /// `Unknown` remain in the queue.
212    ///
213    /// **Caution**: this method evaluates every entry against the supplied
214    /// `protocol`, regardless of whether the protocol declares a step for the
215    /// entry's performative. Since [`verify_causal`] returns `Valid` for
216    /// performatives the protocol does not constrain, calling this with an
217    /// unrelated protocol will incorrectly flush entries that are still
218    /// waiting on their real predecessor. Callers with multiple protocols
219    /// should prefer [`PendingQueue::re_evaluate_with`], which lets the
220    /// caller decide per entry.
221    pub fn re_evaluate<S: MessageStore>(
222        &mut self,
223        store: &S,
224        protocol: &CausalProtocol,
225    ) -> Vec<(PendingEntry, PolicyOutcome)> {
226        self.re_evaluate_with(|entry, thread_id| {
227            Some(verify_causal(
228                &entry.performative,
229                entry.caused_by.as_ref(),
230                store,
231                protocol,
232                thread_id,
233            ))
234        })
235    }
236
237    /// Re-evaluate pending entries with caller-supplied verification.
238    ///
239    /// For each entry, the closure returns `Some(VerificationResult)` to
240    /// resolve the entry (or keep it pending on `Unknown`), or `None` to
241    /// indicate "no applicable protocol — leave the entry untouched". This
242    /// lets callers compose multiple protocols and skip entries that no
243    /// installed protocol constrains, avoiding the spurious-`Accept` hazard
244    /// described on [`Self::re_evaluate`].
245    pub fn re_evaluate_with<F>(&mut self, mut decide: F) -> Vec<(PendingEntry, PolicyOutcome)>
246    where
247        F: FnMut(&PendingEntry, &ThreadId) -> Option<VerificationResult>,
248    {
249        let mut resolved = Vec::new();
250
251        for (thread_id, queue) in self.queues.iter_mut() {
252            let mut i = 0;
253            while i < queue.len() {
254                let entry = &queue[i];
255                match decide(entry, thread_id) {
256                    None | Some(VerificationResult::Unknown) => {
257                        i += 1; // still pending
258                    }
259                    Some(VerificationResult::Valid) => {
260                        let entry = queue.remove(i).unwrap();
261                        resolved.push((entry, PolicyOutcome::Accept));
262                    }
263                    Some(VerificationResult::Violation(v)) => {
264                        let entry = queue.remove(i).unwrap();
265                        resolved.push((entry, PolicyOutcome::Reject(v)));
266                    }
267                }
268            }
269        }
270
271        resolved
272    }
273
274    /// Total number of buffered entries across all threads.
275    pub fn len(&self) -> usize {
276        self.queues.values().map(|q| q.len()).sum()
277    }
278
279    /// Whether the queue is empty.
280    pub fn is_empty(&self) -> bool {
281        self.queues.values().all(|q| q.is_empty())
282    }
283
284    /// Number of buffered entries for a specific thread.
285    pub fn thread_len(&self, thread: &ThreadId) -> usize {
286        self.queues.get(thread).map_or(0, |q| q.len())
287    }
288
289    /// Maximum entries per thread.
290    pub fn max_pending(&self) -> usize {
291        self.max_pending
292    }
293
294    /// TTL in seconds.
295    pub fn ttl(&self) -> u64 {
296        self.ttl
297    }
298}
299
300// ---------------------------------------------------------------------------
301// Tests (TEST-305)
302// ---------------------------------------------------------------------------
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use crate::message::{CausedBy, Message, Performative};
308    use crate::protocol::{CausalProtocol, CausalViolation, NodeRef, StepDecl, VerificationResult};
309    use crate::sexpr::{Atom, SExpr};
310    use crate::store::{ContentHash, MessageStore, ThreadId, ThreadedMessageStore};
311    use alloc::collections::BTreeMap;
312    use alloc::string::ToString;
313    use alloc::vec;
314
315    fn make_message(performative: &str) -> Message {
316        Message::Simple {
317            performative: Performative::Custom(performative.to_string()),
318            recipient: None,
319            content: SExpr::Atom(Atom::Str("x".into())),
320            params: vec![],
321            thread: None,
322            sender: None,
323            caused_by: None,
324        }
325    }
326
327    fn make_thread() -> ThreadId {
328        ThreadId("t1".to_string())
329    }
330
331    fn make_hash(s: &str) -> ContentHash {
332        ContentHash(s.to_string())
333    }
334
335    // ---- apply_policy tests ----
336
337    #[test]
338    fn test_apply_policy_valid_accept() {
339        let result = VerificationResult::Valid;
340        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
341        assert_eq!(outcome, PolicyOutcome::Accept);
342
343        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
344        assert_eq!(outcome, PolicyOutcome::Accept);
345    }
346
347    #[test]
348    fn test_apply_policy_violation_reject() {
349        let v = CausalViolation::MissingCausedBy;
350        let result = VerificationResult::Violation(v.clone());
351
352        // Violation -> Reject regardless of policy
353        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
354        assert_eq!(outcome, PolicyOutcome::Reject(v.clone()));
355
356        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
357        assert_eq!(outcome, PolicyOutcome::Reject(v));
358    }
359
360    #[test]
361    fn test_apply_policy_unknown_reject_pending() {
362        let result = VerificationResult::Unknown;
363        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::Reject);
364        assert_eq!(
365            outcome,
366            PolicyOutcome::Pending(PendingReason::CausalPending)
367        );
368    }
369
370    #[test]
371    fn test_apply_policy_unknown_buffer_buffered() {
372        let result = VerificationResult::Unknown;
373        let outcome = apply_policy(&result, &UnknownPredecessorPolicy::buffer(60));
374        assert_eq!(outcome, PolicyOutcome::Buffered);
375    }
376
377    // ---- Reject policy: zero mutable state (NFR-204, NFR-302) ----
378
379    #[test]
380    fn test_reject_policy_no_mutable_state() {
381        // Reject policy is a simple enum variant with no fields.
382        // apply_policy with Reject never allocates or mutates.
383        let policy = UnknownPredecessorPolicy::Reject;
384        let results = [
385            VerificationResult::Valid,
386            VerificationResult::Unknown,
387            VerificationResult::Violation(CausalViolation::MissingCausedBy),
388        ];
389        for r in &results {
390            let _ = apply_policy(r, &policy);
391        }
392        // If this compiles and runs, Reject preserves zero mutable state.
393        assert_eq!(policy, UnknownPredecessorPolicy::Reject);
394    }
395
396    // ---- PendingQueue tests ----
397
398    fn make_entry(hash: &str, perf: &str, thread: &ThreadId, ts: u64) -> PendingEntry {
399        PendingEntry {
400            hash: make_hash(hash),
401            message: make_message(perf),
402            thread: thread.clone(),
403            performative: perf.to_string(),
404            caused_by: Some(CausedBy::Single(hash.to_string())),
405            inserted_at: ts,
406        }
407    }
408
409    #[test]
410    fn test_pending_queue_enqueue_within_capacity() {
411        let mut pq = PendingQueue::new(64, 300);
412        let tid = make_thread();
413        let evicted = pq.enqueue(make_entry("h1", "ask", &tid, 100));
414        assert!(evicted.is_none());
415        assert_eq!(pq.len(), 1);
416        assert_eq!(pq.thread_len(&tid), 1);
417    }
418
419    #[test]
420    fn test_pending_queue_evicts_oldest_at_capacity() {
421        let mut pq = PendingQueue::new(2, 300);
422        let tid = make_thread();
423
424        pq.enqueue(make_entry("h1", "ask", &tid, 100));
425        pq.enqueue(make_entry("h2", "ask", &tid, 101));
426
427        // Third enqueue should evict h1
428        let evicted = pq.enqueue(make_entry("h3", "ask", &tid, 102));
429        assert!(evicted.is_some());
430        let (entry, reason) = evicted.unwrap();
431        assert_eq!(entry.hash, make_hash("h1"));
432        assert_eq!(reason, DropReason::Evicted);
433        assert_eq!(pq.thread_len(&tid), 2);
434    }
435
436    #[test]
437    fn test_pending_queue_per_thread_isolation() {
438        let mut pq = PendingQueue::new(2, 300);
439        let t1 = ThreadId("t1".to_string());
440        let t2 = ThreadId("t2".to_string());
441
442        pq.enqueue(make_entry("h1", "ask", &t1, 100));
443        pq.enqueue(make_entry("h2", "ask", &t1, 101));
444        pq.enqueue(make_entry("h3", "ask", &t2, 100));
445
446        assert_eq!(pq.thread_len(&t1), 2);
447        assert_eq!(pq.thread_len(&t2), 1);
448        assert_eq!(pq.len(), 3);
449    }
450
451    #[test]
452    fn test_pending_queue_ttl_expiry() {
453        let mut pq = PendingQueue::new(64, 10); // 10-second TTL
454        let tid = make_thread();
455
456        pq.enqueue(make_entry("h1", "ask", &tid, 100));
457        pq.enqueue(make_entry("h2", "ask", &tid, 105));
458
459        // At t=109, nothing expired (TTL=10)
460        let expired = pq.expire(109);
461        assert!(expired.is_empty());
462
463        // At t=110, h1 expires (100 + 10 = 110)
464        let expired = pq.expire(110);
465        assert_eq!(expired.len(), 1);
466        assert_eq!(expired[0].0.hash, make_hash("h1"));
467        assert_eq!(expired[0].1, DropReason::CausalTimeout);
468
469        // h2 still pending
470        assert_eq!(pq.len(), 1);
471
472        // At t=115, h2 expires
473        let expired = pq.expire(115);
474        assert_eq!(expired.len(), 1);
475        assert_eq!(expired[0].0.hash, make_hash("h2"));
476    }
477
478    #[test]
479    fn test_pending_queue_re_evaluate_on_store_growth() {
480        // Set up a protocol: ask -> reply
481        let mut steps = BTreeMap::new();
482        steps.insert(
483            "ask".to_string(),
484            StepDecl {
485                performative: "ask".to_string(),
486                predecessors: vec![],
487                successors: vec![NodeRef::Single("reply".to_string())],
488            },
489        );
490        steps.insert(
491            "reply".to_string(),
492            StepDecl {
493                performative: "reply".to_string(),
494                predecessors: vec![NodeRef::Single("ask".to_string())],
495                successors: vec![],
496            },
497        );
498        let protocol = CausalProtocol { steps };
499
500        let tid = make_thread();
501        let mut store = ThreadedMessageStore::new();
502        let mut pq = PendingQueue::new(64, 300);
503
504        // Buffer a "reply" that references a missing "ask" predecessor
505        let entry = PendingEntry {
506            hash: make_hash("reply1"),
507            message: make_message("reply"),
508            thread: tid.clone(),
509            performative: "reply".to_string(),
510            caused_by: Some(CausedBy::Single("ask1".to_string())),
511            inserted_at: 100,
512        };
513        pq.enqueue(entry);
514
515        // Re-evaluate with empty store: still Unknown
516        let resolved = pq.re_evaluate(&store, &protocol);
517        assert!(resolved.is_empty());
518        assert_eq!(pq.len(), 1);
519
520        // Now add the predecessor "ask" to the store
521        let ask_msg = make_message("ask");
522        store.append(make_hash("ask1"), tid.clone(), ask_msg);
523
524        // Re-evaluate: should now resolve to Accept
525        let resolved = pq.re_evaluate(&store, &protocol);
526        assert_eq!(resolved.len(), 1);
527        assert_eq!(resolved[0].1, PolicyOutcome::Accept);
528        assert_eq!(pq.len(), 0);
529    }
530
531    #[test]
532    fn test_pending_queue_violation_on_re_evaluate() {
533        // Protocol where "reply" expects predecessor "ask"
534        let mut steps = BTreeMap::new();
535        steps.insert(
536            "ask".to_string(),
537            StepDecl {
538                performative: "ask".to_string(),
539                predecessors: vec![],
540                successors: vec![NodeRef::Single("reply".to_string())],
541            },
542        );
543        steps.insert(
544            "reply".to_string(),
545            StepDecl {
546                performative: "reply".to_string(),
547                predecessors: vec![NodeRef::Single("ask".to_string())],
548                successors: vec![],
549            },
550        );
551        let protocol = CausalProtocol { steps };
552
553        let tid = make_thread();
554        let mut store = ThreadedMessageStore::new();
555        let mut pq = PendingQueue::new(64, 300);
556
557        // Buffer a "reply" referencing "wrong_hash"
558        let entry = PendingEntry {
559            hash: make_hash("reply1"),
560            message: make_message("reply"),
561            thread: tid.clone(),
562            performative: "reply".to_string(),
563            caused_by: Some(CausedBy::Single("wrong_hash".to_string())),
564            inserted_at: 100,
565        };
566        pq.enqueue(entry);
567
568        // Add a message with the referenced hash but wrong performative type
569        let wrong_msg = make_message("notify"); // not "ask"
570        store.append(make_hash("wrong_hash"), tid.clone(), wrong_msg);
571
572        // Re-evaluate: should resolve to Reject (InvalidPredecessor)
573        let resolved = pq.re_evaluate(&store, &protocol);
574        assert_eq!(resolved.len(), 1);
575        match &resolved[0].1 {
576            PolicyOutcome::Reject(_) => {} // expected
577            other => panic!("expected Reject, got {:?}", other),
578        }
579        assert_eq!(pq.len(), 0);
580    }
581
582    #[test]
583    fn test_default_policy_is_reject() {
584        assert_eq!(
585            UnknownPredecessorPolicy::default(),
586            UnknownPredecessorPolicy::Reject
587        );
588    }
589
590    #[test]
591    fn test_buffer_convenience_constructor() {
592        let policy = UnknownPredecessorPolicy::buffer(120);
593        assert_eq!(
594            policy,
595            UnknownPredecessorPolicy::Buffer {
596                max_pending: 64,
597                ttl: 120,
598            }
599        );
600    }
601
602    #[test]
603    fn test_from_policy_buffer() {
604        let policy = UnknownPredecessorPolicy::buffer(60);
605        let pq = PendingQueue::from_policy(&policy);
606        assert_eq!(pq.max_pending(), 64);
607        assert_eq!(pq.ttl(), 60);
608    }
609
610    #[test]
611    #[should_panic(expected = "Reject policy")]
612    fn test_from_policy_reject_panics() {
613        PendingQueue::from_policy(&UnknownPredecessorPolicy::Reject);
614    }
615}