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>,
}
#[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
&& self
.groups
.get(a.index())
.is_none_or(|group| self.groups.get(b.index()) != Some(group))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
pub sent: u64,
pub delivered: u64,
pub lost: u64,
pub blocked: 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>);
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>) {
self.build_bundle();
outbox.push(self.message());
}
fn receive(&mut self, _now: u64, message: &cbba::Message, _outbox: &mut Vec<cbba::Message>) {
cbba::Agent::receive(self, message);
}
fn is_settled(team: &[Self], in_flight: &[&cbba::Message]) -> bool {
let Some(first) = team.first() else {
return true;
};
team.iter().all(cbba::Agent::is_consistent)
&& !team.iter().any(cbba::Agent::can_bid)
&& team.iter().all(|agent| agent.claims() == first.claims())
&& in_flight
.iter()
.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>,
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");
let rng = SplitMix64::new(network.seed);
Self {
agents,
network,
rng,
tick: 0,
in_flight: Vec::new(),
next_order: 0,
stats: Stats::default(),
}
}
pub fn step(&mut self) {
let mut outboxes: Vec<Vec<A::Message>> = self.agents.iter().map(|_| Vec::new()).collect();
self.deliver_due(&mut outboxes);
for (agent, outbox) in self.agents.iter_mut().zip(&mut outboxes) {
agent.act(self.tick, outbox);
}
self.broadcast_all(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, waiting): (Copies<A::Message>, Copies<A::Message>) = self
.in_flight
.drain(..)
.partition(|copy| copy.arrives <= tick);
self.in_flight = waiting;
due.sort_unstable_by_key(|copy| (copy.arrives, copy.order));
for copy in due {
let to = copy.to.index();
self.agents[to].receive(tick, ©.message, &mut outboxes[to]);
self.stats.delivered += 1;
}
}
fn broadcast_all(&mut self, outboxes: Vec<Vec<A::Message>>) {
let agents = self.agents.len();
for (sender, outbox) in outboxes.into_iter().enumerate() {
for message in outbox {
let message = Rc::new(message);
for receiver in (0..agents).filter(|&receiver| receiver != sender) {
self.send(AgentId(sender), AgentId(receiver), &message);
}
}
}
}
fn send(&mut self, from: AgentId, to: AgentId, message: &Rc<A::Message>) {
if self.is_cut_off(from, to) {
self.stats.blocked += 1;
return;
}
self.stats.sent += 1;
if self.rng.below(1000) < u64::from(self.network.loss_per_mille) {
self.stats.lost += 1;
return;
}
let delay = 1 + self.rng.below(self.network.max_delay.saturating_add(1));
self.in_flight.push(InFlight {
arrives: self.tick + delay,
order: self.next_order,
to,
message: Rc::clone(message),
});
self.next_order += 1;
}
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
}
#[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;