Skip to main content

task_allocation/
sim.rs

1//! A deterministic simulated network for running teams of agents: seeded delays, losses,
2//! topologies and partitions.
3//!
4//! A [`Simulation`] runs any [`Participant`], such as a [`cbba::Agent`]. Each
5//! [`Simulation::step`] is one tick:
6//!
7//! ```mermaid
8//! flowchart LR
9//!     deliver[deliver due messages] --> round[every agent's round]
10//!     round --> broadcast[broadcast every outbox]
11//!     broadcast --> deliver
12//! ```
13//!
14//! Agents may also answer a delivered message right away; those answers go out with the
15//! tick's broadcasts. A broadcast reaches every agent the sender has a link to in the
16//! [`Topology`] and is not cut off from by an active [`Partition`]; others hear of it only
17//! when it is relayed. Each copy is lost with probability [`Network::loss_per_mille`] /
18//! 1000, and otherwise arrives after 1 to `1 + max_delay` ticks, so messages overtake each
19//! other. Agents process the messages that arrive in a tick in arrival order. Everything
20//! random comes from [`Network::seed`]: the same seed gives the same run.
21//!
22//! When a team is *settled* is up to the protocol ([`Participant::is_settled`]). For CBBA,
23//! every agent believes in the same winners, every agent's bundle holds exactly the tasks it
24//! wins, no bundle phase would change anything, and every message still in flight carries
25//! those same winners. Nothing can change after that.
26
27mod rng;
28
29use alloc::rc::Rc;
30use alloc::vec::Vec;
31
32use crate::assignment::Assignment;
33use crate::bundle::Bundle;
34use crate::cbba;
35use crate::id::{AgentId, TaskId};
36use crate::valuation::Valuation;
37use rng::SplitMix64;
38
39/// How the simulated network behaves.
40#[derive(Clone, Debug, Default, PartialEq, Eq)]
41pub struct Network {
42    /// Seeds every random choice: delays and losses.
43    pub seed: u64,
44
45    /// The most extra ticks a message may take, on top of the one tick every message takes.
46    pub max_delay: u64,
47
48    /// The chance, per mille, that one copy of a broadcast is lost. 0 is lossless; 1000 or
49    /// more loses everything.
50    pub loss_per_mille: u16,
51
52    /// Which agents can reach each other at all.
53    pub topology: Topology,
54
55    /// Intervals in which groups of agents cannot reach each other.
56    pub partitions: Vec<Partition>,
57}
58
59/// Which pairs of agents can exchange messages directly. Agents without a direct link only
60/// hear of each other through relays.
61#[derive(Clone, Debug, Default, PartialEq, Eq)]
62pub enum Topology {
63    /// Every agent reaches every other agent.
64    #[default]
65    Complete,
66
67    /// Only the listed pairs reach each other, in both directions.
68    Links(Vec<(AgentId, AgentId)>),
69}
70
71impl Topology {
72    /// Whether `a` and `b` can exchange messages directly.
73    #[must_use]
74    pub fn connects(&self, a: AgentId, b: AgentId) -> bool {
75        match self {
76            Self::Complete => true,
77            Self::Links(links) => links.iter().any(|&link| link == (a, b) || link == (b, a)),
78        }
79    }
80}
81
82/// A time interval in which agents in different groups cannot reach each other.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct Partition {
85    /// The first tick of the partition.
86    pub from: u64,
87
88    /// The tick at which the partition heals; it is active for ticks `from..until`.
89    pub until: u64,
90
91    /// The group of each agent, indexed by agent. Agents missing from the list form a group
92    /// of their own each.
93    pub groups: Vec<usize>,
94}
95
96impl Partition {
97    /// Whether the partition separates agents `a` and `b` at `tick`.
98    #[must_use]
99    pub fn separates(&self, tick: u64, a: AgentId, b: AgentId) -> bool {
100        let active = (self.from..self.until).contains(&tick);
101
102        active
103            && self
104                .groups
105                .get(a.index())
106                .is_none_or(|group| self.groups.get(b.index()) != Some(group))
107    }
108}
109
110/// Message counts over a run.
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
112pub struct Stats {
113    /// Copies of broadcasts put on the network, one per reachable receiver.
114    pub sent: u64,
115
116    /// Copies that arrived.
117    pub delivered: u64,
118
119    /// Copies the network lost.
120    pub lost: u64,
121
122    /// Copies that could not be sent because the topology has no link to the receiver, or a
123    /// partition cut it off.
124    pub blocked: u64,
125}
126
127/// An agent that a [`Simulation`] can run: it works in rounds, broadcasts messages, and
128/// handles the messages that reach it.
129///
130/// [`cbba::Agent`] implements it; so can other consensus protocols.
131pub trait Participant: Sized {
132    /// What the agent broadcasts.
133    type Message;
134
135    /// The agent's identifier.
136    fn id(&self) -> AgentId;
137
138    /// The tasks the agent holds now.
139    fn bundle(&self) -> &Bundle<TaskId>;
140
141    /// One round of the agent's own work at tick `now`, such as its bundle phase; pushes
142    /// what it broadcasts onto `outbox`.
143    fn act(&mut self, now: u64, outbox: &mut Vec<Self::Message>);
144
145    /// Handles `message`, arriving at tick `now`; pushes what the agent broadcasts in
146    /// response onto `outbox`.
147    fn receive(&mut self, now: u64, message: &Self::Message, outbox: &mut Vec<Self::Message>);
148
149    /// Whether `team` has settled, with `in_flight` still on its way: the agents agree on a
150    /// conflict-free assignment that nothing in flight and no further round can change.
151    fn is_settled(team: &[Self], in_flight: &[&Self::Message]) -> bool;
152}
153
154impl<V: Valuation<TaskId>> Participant for cbba::Agent<V> {
155    type Message = cbba::Message;
156
157    fn id(&self) -> AgentId {
158        self.id()
159    }
160
161    fn bundle(&self) -> &Bundle<TaskId> {
162        self.bundle()
163    }
164
165    /// Runs the bundle phase and broadcasts the agent's full state, every round.
166    fn act(&mut self, _now: u64, outbox: &mut Vec<cbba::Message>) {
167        self.build_bundle();
168        outbox.push(self.message());
169    }
170
171    /// Runs the consensus phase for `message`; CBBA answers in the next round, not now.
172    fn receive(&mut self, _now: u64, message: &cbba::Message, _outbox: &mut Vec<cbba::Message>) {
173        cbba::Agent::receive(self, message);
174    }
175
176    /// The team agrees on every winner, every bundle matches, no agent's bundle phase would
177    /// change anything, and every message in flight carries the agreed winners. A team
178    /// that has not bid yet is not settled.
179    fn is_settled(team: &[Self], in_flight: &[&cbba::Message]) -> bool {
180        let Some(first) = team.first() else {
181            return true;
182        };
183
184        team.iter().all(cbba::Agent::is_consistent)
185            && !team.iter().any(cbba::Agent::can_bid)
186            && team.iter().all(|agent| agent.claims() == first.claims())
187            && in_flight
188                .iter()
189                .all(|message| message.claims() == first.claims())
190    }
191}
192
193/// Message copies on their way.
194type Copies<M> = Vec<InFlight<M>>;
195
196/// A message copy on its way to one agent.
197#[derive(Clone, Debug)]
198struct InFlight<M> {
199    /// The tick at which the copy arrives.
200    arrives: u64,
201
202    /// Sending order, to deliver copies arriving in the same tick deterministically.
203    order: u64,
204
205    /// The receiver.
206    to: AgentId,
207
208    /// The message, shared by all copies of one broadcast.
209    message: Rc<M>,
210}
211
212/// A team of agents on a simulated network.
213///
214/// # Examples
215///
216/// ```
217/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent, sim::{Network, Simulation}};
218///
219/// /// Values task `t` at `10 + t`, minus 3 for every task already held.
220/// struct Worker;
221///
222/// impl Valuation<TaskId> for Worker {
223///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
224///         (10 + task.index() as u64).checked_sub(3 * path.len() as u64)
225///     }
226/// }
227///
228/// let agents = (0..3).map(|id| Agent::new(AgentId(id), 3, 5, 2, Worker)).collect();
229/// let network = Network { seed: 7, max_delay: 3, loss_per_mille: 200, ..Network::default() };
230/// let mut simulation = Simulation::new(agents, network);
231///
232/// let ticks = simulation.run_until_settled(500).expect("settles");
233/// assert!(simulation.assignment().is_conflict_free());
234/// assert!(ticks <= 500);
235/// ```
236#[derive(Clone, Debug)]
237pub struct Simulation<A: Participant> {
238    /// The team, indexed by agent.
239    agents: Vec<A>,
240
241    /// The network's behavior.
242    network: Network,
243
244    /// The source of delays and losses.
245    rng: SplitMix64,
246
247    /// The current tick: how many steps have run.
248    tick: u64,
249
250    /// Copies still on their way.
251    in_flight: Copies<A::Message>,
252
253    /// The sending order of the next copy.
254    next_order: u64,
255
256    /// Message counts so far.
257    stats: Stats,
258}
259
260impl<A: Participant> Simulation<A> {
261    /// A simulation of `agents` on `network`, at tick zero with nothing in flight.
262    ///
263    /// # Panics
264    ///
265    /// Panics when the agents are not identified `0..agents.len()` in order.
266    #[must_use]
267    pub fn new(agents: Vec<A>, network: Network) -> Self {
268        let in_order = agents
269            .iter()
270            .enumerate()
271            .all(|(index, agent)| agent.id() == AgentId(index));
272        assert!(in_order, "agents must be identified 0, 1, 2, ... in order");
273
274        let rng = SplitMix64::new(network.seed);
275
276        Self {
277            agents,
278            network,
279            rng,
280            tick: 0,
281            in_flight: Vec::new(),
282            next_order: 0,
283            stats: Stats::default(),
284        }
285    }
286
287    /// Runs one tick: delivers the messages due, runs every agent's round, and broadcasts
288    /// what the agents put in their outboxes.
289    pub fn step(&mut self) {
290        let mut outboxes: Vec<Vec<A::Message>> = self.agents.iter().map(|_| Vec::new()).collect();
291        self.deliver_due(&mut outboxes);
292
293        for (agent, outbox) in self.agents.iter_mut().zip(&mut outboxes) {
294            agent.act(self.tick, outbox);
295        }
296
297        self.broadcast_all(outboxes);
298        self.tick += 1;
299    }
300
301    /// Steps until the team is [settled](Simulation::is_settled), at most `max_ticks` times;
302    /// returns the tick at which it settled, or `None` when it did not within the limit.
303    pub fn run_until_settled(&mut self, max_ticks: u64) -> Option<u64> {
304        let limit = self.tick.saturating_add(max_ticks);
305        while self.tick < limit {
306            self.step();
307            if self.is_settled() {
308                return Some(self.tick);
309            }
310        }
311
312        None
313    }
314
315    /// Whether the team has settled: see [`Participant::is_settled`]. Nothing changes after
316    /// that.
317    #[must_use]
318    pub fn is_settled(&self) -> bool {
319        let in_flight: Vec<&A::Message> =
320            self.in_flight.iter().map(|copy| &*copy.message).collect();
321
322        A::is_settled(&self.agents, &in_flight)
323    }
324
325    /// Delivers every copy due by the current tick, in arrival order, collecting what the
326    /// receivers broadcast in response in `outboxes`.
327    fn deliver_due(&mut self, outboxes: &mut [Vec<A::Message>]) {
328        let tick = self.tick;
329        let (mut due, waiting): (Copies<A::Message>, Copies<A::Message>) = self
330            .in_flight
331            .drain(..)
332            .partition(|copy| copy.arrives <= tick);
333        self.in_flight = waiting;
334        due.sort_unstable_by_key(|copy| (copy.arrives, copy.order));
335
336        for copy in due {
337            let to = copy.to.index();
338            self.agents[to].receive(tick, &copy.message, &mut outboxes[to]);
339            self.stats.delivered += 1;
340        }
341    }
342
343    /// Broadcasts every message in every agent's outbox.
344    fn broadcast_all(&mut self, outboxes: Vec<Vec<A::Message>>) {
345        let agents = self.agents.len();
346        for (sender, outbox) in outboxes.into_iter().enumerate() {
347            for message in outbox {
348                let message = Rc::new(message);
349                for receiver in (0..agents).filter(|&receiver| receiver != sender) {
350                    self.send(AgentId(sender), AgentId(receiver), &message);
351                }
352            }
353        }
354    }
355
356    /// Sends one copy of `message` from `from` to `to`, unless a partition blocks it or the
357    /// network loses it.
358    fn send(&mut self, from: AgentId, to: AgentId, message: &Rc<A::Message>) {
359        if self.is_cut_off(from, to) {
360            self.stats.blocked += 1;
361            return;
362        }
363
364        self.stats.sent += 1;
365        if self.rng.below(1000) < u64::from(self.network.loss_per_mille) {
366            self.stats.lost += 1;
367            return;
368        }
369
370        let delay = 1 + self.rng.below(self.network.max_delay.saturating_add(1));
371        self.in_flight.push(InFlight {
372            arrives: self.tick + delay,
373            order: self.next_order,
374            to,
375            message: Rc::clone(message),
376        });
377        self.next_order += 1;
378    }
379
380    /// Whether `a` and `b` have no direct link, or an active partition separates them now.
381    fn is_cut_off(&self, a: AgentId, b: AgentId) -> bool {
382        !self.network.topology.connects(a, b)
383            || self
384                .network
385                .partitions
386                .iter()
387                .any(|partition| partition.separates(self.tick, a, b))
388    }
389
390    /// The team, indexed by agent.
391    #[must_use]
392    pub fn agents(&self) -> &[A] {
393        &self.agents
394    }
395
396    /// The current tick: how many steps have run.
397    #[must_use]
398    pub const fn tick(&self) -> u64 {
399        self.tick
400    }
401
402    /// Message counts so far.
403    #[must_use]
404    pub const fn stats(&self) -> Stats {
405        self.stats
406    }
407
408    /// Every agent's bundle, as one assignment. It is conflict-free once the team is
409    /// [settled](Simulation::is_settled); before, agents may still hold the same task.
410    #[must_use]
411    pub fn assignment(&self) -> Assignment {
412        Assignment::from_bundles(
413            self.agents
414                .iter()
415                .map(|agent| agent.bundle().clone())
416                .collect(),
417        )
418    }
419}
420
421/// Unit tests for the simulated network.
422#[cfg(test)]
423mod tests;