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 if self.has_left() {
168 return;
169 }
170
171 self.build_bundle();
172 outbox.push(self.message());
173 }
174
175 /// Runs the consensus phase for `message`; CBBA answers in the next round, not now.
176 fn receive(&mut self, _now: u64, message: &cbba::Message, _outbox: &mut Vec<cbba::Message>) {
177 cbba::Agent::receive(self, message);
178 }
179
180 /// The team agrees on every winner, every bundle matches, no agent's bundle phase would
181 /// change anything, and every message in flight carries the agreed winners. A team
182 /// that has not bid yet is not settled.
183 ///
184 /// Agents that left the team, and messages they sent, are disregarded.
185 fn is_settled(team: &[Self], in_flight: &[&cbba::Message]) -> bool {
186 let mut active = team.iter().filter(|agent| !agent.has_left());
187 let Some(first) = active.next() else {
188 return true;
189 };
190
191 let active = || team.iter().filter(|agent| !agent.has_left());
192
193 active().all(cbba::Agent::is_consistent)
194 && !active().any(cbba::Agent::can_bid)
195 && active().all(|agent| agent.claims() == first.claims())
196 && in_flight
197 .iter()
198 .filter(|message| !first.has_departed(message.sender()))
199 .all(|message| message.claims() == first.claims())
200 }
201}
202
203/// Message copies on their way.
204type Copies<M> = Vec<InFlight<M>>;
205
206/// A message copy on its way to one agent.
207#[derive(Clone, Debug)]
208struct InFlight<M> {
209 /// The tick at which the copy arrives.
210 arrives: u64,
211
212 /// Sending order, to deliver copies arriving in the same tick deterministically.
213 order: u64,
214
215 /// The receiver.
216 to: AgentId,
217
218 /// The message, shared by all copies of one broadcast.
219 message: Rc<M>,
220}
221
222/// A team of agents on a simulated network.
223///
224/// # Examples
225///
226/// ```
227/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent, sim::{Network, Simulation}};
228///
229/// /// Values task `t` at `10 + t`, minus 3 for every task already held.
230/// struct Worker;
231///
232/// impl Valuation<TaskId> for Worker {
233/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
234/// (10 + task.index() as u64).checked_sub(3 * path.len() as u64)
235/// }
236/// }
237///
238/// let agents = (0..3).map(|id| Agent::new(AgentId(id), 3, 5, 2, Worker)).collect();
239/// let network = Network { seed: 7, max_delay: 3, loss_per_mille: 200, ..Network::default() };
240/// let mut simulation = Simulation::new(agents, network);
241///
242/// let ticks = simulation.run_until_settled(500).expect("settles");
243/// assert!(simulation.assignment().is_conflict_free());
244/// assert!(ticks <= 500);
245/// ```
246#[derive(Clone, Debug)]
247pub struct Simulation<A: Participant> {
248 /// The team, indexed by agent.
249 agents: Vec<A>,
250
251 /// The network's behavior.
252 network: Network,
253
254 /// The source of delays and losses.
255 rng: SplitMix64,
256
257 /// The current tick: how many steps have run.
258 tick: u64,
259
260 /// Copies still on their way.
261 in_flight: Copies<A::Message>,
262
263 /// Copies due this tick, kept between ticks so delivering does not allocate.
264 due: Copies<A::Message>,
265
266 /// Each agent's outbox for this tick, kept between ticks so stepping does not allocate.
267 outboxes: Vec<Vec<A::Message>>,
268
269 /// The sending order of the next copy.
270 next_order: u64,
271
272 /// Message counts so far.
273 stats: Stats,
274}
275
276impl<A: Participant> Simulation<A> {
277 /// A simulation of `agents` on `network`, at tick zero with nothing in flight.
278 ///
279 /// # Panics
280 ///
281 /// Panics when the agents are not identified `0..agents.len()` in order.
282 #[must_use]
283 pub fn new(agents: Vec<A>, network: Network) -> Self {
284 let in_order = agents
285 .iter()
286 .enumerate()
287 .all(|(index, agent)| agent.id() == AgentId(index));
288 assert!(in_order, "agents must be identified 0, 1, 2, ... in order");
289
290 let rng = SplitMix64::new(network.seed);
291
292 Self {
293 agents,
294 network,
295 rng,
296 tick: 0,
297 in_flight: Vec::new(),
298 due: Vec::new(),
299 outboxes: Vec::new(),
300 next_order: 0,
301 stats: Stats::default(),
302 }
303 }
304
305 /// Runs one tick: delivers the messages due, runs every agent's round, and broadcasts
306 /// what the agents put in their outboxes.
307 pub fn step(&mut self) {
308 let mut outboxes = core::mem::take(&mut self.outboxes);
309 outboxes.resize_with(self.agents.len(), Vec::new);
310 self.deliver_due(&mut outboxes);
311
312 for (agent, outbox) in self.agents.iter_mut().zip(&mut outboxes) {
313 agent.act(self.tick, outbox);
314 }
315
316 self.broadcast_all(&mut outboxes);
317 self.outboxes = outboxes;
318 self.tick += 1;
319 }
320
321 /// Steps until the team is [settled](Simulation::is_settled), at most `max_ticks` times;
322 /// returns the tick at which it settled, or `None` when it did not within the limit.
323 pub fn run_until_settled(&mut self, max_ticks: u64) -> Option<u64> {
324 let limit = self.tick.saturating_add(max_ticks);
325 while self.tick < limit {
326 self.step();
327 if self.is_settled() {
328 return Some(self.tick);
329 }
330 }
331
332 None
333 }
334
335 /// Whether the team has settled: see [`Participant::is_settled`]. Nothing changes after
336 /// that.
337 #[must_use]
338 pub fn is_settled(&self) -> bool {
339 let in_flight: Vec<&A::Message> =
340 self.in_flight.iter().map(|copy| &*copy.message).collect();
341
342 A::is_settled(&self.agents, &in_flight)
343 }
344
345 /// Delivers every copy due by the current tick, in arrival order, collecting what the
346 /// receivers broadcast in response in `outboxes`.
347 fn deliver_due(&mut self, outboxes: &mut [Vec<A::Message>]) {
348 let tick = self.tick;
349 let mut due = core::mem::take(&mut self.due);
350 let mut index = 0;
351 while index < self.in_flight.len() {
352 if self.in_flight[index].arrives <= tick {
353 due.push(self.in_flight.swap_remove(index));
354 } else {
355 index += 1;
356 }
357 }
358
359 due.sort_unstable_by_key(|copy| (copy.arrives, copy.order));
360 for copy in due.drain(..) {
361 let to = copy.to.index();
362 self.agents[to].receive(tick, ©.message, &mut outboxes[to]);
363 self.stats.delivered += 1;
364 }
365
366 self.due = due;
367 }
368
369 /// Broadcasts every message in every agent's outbox, leaving the outboxes empty.
370 fn broadcast_all(&mut self, outboxes: &mut [Vec<A::Message>]) {
371 let agents = self.agents.len();
372 for (sender, outbox) in outboxes.iter_mut().enumerate() {
373 for message in outbox.drain(..) {
374 let message = Rc::new(message);
375 for receiver in (0..agents).filter(|&receiver| receiver != sender) {
376 self.send(AgentId(sender), AgentId(receiver), &message);
377 }
378 }
379 }
380 }
381
382 /// Sends one copy of `message` from `from` to `to`, unless a partition blocks it or the
383 /// network loses it.
384 fn send(&mut self, from: AgentId, to: AgentId, message: &Rc<A::Message>) {
385 if self.is_cut_off(from, to) {
386 self.stats.blocked += 1;
387 return;
388 }
389
390 self.stats.sent += 1;
391 if self.rng.below(1000) < u64::from(self.network.loss_per_mille) {
392 self.stats.lost += 1;
393 return;
394 }
395
396 let delay = 1 + self.rng.below(self.network.max_delay.saturating_add(1));
397 self.in_flight.push(InFlight {
398 arrives: self.tick + delay,
399 order: self.next_order,
400 to,
401 message: Rc::clone(message),
402 });
403 self.next_order += 1;
404 }
405
406 /// Whether `a` and `b` have no direct link, or an active partition separates them now.
407 fn is_cut_off(&self, a: AgentId, b: AgentId) -> bool {
408 !self.network.topology.connects(a, b)
409 || self
410 .network
411 .partitions
412 .iter()
413 .any(|partition| partition.separates(self.tick, a, b))
414 }
415
416 /// The team, indexed by agent.
417 #[must_use]
418 pub fn agents(&self) -> &[A] {
419 &self.agents
420 }
421
422 /// The team, to change it between steps: add a task, retire one, or let an agent leave.
423 pub fn agents_mut(&mut self) -> &mut [A] {
424 &mut self.agents
425 }
426
427 /// The current tick: how many steps have run.
428 #[must_use]
429 pub const fn tick(&self) -> u64 {
430 self.tick
431 }
432
433 /// Message counts so far.
434 #[must_use]
435 pub const fn stats(&self) -> Stats {
436 self.stats
437 }
438
439 /// Every agent's bundle, as one assignment. It is conflict-free once the team is
440 /// [settled](Simulation::is_settled); before, agents may still hold the same task.
441 #[must_use]
442 pub fn assignment(&self) -> Assignment {
443 Assignment::from_bundles(
444 self.agents
445 .iter()
446 .map(|agent| agent.bundle().clone())
447 .collect(),
448 )
449 }
450}
451
452/// Unit tests for the simulated network.
453#[cfg(test)]
454mod tests;