mod rng;
use alloc::rc::Rc;
use alloc::vec::Vec;
use crate::assignment::Assignment;
use crate::bundle::Bundle;
use crate::cbba;
use crate::id::{AgentId, TaskId};
use crate::valuation::Valuation;
use rng::SplitMix64;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Network {
pub seed: u64,
pub max_delay: u64,
pub loss_per_mille: u16,
pub topology: Topology,
pub partitions: Vec<Partition>,
pub collisions: bool,
pub clusters: Option<Clusters>,
}
pub const BACKOFF_SLOTS: u64 = 16;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Clusters {
pub groups: Vec<usize>,
pub period: u64,
}
fn same_group(groups: &[usize], a: AgentId, b: AgentId) -> bool {
groups
.get(a.index())
.is_some_and(|group| groups.get(b.index()) == Some(group))
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Topology {
#[default]
Complete,
Links(Vec<(AgentId, AgentId)>),
}
impl Topology {
#[must_use]
pub fn connects(&self, a: AgentId, b: AgentId) -> bool {
match self {
Self::Complete => true,
Self::Links(links) => links.iter().any(|&link| link == (a, b) || link == (b, a)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Partition {
pub from: u64,
pub until: u64,
pub groups: Vec<usize>,
}
impl Partition {
#[must_use]
pub fn separates(&self, tick: u64, a: AgentId, b: AgentId) -> bool {
let active = (self.from..self.until).contains(&tick);
active && !same_group(&self.groups, a, b)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
pub sent: u64,
pub delivered: u64,
pub lost: u64,
pub blocked: u64,
pub useful: u64,
pub bytes: u64,
pub collided: u64,
}
pub trait Participant: Sized {
type Message;
fn id(&self) -> AgentId;
fn bundle(&self) -> &Bundle<TaskId>;
fn act(&mut self, now: u64, outbox: &mut Vec<Self::Message>);
fn receive(
&mut self,
now: u64,
message: &Self::Message,
outbox: &mut Vec<Self::Message>,
) -> bool;
fn message_bytes(message: &Self::Message) -> u64;
fn is_settled(team: &[Self], in_flight: &[&Self::Message]) -> bool;
}
impl<V: Valuation<TaskId>> Participant for cbba::Agent<V> {
type Message = cbba::Message;
fn id(&self) -> AgentId {
self.id()
}
fn bundle(&self) -> &Bundle<TaskId> {
self.bundle()
}
fn act(&mut self, _now: u64, outbox: &mut Vec<cbba::Message>) {
if self.has_left() {
return;
}
self.build_bundle();
if self.broadcast_due() {
outbox.push(self.message());
}
}
fn receive(
&mut self,
_now: u64,
message: &cbba::Message,
_outbox: &mut Vec<cbba::Message>,
) -> bool {
cbba::Agent::receive(self, message)
}
fn message_bytes(message: &cbba::Message) -> u64 {
message.bytes()
}
fn is_settled(team: &[Self], in_flight: &[&cbba::Message]) -> bool {
let mut active = team.iter().filter(|agent| !agent.has_left());
let Some(first) = active.next() else {
return true;
};
let active = || team.iter().filter(|agent| !agent.has_left());
active().all(cbba::Agent::is_consistent)
&& !active().any(cbba::Agent::can_bid)
&& active().all(|agent| agent.claims() == first.claims())
&& in_flight
.iter()
.filter(|message| !first.has_departed(message.sender()))
.all(|message| message.claims() == first.claims())
}
}
type Copies<M> = Vec<InFlight<M>>;
#[derive(Clone, Debug)]
struct InFlight<M> {
arrives: u64,
order: u64,
to: AgentId,
message: Rc<M>,
}
#[derive(Clone, Debug)]
pub struct Simulation<A: Participant> {
agents: Vec<A>,
network: Network,
rng: SplitMix64,
tick: u64,
in_flight: Copies<A::Message>,
due: Copies<A::Message>,
outboxes: Vec<Vec<A::Message>>,
next_order: u64,
stats: Stats,
}
impl<A: Participant> Simulation<A> {
#[must_use]
pub fn new(agents: Vec<A>, network: Network) -> Self {
let in_order = agents
.iter()
.enumerate()
.all(|(index, agent)| agent.id() == AgentId(index));
assert!(in_order, "agents must be identified 0, 1, 2, ... in order");
assert!(
network
.clusters
.as_ref()
.is_none_or(|clusters| clusters.period > 0),
"clusters must exchange messages every positive number of ticks"
);
let rng = SplitMix64::new(network.seed);
Self {
agents,
network,
rng,
tick: 0,
in_flight: Vec::new(),
due: Vec::new(),
outboxes: Vec::new(),
next_order: 0,
stats: Stats::default(),
}
}
pub fn step(&mut self) {
let mut outboxes = core::mem::take(&mut self.outboxes);
outboxes.resize_with(self.agents.len(), Vec::new);
self.deliver_due(&mut outboxes);
for (agent, outbox) in self.agents.iter_mut().zip(&mut outboxes) {
agent.act(self.tick, outbox);
}
self.broadcast_all(&mut outboxes);
self.outboxes = outboxes;
self.tick += 1;
}
pub fn run_until_settled(&mut self, max_ticks: u64) -> Option<u64> {
let limit = self.tick.saturating_add(max_ticks);
while self.tick < limit {
self.step();
if self.is_settled() {
return Some(self.tick);
}
}
None
}
#[must_use]
pub fn is_settled(&self) -> bool {
let in_flight: Vec<&A::Message> =
self.in_flight.iter().map(|copy| &*copy.message).collect();
A::is_settled(&self.agents, &in_flight)
}
fn deliver_due(&mut self, outboxes: &mut [Vec<A::Message>]) {
let tick = self.tick;
let mut due = core::mem::take(&mut self.due);
let mut index = 0;
while index < self.in_flight.len() {
if self.in_flight[index].arrives <= tick {
due.push(self.in_flight.swap_remove(index));
} else {
index += 1;
}
}
due.sort_unstable_by_key(|copy| (copy.arrives, copy.order));
for copy in due.drain(..) {
let to = copy.to.index();
let changed = self.agents[to].receive(tick, ©.message, &mut outboxes[to]);
self.stats.delivered += 1;
self.stats.useful += u64::from(changed);
}
self.due = due;
}
fn broadcast_all(&mut self, outboxes: &mut [Vec<A::Message>]) {
let agents = self.agents.len();
let slots = self.backoff_slots(outboxes);
for (sender, outbox) in outboxes.iter_mut().enumerate() {
for (frame, message) in outbox.drain(..).enumerate() {
let message = Rc::new(message);
let slot = slots
.get(sender)
.and_then(|frames| frames.get(frame))
.copied();
let mut transmitted = false;
for receiver in (0..agents).filter(|&receiver| receiver != sender) {
let (from, to) = (AgentId(sender), AgentId(receiver));
let collides = slot.is_some_and(|slot| self.collides(&slots, from, slot, to));
transmitted |= self.send(from, to, &message, collides);
}
if transmitted {
self.stats.bytes += A::message_bytes(&message);
}
}
}
}
fn backoff_slots(&mut self, outboxes: &[Vec<A::Message>]) -> Vec<Vec<u64>> {
if !self.network.collisions {
return Vec::new();
}
outboxes
.iter()
.map(|outbox| {
outbox
.iter()
.map(|_| self.rng.below(BACKOFF_SLOTS))
.collect()
})
.collect()
}
fn collides(&self, slots: &[Vec<u64>], from: AgentId, slot: u64, to: AgentId) -> bool {
slots.iter().enumerate().any(|(other, frames)| {
let other = AgentId(other);
frames.contains(&slot)
&& other != from
&& other != to
&& !self.is_cut_off(other, to)
&& self.is_cut_off(from, other)
})
}
fn send(
&mut self,
from: AgentId,
to: AgentId,
message: &Rc<A::Message>,
collides: bool,
) -> bool {
if self.is_cut_off(from, to) {
self.stats.blocked += 1;
return false;
}
self.stats.sent += 1;
if collides {
self.stats.collided += 1;
return true;
}
if self.rng.below(1000) < u64::from(self.network.loss_per_mille) {
self.stats.lost += 1;
return true;
}
let delay = 1 + self.rng.below(self.network.max_delay.saturating_add(1));
self.in_flight.push(InFlight {
arrives: self.arrival(from, to, self.tick + delay),
order: self.next_order,
to,
message: Rc::clone(message),
});
self.next_order += 1;
true
}
fn arrival(&self, from: AgentId, to: AgentId, tick: u64) -> u64 {
match &self.network.clusters {
Some(clusters) if !same_group(&clusters.groups, from, to) => {
tick.div_ceil(clusters.period) * clusters.period
}
_ => tick,
}
}
fn is_cut_off(&self, a: AgentId, b: AgentId) -> bool {
!self.network.topology.connects(a, b)
|| self
.network
.partitions
.iter()
.any(|partition| partition.separates(self.tick, a, b))
}
#[must_use]
pub fn agents(&self) -> &[A] {
&self.agents
}
pub fn agents_mut(&mut self) -> &mut [A] {
&mut self.agents
}
#[must_use]
pub const fn tick(&self) -> u64 {
self.tick
}
#[must_use]
pub const fn stats(&self) -> Stats {
self.stats
}
#[must_use]
pub fn assignment(&self) -> Assignment {
Assignment::from_bundles(
self.agents
.iter()
.map(|agent| agent.bundle().clone())
.collect(),
)
}
}
#[cfg(test)]
mod tests;