1#![forbid(unsafe_code)]
14
15use alloc::collections::BTreeMap;
16use alloc::collections::BTreeSet;
17use alloc::string::String;
18use alloc::string::ToString;
19use alloc::vec::Vec;
20
21use crate::dialect::Dialect;
22
23fn ln_approx(x: f64) -> f64 {
32 if x <= 0.0 {
33 return f64::NEG_INFINITY;
34 }
35 let bits = x.to_bits();
37 let exp = ((bits >> 52) & 0x7FF) as i64 - 1023;
38 let mantissa = f64::from_bits((bits & 0x000F_FFFF_FFFF_FFFF) | 0x3FF0_0000_0000_0000);
39
40 let t = (mantissa - 1.0) / (mantissa + 1.0);
43 let t2 = t * t;
44 let ln_m = 2.0
46 * t
47 * (1.0
48 + t2 * (1.0 / 3.0
49 + t2 * (1.0 / 5.0
50 + t2 * (1.0 / 7.0 + t2 * (1.0 / 9.0 + t2 * (1.0 / 11.0 + t2 / 13.0))))));
51
52 (exp as f64) * core::f64::consts::LN_2 + ln_m
53}
54
55#[derive(Debug, Clone, PartialEq)]
61#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
62pub enum Topology {
63 FullyConnected,
65 Ring,
67 Random(f64),
69}
70
71#[derive(Debug, Clone, PartialEq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
74pub struct GossipConfig {
75 pub transmission_probability: f64,
77 pub max_rounds: u32,
79 pub topology: Topology,
81}
82
83impl Default for GossipConfig {
84 fn default() -> Self {
85 Self {
86 transmission_probability: 0.8,
87 max_rounds: 100,
88 topology: Topology::FullyConnected,
89 }
90 }
91}
92
93#[derive(Debug, Clone)]
102#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
103struct Lcg {
104 seed: u64,
105}
106
107impl Lcg {
108 fn new(seed: u64) -> Self {
109 Self { seed }
110 }
111
112 fn next_f64(&mut self) -> f64 {
114 let m: u64 = 1 << 31;
115 self.seed = (self.seed.wrapping_mul(1_103_515_245).wrapping_add(12345)) % m;
116 self.seed as f64 / m as f64
117 }
118}
119
120#[derive(Debug, Clone)]
126#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
127pub struct PropagationState {
128 pub dialect: Dialect,
130 pub infected: BTreeSet<String>,
132 pub susceptible: BTreeSet<String>,
134 pub round: u32,
136 pub transmission_prob: f64,
138}
139
140impl PropagationState {
141 pub fn coverage(&self) -> f64 {
143 let total = self.infected.len() + self.susceptible.len();
144 if total == 0 {
145 1.0
146 } else {
147 self.infected.len() as f64 / total as f64
148 }
149 }
150
151 pub fn is_complete(&self) -> bool {
153 self.susceptible.is_empty()
154 }
155}
156
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
163#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164pub struct GossipStats {
165 pub total_rounds: u64,
167 pub successful_propagations: u64,
169 pub failed_propagations: u64,
171}
172
173#[derive(Debug, Clone)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180pub struct SimulationResult {
181 pub dialect_name: String,
183 pub rounds: u32,
185 pub final_coverage: f64,
187 pub successful: bool,
189}
190
191#[derive(Debug, Clone)]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
204pub struct GossipNetwork {
205 agents: BTreeMap<String, BTreeSet<String>>,
207 topology: BTreeMap<String, BTreeSet<String>>,
209 active_propagations: BTreeMap<String, PropagationState>,
211 stats: GossipStats,
213 config: GossipConfig,
215 rng: Lcg,
217}
218
219impl GossipNetwork {
220 pub fn new(config: GossipConfig, seed: u64) -> Self {
222 Self {
223 agents: BTreeMap::new(),
224 topology: BTreeMap::new(),
225 active_propagations: BTreeMap::new(),
226 stats: GossipStats::default(),
227 config,
228 rng: Lcg::new(seed),
229 }
230 }
231
232 pub fn with_defaults() -> Self {
235 Self::new(GossipConfig::default(), 1_234_567)
236 }
237
238 pub fn add_agent(&mut self, agent_id: impl Into<String>) -> bool {
246 let id = agent_id.into();
247 if self.agents.contains_key(&id) {
248 return false;
249 }
250 self.agents.insert(id.clone(), BTreeSet::new());
251 self.topology.insert(id.clone(), BTreeSet::new());
252 self.update_topology(&id);
253 true
254 }
255
256 pub fn remove_agent(&mut self, agent_id: &str) -> bool {
261 if self.agents.remove(agent_id).is_none() {
262 return false;
263 }
264 self.topology.remove(agent_id);
265 for neighbors in self.topology.values_mut() {
267 neighbors.remove(agent_id);
268 }
269 for prop in self.active_propagations.values_mut() {
271 prop.infected.remove(agent_id);
272 prop.susceptible.remove(agent_id);
273 }
274 true
275 }
276
277 pub fn agent_ids(&self) -> Vec<&str> {
279 self.agents.keys().map(|s| s.as_str()).collect()
280 }
281
282 pub fn agent_count(&self) -> usize {
284 self.agents.len()
285 }
286
287 pub fn neighbors(&self, agent_id: &str) -> Option<Vec<&str>> {
289 self.topology
290 .get(agent_id)
291 .map(|s| s.iter().map(|n| n.as_str()).collect())
292 }
293
294 fn update_topology(&mut self, new_agent_id: &str) {
297 match &self.config.topology {
298 Topology::FullyConnected => {
299 let all_ids: Vec<String> = self.agents.keys().cloned().collect();
300 for id in &all_ids {
301 if id != new_agent_id {
302 self.topology
304 .get_mut(new_agent_id)
305 .unwrap()
306 .insert(id.clone());
307 self.topology
309 .get_mut(id.as_str())
310 .unwrap()
311 .insert(String::from(new_agent_id));
312 }
313 }
314 }
315 Topology::Ring => {
316 let all_ids: Vec<String> = self.agents.keys().cloned().collect();
317 if all_ids.len() > 1 {
318 let others: Vec<&String> = all_ids
320 .iter()
321 .filter(|id| id.as_str() != new_agent_id)
322 .collect();
323 let count = others.len().min(2);
324 for id in &others[..count] {
325 self.topology
326 .get_mut(new_agent_id)
327 .unwrap()
328 .insert((*id).clone());
329 self.topology
330 .get_mut(id.as_str())
331 .unwrap()
332 .insert(String::from(new_agent_id));
333 }
334 }
335 }
336 Topology::Random(p) => {
337 let p = *p;
338 let all_ids: Vec<String> = self.agents.keys().cloned().collect();
339 for id in &all_ids {
340 if id.as_str() != new_agent_id && self.rng.next_f64() < p {
341 self.topology
342 .get_mut(new_agent_id)
343 .unwrap()
344 .insert(id.clone());
345 self.topology
346 .get_mut(id.as_str())
347 .unwrap()
348 .insert(String::from(new_agent_id));
349 }
350 }
351 }
352 }
353 }
354
355 pub fn announce_dialect(&mut self, dialect: Dialect, initial_agent_id: &str) -> Option<String> {
366 if !self.agents.contains_key(initial_agent_id) {
367 return None;
368 }
369 if self.active_propagations.contains_key(&dialect.name) {
370 return None;
371 }
372
373 let dialect_name = dialect.name.clone();
374
375 self.agents
377 .get_mut(initial_agent_id)
378 .unwrap()
379 .insert(dialect_name.clone());
380
381 let mut infected = BTreeSet::new();
382 infected.insert(String::from(initial_agent_id));
383
384 let susceptible: BTreeSet<String> = self
385 .agents
386 .keys()
387 .filter(|id| id.as_str() != initial_agent_id)
388 .cloned()
389 .collect();
390
391 let transmission_prob = self.config.transmission_probability;
392
393 self.active_propagations.insert(
394 dialect_name.clone(),
395 PropagationState {
396 dialect,
397 infected,
398 susceptible,
399 round: 0,
400 transmission_prob,
401 },
402 );
403
404 #[cfg(feature = "tracing")]
405 tracing::event!(
406 tracing::Level::INFO,
407 dialect = %dialect_name,
408 initial_agent = initial_agent_id,
409 network_size = self.agents.len(),
410 "gossip_announce_dialect"
411 );
412
413 Some(dialect_name)
414 }
415
416 pub fn step(&mut self) -> Vec<(String, Vec<String>)> {
425 let dialect_names: Vec<String> = self.active_propagations.keys().cloned().collect();
426 let mut results = Vec::new();
427
428 for dialect_name in &dialect_names {
429 let newly_infected = self.step_propagation(dialect_name);
430 if !newly_infected.is_empty() {
431 results.push((dialect_name.clone(), newly_infected));
432 }
433 }
434
435 self.cleanup_completed_propagations();
436 self.stats.total_rounds += 1;
437
438 #[cfg(feature = "tracing")]
439 for (name, prop) in &self.active_propagations {
440 tracing::event!(
441 tracing::Level::INFO,
442 dialect = %name,
443 round = prop.round,
444 coverage = prop.coverage(),
445 infected = prop.infected.len(),
446 susceptible = prop.susceptible.len(),
447 "gossip_round_convergence"
448 );
449 }
450
451 results
452 }
453
454 fn step_propagation(&mut self, dialect_name: &str) -> Vec<String> {
455 let prop = match self.active_propagations.get(dialect_name) {
457 Some(p) => p,
458 None => return Vec::new(),
459 };
460
461 let infected: Vec<String> = prop.infected.iter().cloned().collect();
462 let transmission_prob = prop.transmission_prob;
463
464 let mut newly_infected = Vec::new();
466
467 for infected_id in &infected {
468 let neighbor_ids: Vec<String> = self
469 .topology
470 .get(infected_id.as_str())
471 .map(|s| s.iter().cloned().collect())
472 .unwrap_or_default();
473
474 let prop = self.active_propagations.get(dialect_name).unwrap();
475 for neighbor_id in &neighbor_ids {
476 if prop.susceptible.contains(neighbor_id) && self.rng.next_f64() < transmission_prob
477 {
478 newly_infected.push(neighbor_id.clone());
479 }
480 }
481 }
482
483 if let Some(prop) = self.active_propagations.get_mut(dialect_name) {
485 for id in &newly_infected {
486 prop.infected.insert(id.clone());
487 prop.susceptible.remove(id);
488 if let Some(agent_dialects) = self.agents.get_mut(id) {
490 agent_dialects.insert(dialect_name.to_string());
491 }
492 }
493 prop.round += 1;
494 }
495
496 newly_infected
497 }
498
499 fn cleanup_completed_propagations(&mut self) {
500 let max_rounds = self.config.max_rounds;
501 let to_remove: Vec<(String, bool)> = self
502 .active_propagations
503 .iter()
504 .filter_map(|(name, prop)| {
505 if prop.susceptible.is_empty() {
506 Some((name.clone(), true))
507 } else if prop.round >= max_rounds {
508 Some((name.clone(), false))
509 } else {
510 None
511 }
512 })
513 .collect();
514
515 for (name, success) in to_remove {
516 self.active_propagations.remove(&name);
517 if success {
518 self.stats.successful_propagations += 1;
519 } else {
520 self.stats.failed_propagations += 1;
521 }
522 }
523 }
524
525 pub fn receive_gossip(&mut self, agent_id: &str, dialect: &Dialect) -> Result<(), Vec<String>> {
537 let mut violations = Vec::new();
539
540 if !crate::r1::verify_r1_dialect(dialect) {
541 violations.extend(crate::r1::r1_violations(dialect));
542 }
543 if !crate::r2::verify_r2(dialect) {
544 violations.push(alloc::format!(
545 "R2 violation: invalid resource bounds in '{}'",
546 dialect.name
547 ));
548 }
549 if !crate::r3::verify_r3(dialect) {
550 violations.extend(
551 crate::r3::r3_violations(dialect)
552 .into_iter()
553 .map(|v| alloc::format!("R3 violation: {}", v)),
554 );
555 }
556
557 if !violations.is_empty() {
558 return Err(violations);
559 }
560
561 if let Some(agent_dialects) = self.agents.get_mut(agent_id) {
563 agent_dialects.insert(dialect.name.clone());
564 }
565
566 if let Some(prop) = self.active_propagations.get_mut(&dialect.name) {
568 prop.susceptible.remove(agent_id);
569 prop.infected.insert(String::from(agent_id));
570 }
571
572 Ok(())
573 }
574
575 pub fn select_peers(&mut self, agent_id: &str, k: usize) -> Vec<String> {
582 let neighbors: Vec<String> = match self.topology.get(agent_id) {
583 Some(n) => n.iter().cloned().collect(),
584 None => return Vec::new(),
585 };
586
587 if neighbors.len() <= k {
588 return neighbors;
589 }
590
591 let mut shuffled = neighbors;
593 let len = shuffled.len();
594 for i in (1..len).rev() {
595 let r = self.rng.next_f64();
596 let j = (r * (i + 1) as f64) as usize;
597 let j = j.min(i); shuffled.swap(i, j);
599 }
600 shuffled.truncate(k);
601 shuffled
602 }
603
604 pub fn estimate_convergence_time(&self) -> u32 {
614 let n = self.agents.len();
615 if n <= 1 {
616 return 0;
617 }
618 let p = self.config.transmission_probability;
619 let rounds = ln_approx(n as f64) / ln_approx(1.0 + p);
620 rounds as u32 + 1
621 }
622
623 pub fn is_connected(&self) -> bool {
625 if self.agents.is_empty() {
626 return true;
627 }
628
629 let start = match self.agents.keys().next() {
630 Some(id) => id.clone(),
631 None => return true,
632 };
633
634 let mut visited = BTreeSet::new();
635 let mut queue = alloc::vec![start];
636
637 while let Some(current) = queue.pop() {
638 if !visited.insert(current.clone()) {
639 continue;
640 }
641 if let Some(neighbors) = self.topology.get(¤t) {
642 for neighbor in neighbors {
643 if !visited.contains(neighbor) {
644 queue.push(neighbor.clone());
645 }
646 }
647 }
648 }
649
650 visited.len() == self.agents.len()
651 }
652
653 pub fn simulate_propagation(
657 &mut self,
658 dialect: Dialect,
659 initial_agent_id: &str,
660 ) -> Option<SimulationResult> {
661 let dialect_name = self.announce_dialect(dialect, initial_agent_id)?;
662 let mut rounds = 0u32;
663
664 while self.active_propagations.contains_key(&dialect_name) {
665 self.step();
666 rounds += 1;
667 }
668
669 let successful = self
672 .agents
673 .values()
674 .all(|dialects| dialects.contains(&dialect_name));
675
676 Some(SimulationResult {
677 dialect_name,
678 rounds,
679 final_coverage: if successful { 1.0 } else { 0.0 },
680 successful,
681 })
682 }
683
684 pub fn config(&self) -> &GossipConfig {
688 &self.config
689 }
690
691 pub fn stats(&self) -> &GossipStats {
693 &self.stats
694 }
695
696 pub fn active_propagations(&self) -> &BTreeMap<String, PropagationState> {
698 &self.active_propagations
699 }
700
701 pub fn propagation_stats(&self, dialect_name: &str) -> Option<&PropagationState> {
703 self.active_propagations.get(dialect_name)
704 }
705
706 pub fn agent_has_dialect(&self, agent_id: &str, dialect_name: &str) -> bool {
708 self.agents
709 .get(agent_id)
710 .map(|d| d.contains(dialect_name))
711 .unwrap_or(false)
712 }
713}
714
715#[cfg(test)]
720mod tests {
721 use super::*;
722 use crate::dialect::{PerformativeDef, ResourceBounds};
723 use crate::sexpr::{Atom, SExpr};
724 use alloc::string::String;
725
726 fn test_dialect(name: &str) -> Dialect {
727 Dialect {
728 types: Default::default(),
729 roles: Vec::new(),
730 state: None,
731 state_bounds: None,
732 causal_locality: Default::default(),
733 name: String::from(name),
734 extends: Vec::new(),
735 author: None,
736 performatives: vec![PerformativeDef {
737 role: None,
738 name: alloc::format!("{}-action", name),
739 params: Vec::new(),
740 template: SExpr::List(alloc::vec![
741 SExpr::Atom(Atom::Symbol(String::from("effect"))),
742 SExpr::Atom(Atom::Symbol(alloc::format!("{}-effect", name))),
743 ]),
744 }],
745 resources: ResourceBounds {
746 max_depth: 8,
747 max_expansion_size: 512,
748 },
749 examples: Vec::new(),
750 signature: None,
751 hash: None,
752 protocol: None,
753 causal_protocol: None,
754 shapes: Vec::new(),
755 }
756 }
757
758 #[test]
761 fn new_network_is_empty() {
762 let net = GossipNetwork::with_defaults();
763 assert_eq!(net.agent_count(), 0);
764 assert!(net.agent_ids().is_empty());
765 assert!(net.active_propagations().is_empty());
766 }
767
768 #[test]
769 fn default_config() {
770 let config = GossipConfig::default();
771 assert!((config.transmission_probability - 0.8).abs() < f64::EPSILON);
772 assert_eq!(config.max_rounds, 100);
773 assert_eq!(config.topology, Topology::FullyConnected);
774 }
775
776 #[test]
779 fn add_agent() {
780 let mut net = GossipNetwork::with_defaults();
781 assert!(net.add_agent("alice"));
782 assert!(net.add_agent("bob"));
783 assert!(!net.add_agent("alice")); assert_eq!(net.agent_count(), 2);
785 }
786
787 #[test]
788 fn remove_agent() {
789 let mut net = GossipNetwork::with_defaults();
790 net.add_agent("alice");
791 net.add_agent("bob");
792 assert!(net.remove_agent("alice"));
793 assert!(!net.remove_agent("alice")); assert_eq!(net.agent_count(), 1);
795 }
796
797 #[test]
798 fn remove_agent_updates_topology() {
799 let mut net = GossipNetwork::with_defaults();
800 net.add_agent("alice");
801 net.add_agent("bob");
802 net.add_agent("carol");
803 assert_eq!(net.neighbors("alice").unwrap().len(), 2);
805 net.remove_agent("bob");
806 let neighbors = net.neighbors("alice").unwrap();
808 assert_eq!(neighbors.len(), 1);
809 assert_eq!(neighbors[0], "carol");
810 }
811
812 #[test]
815 fn fully_connected_topology() {
816 let mut net = GossipNetwork::with_defaults();
817 for name in &["a", "b", "c", "d"] {
818 net.add_agent(*name);
819 }
820 for name in &["a", "b", "c", "d"] {
821 assert_eq!(net.neighbors(name).unwrap().len(), 3);
822 }
823 }
824
825 #[test]
826 fn ring_topology() {
827 let config = GossipConfig {
828 topology: Topology::Ring,
829 ..GossipConfig::default()
830 };
831 let mut net = GossipNetwork::new(config, 42);
832 for name in &["a", "b", "c", "d", "e"] {
833 net.add_agent(*name);
834 }
835 for name in &["a", "b", "c", "d", "e"] {
837 let n = net.neighbors(name).unwrap().len();
838 assert!(n <= 4, "ring neighbor count {} > 4 for {}", n, name);
839 assert!(n >= 1, "ring neighbor count {} < 1 for {}", n, name);
840 }
841 }
842
843 #[test]
844 fn is_connected_empty_network() {
845 let net = GossipNetwork::with_defaults();
846 assert!(net.is_connected());
847 }
848
849 #[test]
850 fn is_connected_fully_connected() {
851 let mut net = GossipNetwork::with_defaults();
852 for name in &["a", "b", "c"] {
853 net.add_agent(*name);
854 }
855 assert!(net.is_connected());
856 }
857
858 #[test]
861 fn announce_dialect_creates_propagation() {
862 let mut net = GossipNetwork::with_defaults();
863 net.add_agent("alice");
864 net.add_agent("bob");
865 let result = net.announce_dialect(test_dialect("test"), "alice");
866 assert_eq!(result, Some(String::from("test")));
867 assert_eq!(net.active_propagations().len(), 1);
868
869 let prop = net.propagation_stats("test").unwrap();
870 assert_eq!(prop.infected.len(), 1);
871 assert!(prop.infected.contains("alice"));
872 assert_eq!(prop.susceptible.len(), 1);
873 assert!(prop.susceptible.contains("bob"));
874 assert_eq!(prop.round, 0);
875 }
876
877 #[test]
878 fn announce_dialect_unknown_agent() {
879 let mut net = GossipNetwork::with_defaults();
880 let result = net.announce_dialect(test_dialect("test"), "nonexistent");
881 assert!(result.is_none());
882 }
883
884 #[test]
885 fn announce_dialect_duplicate() {
886 let mut net = GossipNetwork::with_defaults();
887 net.add_agent("alice");
888 net.announce_dialect(test_dialect("test"), "alice");
889 let result = net.announce_dialect(test_dialect("test"), "alice");
890 assert!(result.is_none());
891 }
892
893 #[test]
894 fn step_propagates_dialect() {
895 let config = GossipConfig {
896 transmission_probability: 1.0, ..GossipConfig::default()
898 };
899 let mut net = GossipNetwork::new(config, 42);
900 for name in &["a", "b", "c"] {
901 net.add_agent(*name);
902 }
903 net.announce_dialect(test_dialect("test"), "a");
904
905 let results = net.step();
907 assert!(!results.is_empty());
908
909 assert!(net.active_propagations().is_empty()); assert_eq!(net.stats().successful_propagations, 1);
912 }
913
914 #[test]
915 fn step_respects_max_rounds() {
916 let config = GossipConfig {
917 transmission_probability: 0.0, max_rounds: 3,
919 ..GossipConfig::default()
920 };
921 let mut net = GossipNetwork::new(config, 42);
922 net.add_agent("a");
923 net.add_agent("b");
924 net.announce_dialect(test_dialect("test"), "a");
925
926 for _ in 0..4 {
927 net.step();
928 }
929 assert!(net.active_propagations().is_empty());
931 assert_eq!(net.stats().failed_propagations, 1);
932 }
933
934 #[test]
937 fn estimate_convergence_single_agent() {
938 let mut net = GossipNetwork::with_defaults();
939 net.add_agent("alice");
940 assert_eq!(net.estimate_convergence_time(), 0);
941 }
942
943 #[test]
944 fn estimate_convergence_log_n() {
945 let mut net = GossipNetwork::with_defaults();
946 for i in 0..100 {
947 net.add_agent(alloc::format!("agent-{}", i));
948 }
949 let estimate = net.estimate_convergence_time();
950 assert!(estimate > 0);
952 assert!(
953 estimate <= 10,
954 "estimate {} too high for 100 agents",
955 estimate
956 );
957 }
958
959 #[test]
960 fn estimate_convergence_empty_network() {
961 let net = GossipNetwork::with_defaults();
962 assert_eq!(net.estimate_convergence_time(), 0);
963 }
964
965 #[test]
968 fn receive_gossip_valid_dialect() {
969 let mut net = GossipNetwork::with_defaults();
970 net.add_agent("alice");
971 let d = test_dialect("ext");
972 assert!(net.receive_gossip("alice", &d).is_ok());
973 assert!(net.agent_has_dialect("alice", "ext"));
974 }
975
976 #[test]
977 fn receive_gossip_rejects_r3_violation() {
978 let mut net = GossipNetwork::with_defaults();
979 net.add_agent("alice");
980 let bad = Dialect {
981 types: Default::default(),
982 roles: Vec::new(),
983 state: None,
984 state_bounds: None,
985 causal_locality: Default::default(),
986 name: String::from("bad"),
987 extends: Vec::new(),
988 author: None,
989 performatives: vec![PerformativeDef {
990 role: None,
991 name: String::from("tell"), params: Vec::new(),
993 template: SExpr::Atom(Atom::Symbol(String::from("x"))),
994 }],
995 resources: ResourceBounds {
996 max_depth: 8,
997 max_expansion_size: 512,
998 },
999 examples: Vec::new(),
1000 signature: None,
1001 hash: None,
1002 protocol: None,
1003 causal_protocol: None,
1004 shapes: Vec::new(),
1005 };
1006 let result = net.receive_gossip("alice", &bad);
1007 assert!(result.is_err());
1008 assert!(!net.agent_has_dialect("alice", "bad"));
1009 }
1010
1011 #[test]
1012 fn receive_gossip_rejects_r2_violation() {
1013 let mut net = GossipNetwork::with_defaults();
1014 net.add_agent("alice");
1015 let bad = Dialect {
1016 types: Default::default(),
1017 roles: Vec::new(),
1018 state: None,
1019 state_bounds: None,
1020 causal_locality: Default::default(),
1021 name: String::from("bad-bounds"),
1022 extends: Vec::new(),
1023 author: None,
1024 performatives: Vec::new(),
1025 resources: ResourceBounds {
1026 max_depth: 100, max_expansion_size: 512,
1028 },
1029 examples: Vec::new(),
1030 signature: None,
1031 hash: None,
1032 protocol: None,
1033 causal_protocol: None,
1034 shapes: Vec::new(),
1035 };
1036 let result = net.receive_gossip("alice", &bad);
1037 assert!(result.is_err());
1038 }
1039
1040 #[test]
1043 fn select_peers_returns_subset() {
1044 let mut net = GossipNetwork::with_defaults();
1045 for name in &["a", "b", "c", "d", "e"] {
1046 net.add_agent(*name);
1047 }
1048 let peers = net.select_peers("a", 2);
1049 assert_eq!(peers.len(), 2);
1050 let neighbors = net.neighbors("a").unwrap();
1052 for peer in &peers {
1053 assert!(neighbors.contains(&peer.as_str()));
1054 }
1055 }
1056
1057 #[test]
1058 fn select_peers_all_when_k_large() {
1059 let mut net = GossipNetwork::with_defaults();
1060 net.add_agent("a");
1061 net.add_agent("b");
1062 let peers = net.select_peers("a", 10);
1063 assert_eq!(peers.len(), 1); }
1065
1066 #[test]
1067 fn select_peers_unknown_agent() {
1068 let mut net = GossipNetwork::with_defaults();
1069 let peers = net.select_peers("nonexistent", 3);
1070 assert!(peers.is_empty());
1071 }
1072
1073 #[test]
1076 fn simulate_propagation_converges() {
1077 let config = GossipConfig {
1078 transmission_probability: 1.0,
1079 ..GossipConfig::default()
1080 };
1081 let mut net = GossipNetwork::new(config, 42);
1082 for i in 0..10 {
1083 net.add_agent(alloc::format!("agent-{}", i));
1084 }
1085 let result = net
1086 .simulate_propagation(test_dialect("test"), "agent-0")
1087 .unwrap();
1088 assert!(result.successful);
1089 assert!((result.final_coverage - 1.0).abs() < f64::EPSILON);
1090 assert_eq!(result.rounds, 1);
1092 }
1093
1094 #[test]
1095 fn simulate_propagation_with_realistic_probability() {
1096 let mut net = GossipNetwork::new(GossipConfig::default(), 42);
1097 for i in 0..20 {
1098 net.add_agent(alloc::format!("agent-{}", i));
1099 }
1100 let result = net
1101 .simulate_propagation(test_dialect("epidemic"), "agent-0")
1102 .unwrap();
1103 assert!(result.successful);
1104 assert!(
1106 result.rounds < 20,
1107 "took {} rounds for 20 agents",
1108 result.rounds
1109 );
1110 }
1111
1112 #[test]
1113 fn simulate_propagation_unknown_agent() {
1114 let mut net = GossipNetwork::with_defaults();
1115 let result = net.simulate_propagation(test_dialect("test"), "nonexistent");
1116 assert!(result.is_none());
1117 }
1118
1119 #[test]
1122 fn propagation_coverage() {
1123 let mut state = PropagationState {
1124 dialect: test_dialect("test"),
1125 infected: BTreeSet::new(),
1126 susceptible: BTreeSet::new(),
1127 round: 0,
1128 transmission_prob: 0.8,
1129 };
1130 assert!((state.coverage() - 1.0).abs() < f64::EPSILON);
1132 assert!(state.is_complete());
1133
1134 state.infected.insert(String::from("a"));
1135 state.susceptible.insert(String::from("b"));
1136 state.susceptible.insert(String::from("c"));
1137 assert!((state.coverage() - 1.0 / 3.0).abs() < 0.01);
1138 assert!(!state.is_complete());
1139 }
1140
1141 #[test]
1144 fn deterministic_with_same_seed() {
1145 let run = |seed: u64| -> SimulationResult {
1146 let mut net = GossipNetwork::new(GossipConfig::default(), seed);
1147 for i in 0..15 {
1148 net.add_agent(alloc::format!("agent-{}", i));
1149 }
1150 net.simulate_propagation(test_dialect("det-test"), "agent-0")
1151 .unwrap()
1152 };
1153
1154 let r1 = run(9999);
1155 let r2 = run(9999);
1156 assert_eq!(r1.rounds, r2.rounds);
1157 assert_eq!(r1.successful, r2.successful);
1158 }
1159
1160 #[test]
1163 fn stats_track_success_and_failure() {
1164 let config = GossipConfig {
1166 transmission_probability: 1.0,
1167 max_rounds: 100,
1168 ..GossipConfig::default()
1169 };
1170 let mut net = GossipNetwork::new(config, 42);
1171 net.add_agent("a");
1172 net.add_agent("b");
1173 net.simulate_propagation(test_dialect("good"), "a");
1174 assert_eq!(net.stats().successful_propagations, 1);
1175
1176 let config2 = GossipConfig {
1178 transmission_probability: 0.0,
1179 max_rounds: 2,
1180 ..GossipConfig::default()
1181 };
1182 let mut net2 = GossipNetwork::new(config2, 42);
1183 net2.add_agent("a");
1184 net2.add_agent("b");
1185 net2.simulate_propagation(test_dialect("fail"), "a");
1186 assert_eq!(net2.stats().failed_propagations, 1);
1187 }
1188
1189 #[test]
1192 fn lcg_produces_values_in_range() {
1193 let mut rng = Lcg::new(12345);
1194 for _ in 0..1000 {
1195 let v = rng.next_f64();
1196 assert!((0.0..1.0).contains(&v), "LCG value {} out of range", v);
1197 }
1198 }
1199
1200 #[test]
1201 fn lcg_deterministic() {
1202 let mut rng1 = Lcg::new(42);
1203 let mut rng2 = Lcg::new(42);
1204 for _ in 0..100 {
1205 assert_eq!(rng1.next_f64().to_bits(), rng2.next_f64().to_bits());
1206 }
1207 }
1208
1209 #[test]
1212 fn remove_agent_during_propagation() {
1213 let mut net = GossipNetwork::with_defaults();
1214 net.add_agent("a");
1215 net.add_agent("b");
1216 net.add_agent("c");
1217 net.announce_dialect(test_dialect("test"), "a");
1218
1219 net.remove_agent("b");
1221 let prop = net.propagation_stats("test").unwrap();
1222 assert!(!prop.susceptible.contains("b"));
1223 assert_eq!(prop.susceptible.len(), 1);
1224 }
1225}