1#![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#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub enum UnknownPredecessorPolicy {
33 #[default]
36 Reject,
37 Buffer {
39 max_pending: usize,
41 ttl: u64,
43 },
44}
45
46impl UnknownPredecessorPolicy {
47 pub fn buffer(ttl: u64) -> Self {
49 UnknownPredecessorPolicy::Buffer {
50 max_pending: 64,
51 ttl,
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum PendingReason {
63 CausalPending,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum DropReason {
70 CausalTimeout,
72 Evicted,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum PolicyOutcome {
79 Accept,
81 Reject(CausalViolation),
83 Pending(PendingReason),
85 Buffered,
87}
88
89pub 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#[derive(Debug, Clone)]
126pub struct PendingEntry {
127 pub hash: ContentHash,
129 pub message: Message,
131 pub thread: ThreadId,
133 pub performative: alloc::string::String,
135 pub caused_by: Option<CausedBy>,
137 pub inserted_at: u64,
139}
140
141#[derive(Debug, Clone)]
147pub struct PendingQueue {
148 max_pending: usize,
150 ttl: u64,
152 queues: HashMap<ThreadId, VecDeque<PendingEntry>>,
154}
155
156impl PendingQueue {
157 pub fn new(max_pending: usize, ttl: u64) -> Self {
159 PendingQueue {
160 max_pending,
161 ttl,
162 queues: HashMap::new(),
163 }
164 }
165
166 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 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 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 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 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 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; }
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 pub fn len(&self) -> usize {
276 self.queues.values().map(|q| q.len()).sum()
277 }
278
279 pub fn is_empty(&self) -> bool {
281 self.queues.values().all(|q| q.is_empty())
282 }
283
284 pub fn thread_len(&self, thread: &ThreadId) -> usize {
286 self.queues.get(thread).map_or(0, |q| q.len())
287 }
288
289 pub fn max_pending(&self) -> usize {
291 self.max_pending
292 }
293
294 pub fn ttl(&self) -> u64 {
296 self.ttl
297 }
298}
299
300#[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 #[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 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 #[test]
380 fn test_reject_policy_no_mutable_state() {
381 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 assert_eq!(policy, UnknownPredecessorPolicy::Reject);
394 }
395
396 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 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); 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 let expired = pq.expire(109);
461 assert!(expired.is_empty());
462
463 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 assert_eq!(pq.len(), 1);
471
472 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 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 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 let resolved = pq.re_evaluate(&store, &protocol);
517 assert!(resolved.is_empty());
518 assert_eq!(pq.len(), 1);
519
520 let ask_msg = make_message("ask");
522 store.append(make_hash("ask1"), tid.clone(), ask_msg);
523
524 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 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 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 let wrong_msg = make_message("notify"); store.append(make_hash("wrong_hash"), tid.clone(), wrong_msg);
571
572 let resolved = pq.re_evaluate(&store, &protocol);
574 assert_eq!(resolved.len(), 1);
575 match &resolved[0].1 {
576 PolicyOutcome::Reject(_) => {} 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}