Skip to main content

cbcl_core/
gossip.rs

1//! Epidemic gossip protocol for dialect propagation (REQ-120–122).
2//!
3//! Implements round-based epidemic propagation with configurable transmission
4//! probability, infected/susceptible set tracking, and O(log n) expected
5//! convergence. Faithfully reproduces `src/cbcl/gossip.scm`.
6//!
7//! # Purity
8//!
9//! This module uses a deterministic linear congruential generator (LCG) seeded
10//! at construction time, matching the Guile reference. Given the same seed and
11//! inputs, the protocol produces identical results — no external RNG or I/O.
12
13#![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
23// ---------------------------------------------------------------------------
24// no_std-compatible ln approximation
25// ---------------------------------------------------------------------------
26
27/// Natural logarithm approximation for no_std (used in convergence estimation).
28///
29/// Uses the identity: ln(x) = 2 * atanh((x-1)/(x+1)) with a truncated series.
30/// Accurate enough for O(log n) convergence estimation.
31fn ln_approx(x: f64) -> f64 {
32    if x <= 0.0 {
33        return f64::NEG_INFINITY;
34    }
35    // Reduce to range [1, 2) by extracting the exponent
36    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    // ln(x) = exp * ln(2) + ln(mantissa)
41    // ln(mantissa) via atanh series: 2 * sum_{k=0}^{N} t^(2k+1)/(2k+1)
42    let t = (mantissa - 1.0) / (mantissa + 1.0);
43    let t2 = t * t;
44    // 7 terms for good accuracy
45    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// ---------------------------------------------------------------------------
56// Configuration
57// ---------------------------------------------------------------------------
58
59/// Network topology for gossip propagation.
60#[derive(Debug, Clone, PartialEq)]
61#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
62pub enum Topology {
63    /// Every agent is connected to every other agent.
64    FullyConnected,
65    /// Each agent is connected to its ring neighbors.
66    Ring,
67    /// Erdős–Rényi random graph with edge probability `p`.
68    Random(f64),
69}
70
71/// Configuration for the gossip network.
72#[derive(Debug, Clone, PartialEq)]
73#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
74pub struct GossipConfig {
75    /// Probability of successful transmission per contact (0.0–1.0).
76    pub transmission_probability: f64,
77    /// Maximum number of rounds before a propagation is considered failed.
78    pub max_rounds: u32,
79    /// Network topology.
80    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// ---------------------------------------------------------------------------
94// Deterministic RNG (matches Guile simple-random)
95// ---------------------------------------------------------------------------
96
97/// Simple linear congruential generator for deterministic gossip randomness.
98///
99/// Uses the same constants as the Guile reference (`gossip.scm:46–50`):
100/// `seed = (seed * 1103515245 + 12345) mod 2^31`
101#[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    /// Returns a value in [0.0, 1.0).
113    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// ---------------------------------------------------------------------------
121// Propagation state
122// ---------------------------------------------------------------------------
123
124/// State of an epidemic propagation for a single dialect.
125#[derive(Debug, Clone)]
126#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
127pub struct PropagationState {
128    /// The dialect being propagated.
129    pub dialect: Dialect,
130    /// Agent ids that have the dialect installed.
131    pub infected: BTreeSet<String>,
132    /// Agent ids that do not yet have the dialect.
133    pub susceptible: BTreeSet<String>,
134    /// Current round number.
135    pub round: u32,
136    /// Transmission probability for this propagation.
137    pub transmission_prob: f64,
138}
139
140impl PropagationState {
141    /// Coverage ratio: infected / (infected + susceptible).
142    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    /// Whether propagation is complete (no susceptible agents remain).
152    pub fn is_complete(&self) -> bool {
153        self.susceptible.is_empty()
154    }
155}
156
157// ---------------------------------------------------------------------------
158// Statistics
159// ---------------------------------------------------------------------------
160
161/// Aggregate statistics for a gossip network.
162#[derive(Debug, Clone, Default, PartialEq, Eq)]
163#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164pub struct GossipStats {
165    /// Total rounds executed across all propagations.
166    pub total_rounds: u64,
167    /// Number of propagations that reached full coverage.
168    pub successful_propagations: u64,
169    /// Number of propagations that timed out (exceeded max_rounds).
170    pub failed_propagations: u64,
171}
172
173// ---------------------------------------------------------------------------
174// Simulation result
175// ---------------------------------------------------------------------------
176
177/// Result of a complete propagation simulation.
178#[derive(Debug, Clone)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180pub struct SimulationResult {
181    /// Name of the dialect propagated.
182    pub dialect_name: String,
183    /// Number of rounds to convergence (or timeout).
184    pub rounds: u32,
185    /// Final coverage ratio.
186    pub final_coverage: f64,
187    /// Whether the propagation completed successfully.
188    pub successful: bool,
189}
190
191// ---------------------------------------------------------------------------
192// GossipNetwork
193// ---------------------------------------------------------------------------
194
195/// Epidemic gossip network for dialect propagation (REQ-120).
196///
197/// Manages a set of agents connected by a configurable topology.
198/// Dialects are propagated epidemically: each round, infected agents
199/// attempt to transmit to their susceptible neighbors with a given
200/// probability. Expected convergence is O(log n) rounds for a
201/// fully-connected network with constant transmission probability.
202#[derive(Debug, Clone)]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
204pub struct GossipNetwork {
205    /// Agent ids and their installed dialect names.
206    agents: BTreeMap<String, BTreeSet<String>>,
207    /// Adjacency list: agent_id → set of neighbor ids.
208    topology: BTreeMap<String, BTreeSet<String>>,
209    /// Active propagations keyed by dialect name.
210    active_propagations: BTreeMap<String, PropagationState>,
211    /// Aggregate statistics.
212    stats: GossipStats,
213    /// Network configuration.
214    config: GossipConfig,
215    /// Deterministic RNG.
216    rng: Lcg,
217}
218
219impl GossipNetwork {
220    /// Create a new gossip network with the given configuration and RNG seed.
221    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    /// Create a new gossip network with default configuration and the
233    /// reference seed (1234567, matching the Guile implementation).
234    pub fn with_defaults() -> Self {
235        Self::new(GossipConfig::default(), 1_234_567)
236    }
237
238    // -- Agent management (REQ-121) --
239
240    /// Add an agent to the network.
241    ///
242    /// The topology is updated automatically based on the configured topology
243    /// type. Returns `true` if the agent was newly added, `false` if it was
244    /// already present.
245    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    /// Remove an agent from the network.
257    ///
258    /// Removes the agent from all neighbor lists and from any active
259    /// propagation sets. Returns `true` if the agent was present.
260    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        // Remove from all neighbor lists
266        for neighbors in self.topology.values_mut() {
267            neighbors.remove(agent_id);
268        }
269        // Remove from active propagations
270        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    /// Returns the set of agent ids in the network.
278    pub fn agent_ids(&self) -> Vec<&str> {
279        self.agents.keys().map(|s| s.as_str()).collect()
280    }
281
282    /// Returns the number of agents in the network.
283    pub fn agent_count(&self) -> usize {
284        self.agents.len()
285    }
286
287    /// Returns neighbors of the given agent.
288    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    // -- Topology --
295
296    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                        // Connect new agent to existing
303                        self.topology
304                            .get_mut(new_agent_id)
305                            .unwrap()
306                            .insert(id.clone());
307                        // Connect existing to new agent
308                        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                    // Connect to up to 2 existing agents
319                    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    // -- Propagation (REQ-120, REQ-121) --
356
357    /// Start epidemic propagation of a dialect from an initial agent (REQ-121).
358    ///
359    /// The dialect is considered "installed" on the initial agent. All other
360    /// agents in the network are placed in the susceptible set.
361    ///
362    /// Returns `None` if the initial agent is not in the network, or if a
363    /// propagation for this dialect is already active. Otherwise returns the
364    /// dialect name as a propagation identifier.
365    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        // Mark initial agent as having the dialect
376        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    /// Execute one round of epidemic propagation for all active dialects.
417    ///
418    /// Each infected agent attempts to transmit to each of its susceptible
419    /// neighbors with the configured transmission probability. Newly infected
420    /// agents are added to the infected set. Propagations that complete (empty
421    /// susceptible set) or exceed `max_rounds` are cleaned up.
422    ///
423    /// Returns a list of (dialect_name, newly_infected_agent_ids) for this round.
424    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        // Collect the data we need to decide transmissions
456        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        // For each infected agent, try to infect susceptible neighbors
465        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        // Update propagation state
484        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                // Mark agent as having the dialect
489                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    // -- Gossip reception (REQ-121, REQ-122) --
526
527    /// Receive a gossip message containing a dialect for a specific agent.
528    ///
529    /// The dialect is validated through the R1+R2+R3 pipeline (REQ-122).
530    /// Returns a list of validation violations if the dialect fails checks,
531    /// or `Ok(())` if the dialect is accepted.
532    ///
533    /// Note: actual dialect installation on real Agent structs is the caller's
534    /// responsibility. This method tracks the gossip-level state (infected/
535    /// susceptible sets) for the propagation simulation.
536    pub fn receive_gossip(&mut self, agent_id: &str, dialect: &Dialect) -> Result<(), Vec<String>> {
537        // Validate through R1+R2+R3 pipeline (REQ-122)
538        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        // Mark agent as having the dialect
562        if let Some(agent_dialects) = self.agents.get_mut(agent_id) {
563            agent_dialects.insert(dialect.name.clone());
564        }
565
566        // Update propagation state if this dialect is being actively propagated
567        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    // -- Peer selection (REQ-121) --
576
577    /// Select up to `k` peers for gossip fan-out (REQ-121).
578    ///
579    /// Uses the deterministic LCG to select peers from the agent's neighbors.
580    /// Returns the selected peer ids.
581    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        // Fisher-Yates shuffle on a copy, then take first k
592        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); // safety bound
598            shuffled.swap(i, j);
599        }
600        shuffled.truncate(k);
601        shuffled
602    }
603
604    // -- Analysis --
605
606    /// Estimate expected convergence time in rounds (REQ-120).
607    ///
608    /// For a network of n agents with transmission probability p,
609    /// the expected convergence is O(log n) rounds:
610    /// `ceil(ln(n) / ln(1 + p))`
611    ///
612    /// This matches `estimate-convergence-time` in `gossip.scm:275–284`.
613    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    /// Check if the network is connected (all agents reachable from any agent).
624    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(&current) {
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    /// Simulate complete epidemic propagation until convergence or timeout.
654    ///
655    /// Matches `simulate-propagation` in `gossip.scm:302–318`.
656    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        // Determine if it was successful by checking stats
670        // (the cleanup in step() already updated stats)
671        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    // -- Accessors --
685
686    /// Returns a reference to the network configuration.
687    pub fn config(&self) -> &GossipConfig {
688        &self.config
689    }
690
691    /// Returns a reference to the aggregate statistics.
692    pub fn stats(&self) -> &GossipStats {
693        &self.stats
694    }
695
696    /// Returns a reference to the active propagations.
697    pub fn active_propagations(&self) -> &BTreeMap<String, PropagationState> {
698        &self.active_propagations
699    }
700
701    /// Get propagation statistics for a specific dialect.
702    pub fn propagation_stats(&self, dialect_name: &str) -> Option<&PropagationState> {
703        self.active_propagations.get(dialect_name)
704    }
705
706    /// Check if an agent has a specific dialect installed.
707    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// ---------------------------------------------------------------------------
716// Tests
717// ---------------------------------------------------------------------------
718
719#[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    // -- Construction --
759
760    #[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    // -- Agent management --
777
778    #[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")); // duplicate
784        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")); // already removed
794        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        // Fully connected: each has 2 neighbors
804        assert_eq!(net.neighbors("alice").unwrap().len(), 2);
805        net.remove_agent("bob");
806        // Alice should now only have carol as neighbor
807        let neighbors = net.neighbors("alice").unwrap();
808        assert_eq!(neighbors.len(), 1);
809        assert_eq!(neighbors[0], "carol");
810    }
811
812    // -- Topology --
813
814    #[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        // Each agent should have at most 2 neighbors in a ring
836        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    // -- Propagation --
859
860    #[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, // guaranteed transmission
897            ..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        // After one step with p=1.0, all neighbors of "a" should be infected
906        let results = net.step();
907        assert!(!results.is_empty());
908
909        // In a fully connected network with p=1.0, one round should infect everyone
910        assert!(net.active_propagations().is_empty()); // cleaned up as complete
911        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, // never transmits
918            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        // Should have timed out
930        assert!(net.active_propagations().is_empty());
931        assert_eq!(net.stats().failed_propagations, 1);
932    }
933
934    // -- Convergence estimation --
935
936    #[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        // With p=0.8, ln(100)/ln(1.8) ≈ 7.8, so estimate should be 8
951        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    // -- Receive gossip (REQ-122) --
966
967    #[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"), // R3 violation
992                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, // invalid
1027                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    // -- Select peers (REQ-121) --
1041
1042    #[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        // All selected peers should be neighbors of "a"
1051        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); // only neighbor is "b"
1064    }
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    // -- Simulation --
1074
1075    #[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        // With p=1.0 fully connected, should converge in 1 round
1091        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        // O(log n) convergence: should complete well under max_rounds
1105        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    // -- Coverage --
1120
1121    #[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        // Empty network: coverage = 1.0
1131        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    // -- Determinism --
1142
1143    #[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    // -- Statistics --
1161
1162    #[test]
1163    fn stats_track_success_and_failure() {
1164        // Successful propagation
1165        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        // Failed propagation (p=0, max_rounds=2)
1177        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    // -- LCG --
1190
1191    #[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    // -- Remove agent from active propagation --
1210
1211    #[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        // Remove a susceptible agent
1220        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}