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//! Two optional models make the network harsher: [`Network::collisions`] lets senders
23//! that cannot hear each other destroy each other's copies, and [`Network::clusters`]
24//! lets groups of agents exchange messages with each other only every few ticks. Both are
25//! off by default and draw no randomness then, so seeded runs stay the same.
26//!
27//! [`Stats`] counts what the run cost: copies sent, delivered and lost, the bytes
28//! broadcast, and how many delivered copies changed their receiver.
29//!
30//! When a team is *settled* is up to the protocol ([`Participant::is_settled`]). For CBBA,
31//! every agent believes in the same winners, every agent's bundle holds exactly the tasks it
32//! wins, no bundle phase would change anything, and every message still in flight carries
33//! those same winners. Nothing can change after that.
34
35mod rng;
36
37use alloc::rc::Rc;
38use alloc::vec::Vec;
39
40use crate::assignment::Assignment;
41use crate::bundle::Bundle;
42use crate::cbba;
43use crate::id::{AgentId, TaskId};
44use crate::valuation::Valuation;
45use rng::SplitMix64;
46
47/// How the simulated network behaves.
48#[derive(Clone, Debug, Default, PartialEq, Eq)]
49pub struct Network {
50 /// Seeds every random choice: delays and losses.
51 pub seed: u64,
52
53 /// The most extra ticks a message may take, on top of the one tick every message takes.
54 pub max_delay: u64,
55
56 /// The chance, per mille, that one copy of a broadcast is lost. 0 is lossless; 1000 or
57 /// more loses everything.
58 pub loss_per_mille: u16,
59
60 /// Which agents can reach each other at all.
61 pub topology: Topology,
62
63 /// Intervals in which groups of agents cannot reach each other.
64 pub partitions: Vec<Partition>,
65
66 /// Whether broadcasts from hidden nodes collide.
67 ///
68 /// Every message a sender broadcasts is a frame that waits a random backoff of one of
69 /// [`BACKOFF_SLOTS`] slots before going out, as 802.11 radios do. Two frames from
70 /// senders that cannot hear each other in the same slot are both lost to every agent
71 /// that hears both senders; their bytes still count, since they took the airtime.
72 /// Senders that hear each other take turns, as radios sensing the channel do, so on a
73 /// [`Topology::Complete`] network nothing collides. This follows the hidden-node
74 /// picture in Raja, Habibi and How (IEEE Access 10, 2022, p. 19756), with their
75 /// contention window of 16.
76 pub collisions: bool,
77
78 /// Clusters that talk among themselves every tick, but with each other only every
79 /// few ticks; `None` for one rate everywhere.
80 pub clusters: Option<Clusters>,
81}
82
83/// The backoff slots a sender picks from each tick when [`Network::collisions`] is on.
84pub const BACKOFF_SLOTS: u64 = 16;
85
86/// Groups of agents that exchange messages at different rates: inside a group as usual,
87/// between groups only every `period` ticks.
88///
89/// A copy between groups arrives at the first multiple of `period` at or after the tick it
90/// would otherwise arrive at. This is the multirate idea of hierarchical co-simulation
91/// (Hafner, *Cooperative and Multirate Simulation Analysis*, TU Wien, 2021): tightly
92/// coupled parts synchronize often, the whole less often.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct Clusters {
95 /// The group of each agent, indexed by agent. Agents missing from the list form a group
96 /// of their own each.
97 pub groups: Vec<usize>,
98
99 /// Ticks between two exchanges across groups; positive. One changes nothing.
100 pub period: u64,
101}
102
103/// Whether `a` and `b` are in the same group of `groups`, where agents missing from the
104/// list form a group of their own each.
105fn same_group(groups: &[usize], a: AgentId, b: AgentId) -> bool {
106 groups
107 .get(a.index())
108 .is_some_and(|group| groups.get(b.index()) == Some(group))
109}
110
111/// Which pairs of agents can exchange messages directly. Agents without a direct link only
112/// hear of each other through relays.
113#[derive(Clone, Debug, Default, PartialEq, Eq)]
114pub enum Topology {
115 /// Every agent reaches every other agent.
116 #[default]
117 Complete,
118
119 /// Only the listed pairs reach each other, in both directions.
120 Links(Vec<(AgentId, AgentId)>),
121}
122
123impl Topology {
124 /// Whether `a` and `b` can exchange messages directly.
125 #[must_use]
126 pub fn connects(&self, a: AgentId, b: AgentId) -> bool {
127 match self {
128 Self::Complete => true,
129 Self::Links(links) => links.iter().any(|&link| link == (a, b) || link == (b, a)),
130 }
131 }
132}
133
134/// A time interval in which agents in different groups cannot reach each other.
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct Partition {
137 /// The first tick of the partition.
138 pub from: u64,
139
140 /// The tick at which the partition heals; it is active for ticks `from..until`.
141 pub until: u64,
142
143 /// The group of each agent, indexed by agent. Agents missing from the list form a group
144 /// of their own each.
145 pub groups: Vec<usize>,
146}
147
148impl Partition {
149 /// Whether the partition separates agents `a` and `b` at `tick`.
150 #[must_use]
151 pub fn separates(&self, tick: u64, a: AgentId, b: AgentId) -> bool {
152 let active = (self.from..self.until).contains(&tick);
153
154 active && !same_group(&self.groups, a, b)
155 }
156}
157
158/// Message counts over a run.
159///
160/// Two ratios compare protocols beyond raw counts:
161///
162/// - **Value of a message:** `useful / delivered`, the share of delivered copies that
163/// changed the receiver's winners, bids or bundle. Raja, Habibi and How ("Communication-
164/// Aware Consensus-Based Decentralized Task Allocation", IEEE Access 10, 2022, Eq. 3)
165/// average the number of changed winning-bid entries per neighbor instead; here a copy
166/// counts once, however many entries it changed.
167/// - **Bytes per completed task:** `bytes` divided by the number of tasks the final
168/// [assignment](Simulation::assignment) holds, as in Zhao et al. ("AC-DMTA", Drones 10,
169/// 2026, Sec. 5.4). Sizes are nominal; see [`Participant::message_bytes`].
170#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
171pub struct Stats {
172 /// Copies of broadcasts put on the network, one per reachable receiver.
173 pub sent: u64,
174
175 /// Copies that arrived.
176 pub delivered: u64,
177
178 /// Copies the network lost.
179 pub lost: u64,
180
181 /// Copies that could not be sent because the topology has no link to the receiver, or a
182 /// partition cut it off.
183 pub blocked: u64,
184
185 /// Delivered copies that changed the receiver's winners, bids or bundle.
186 pub useful: u64,
187
188 /// Bytes broadcast, by [`Participant::message_bytes`], counted once per broadcast that
189 /// went on the air to at least one receiver, whether its copies arrived or were lost:
190 /// on a shared radio channel, one transmission reaches every neighbor and costs the
191 /// same airtime either way.
192 pub bytes: u64,
193
194 /// Copies lost to [collisions](Network::collisions) between hidden senders; also
195 /// counted in `sent`, not in `lost`.
196 pub collided: u64,
197}
198
199/// An agent that a [`Simulation`] can run: it works in rounds, broadcasts messages, and
200/// handles the messages that reach it.
201///
202/// [`cbba::Agent`] implements it; so can other consensus protocols.
203pub trait Participant: Sized {
204 /// What the agent broadcasts.
205 type Message;
206
207 /// The agent's identifier.
208 fn id(&self) -> AgentId;
209
210 /// The tasks the agent holds now.
211 fn bundle(&self) -> &Bundle<TaskId>;
212
213 /// One round of the agent's own work at tick `now`, such as its bundle phase; pushes
214 /// what it broadcasts onto `outbox`.
215 fn act(&mut self, now: u64, outbox: &mut Vec<Self::Message>);
216
217 /// Handles `message`, arriving at tick `now`; pushes what the agent broadcasts in
218 /// response onto `outbox`. Returns whether the agent's winners, bids or bundle changed,
219 /// for [`Stats::useful`].
220 fn receive(
221 &mut self,
222 now: u64,
223 message: &Self::Message,
224 outbox: &mut Vec<Self::Message>,
225 ) -> bool;
226
227 /// The size of `message` on the wire, in bytes, for [`Stats::bytes`].
228 ///
229 /// The protocols in this crate use a nominal encoding without compression: 4 bytes per
230 /// agent or task identifier (an absent winner takes a reserved value), 8 per bid,
231 /// timestamp or clock, 1 per tag, and a 4-byte length before every list.
232 fn message_bytes(message: &Self::Message) -> u64;
233
234 /// Whether `team` has settled, with `in_flight` still on its way: the agents agree on a
235 /// conflict-free assignment that nothing in flight and no further round can change.
236 fn is_settled(team: &[Self], in_flight: &[&Self::Message]) -> bool;
237}
238
239impl<V: Valuation<TaskId>> Participant for cbba::Agent<V> {
240 type Message = cbba::Message;
241
242 fn id(&self) -> AgentId {
243 self.id()
244 }
245
246 fn bundle(&self) -> &Bundle<TaskId> {
247 self.bundle()
248 }
249
250 /// Runs the bundle phase and broadcasts the agent's full state when its
251 /// [`Cadence`](cbba::Cadence) calls for it; by default, every round.
252 fn act(&mut self, _now: u64, outbox: &mut Vec<cbba::Message>) {
253 if self.has_left() {
254 return;
255 }
256
257 self.build_bundle();
258 if self.broadcast_due() {
259 outbox.push(self.message());
260 }
261 }
262
263 /// Runs the consensus phase for `message`; CBBA answers in the next round, not now.
264 fn receive(
265 &mut self,
266 _now: u64,
267 message: &cbba::Message,
268 _outbox: &mut Vec<cbba::Message>,
269 ) -> bool {
270 cbba::Agent::receive(self, message)
271 }
272
273 /// The sender, every task's winner and bid, and every agent's clock.
274 fn message_bytes(message: &cbba::Message) -> u64 {
275 message.bytes()
276 }
277
278 /// The team agrees on every winner, every bundle matches, no agent's bundle phase would
279 /// change anything, and every message in flight carries the agreed winners. A team
280 /// that has not bid yet is not settled.
281 ///
282 /// Agents that left the team, and messages they sent, are disregarded.
283 fn is_settled(team: &[Self], in_flight: &[&cbba::Message]) -> bool {
284 let mut active = team.iter().filter(|agent| !agent.has_left());
285 let Some(first) = active.next() else {
286 return true;
287 };
288
289 let active = || team.iter().filter(|agent| !agent.has_left());
290
291 active().all(cbba::Agent::is_consistent)
292 && !active().any(cbba::Agent::can_bid)
293 && active().all(|agent| agent.claims() == first.claims())
294 && in_flight
295 .iter()
296 .filter(|message| !first.has_departed(message.sender()))
297 .all(|message| message.claims() == first.claims())
298 }
299}
300
301/// Message copies on their way.
302type Copies<M> = Vec<InFlight<M>>;
303
304/// A message copy on its way to one agent.
305#[derive(Clone, Debug)]
306struct InFlight<M> {
307 /// The tick at which the copy arrives.
308 arrives: u64,
309
310 /// Sending order, to deliver copies arriving in the same tick deterministically.
311 order: u64,
312
313 /// The receiver.
314 to: AgentId,
315
316 /// The message, shared by all copies of one broadcast.
317 message: Rc<M>,
318}
319
320/// A team of agents on a simulated network.
321///
322/// # Examples
323///
324/// ```
325/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent, sim::{Network, Simulation}};
326///
327/// /// Values task `t` at `10 + t`, minus 3 for every task already held.
328/// struct Worker;
329///
330/// impl Valuation<TaskId> for Worker {
331/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
332/// (10 + task.index() as u64).checked_sub(3 * path.len() as u64)
333/// }
334/// }
335///
336/// let agents = (0..3).map(|id| Agent::new(AgentId(id), 3, 5, 2, Worker)).collect();
337/// let network = Network { seed: 7, max_delay: 3, loss_per_mille: 200, ..Network::default() };
338/// let mut simulation = Simulation::new(agents, network);
339///
340/// let ticks = simulation.run_until_settled(500).expect("settles");
341/// assert!(simulation.assignment().is_conflict_free());
342/// assert!(ticks <= 500);
343/// ```
344#[derive(Clone, Debug)]
345pub struct Simulation<A: Participant> {
346 /// The team, indexed by agent.
347 agents: Vec<A>,
348
349 /// The network's behavior.
350 network: Network,
351
352 /// The source of delays and losses.
353 rng: SplitMix64,
354
355 /// The current tick: how many steps have run.
356 tick: u64,
357
358 /// Copies still on their way.
359 in_flight: Copies<A::Message>,
360
361 /// Copies due this tick, kept between ticks so delivering does not allocate.
362 due: Copies<A::Message>,
363
364 /// Each agent's outbox for this tick, kept between ticks so stepping does not allocate.
365 outboxes: Vec<Vec<A::Message>>,
366
367 /// The sending order of the next copy.
368 next_order: u64,
369
370 /// Message counts so far.
371 stats: Stats,
372}
373
374impl<A: Participant> Simulation<A> {
375 /// A simulation of `agents` on `network`, at tick zero with nothing in flight.
376 ///
377 /// # Panics
378 ///
379 /// Panics when the agents are not identified `0..agents.len()` in order, and when the
380 /// network's [`Clusters::period`] is zero.
381 #[must_use]
382 pub fn new(agents: Vec<A>, network: Network) -> Self {
383 let in_order = agents
384 .iter()
385 .enumerate()
386 .all(|(index, agent)| agent.id() == AgentId(index));
387 assert!(in_order, "agents must be identified 0, 1, 2, ... in order");
388 assert!(
389 network
390 .clusters
391 .as_ref()
392 .is_none_or(|clusters| clusters.period > 0),
393 "clusters must exchange messages every positive number of ticks"
394 );
395
396 let rng = SplitMix64::new(network.seed);
397
398 Self {
399 agents,
400 network,
401 rng,
402 tick: 0,
403 in_flight: Vec::new(),
404 due: Vec::new(),
405 outboxes: Vec::new(),
406 next_order: 0,
407 stats: Stats::default(),
408 }
409 }
410
411 /// Runs one tick: delivers the messages due, runs every agent's round, and broadcasts
412 /// what the agents put in their outboxes.
413 pub fn step(&mut self) {
414 let mut outboxes = core::mem::take(&mut self.outboxes);
415 outboxes.resize_with(self.agents.len(), Vec::new);
416 self.deliver_due(&mut outboxes);
417
418 for (agent, outbox) in self.agents.iter_mut().zip(&mut outboxes) {
419 agent.act(self.tick, outbox);
420 }
421
422 self.broadcast_all(&mut outboxes);
423 self.outboxes = outboxes;
424 self.tick += 1;
425 }
426
427 /// Steps until the team is [settled](Simulation::is_settled), at most `max_ticks` times;
428 /// returns the tick at which it settled, or `None` when it did not within the limit.
429 pub fn run_until_settled(&mut self, max_ticks: u64) -> Option<u64> {
430 let limit = self.tick.saturating_add(max_ticks);
431 while self.tick < limit {
432 self.step();
433 if self.is_settled() {
434 return Some(self.tick);
435 }
436 }
437
438 None
439 }
440
441 /// Whether the team has settled: see [`Participant::is_settled`]. Nothing changes after
442 /// that.
443 #[must_use]
444 pub fn is_settled(&self) -> bool {
445 let in_flight: Vec<&A::Message> =
446 self.in_flight.iter().map(|copy| &*copy.message).collect();
447
448 A::is_settled(&self.agents, &in_flight)
449 }
450
451 /// Delivers every copy due by the current tick, in arrival order, collecting what the
452 /// receivers broadcast in response in `outboxes`.
453 fn deliver_due(&mut self, outboxes: &mut [Vec<A::Message>]) {
454 let tick = self.tick;
455 let mut due = core::mem::take(&mut self.due);
456 let mut index = 0;
457 while index < self.in_flight.len() {
458 if self.in_flight[index].arrives <= tick {
459 due.push(self.in_flight.swap_remove(index));
460 } else {
461 index += 1;
462 }
463 }
464
465 due.sort_unstable_by_key(|copy| (copy.arrives, copy.order));
466 for copy in due.drain(..) {
467 let to = copy.to.index();
468 let changed = self.agents[to].receive(tick, ©.message, &mut outboxes[to]);
469 self.stats.delivered += 1;
470 self.stats.useful += u64::from(changed);
471 }
472
473 self.due = due;
474 }
475
476 /// Broadcasts every message in every agent's outbox, leaving the outboxes empty.
477 fn broadcast_all(&mut self, outboxes: &mut [Vec<A::Message>]) {
478 let agents = self.agents.len();
479 let slots = self.backoff_slots(outboxes);
480
481 for (sender, outbox) in outboxes.iter_mut().enumerate() {
482 for (frame, message) in outbox.drain(..).enumerate() {
483 let message = Rc::new(message);
484 let slot = slots
485 .get(sender)
486 .and_then(|frames| frames.get(frame))
487 .copied();
488 let mut transmitted = false;
489 for receiver in (0..agents).filter(|&receiver| receiver != sender) {
490 let (from, to) = (AgentId(sender), AgentId(receiver));
491 let collides = slot.is_some_and(|slot| self.collides(&slots, from, slot, to));
492 transmitted |= self.send(from, to, &message, collides);
493 }
494
495 if transmitted {
496 self.stats.bytes += A::message_bytes(&message);
497 }
498 }
499 }
500 }
501
502 /// The backoff slot of every message in every agent's outbox this tick: each message is
503 /// its own frame and contends on its own. Empty when [collisions](Network::collisions)
504 /// are off, so that no randomness is drawn.
505 fn backoff_slots(&mut self, outboxes: &[Vec<A::Message>]) -> Vec<Vec<u64>> {
506 if !self.network.collisions {
507 return Vec::new();
508 }
509
510 outboxes
511 .iter()
512 .map(|outbox| {
513 outbox
514 .iter()
515 .map(|_| self.rng.below(BACKOFF_SLOTS))
516 .collect()
517 })
518 .collect()
519 }
520
521 /// Whether the copy from `from` to `to`, sent in backoff `slot`, collides: another
522 /// sender with a frame in the same slot reaches `to` but cannot hear `from`.
523 fn collides(&self, slots: &[Vec<u64>], from: AgentId, slot: u64, to: AgentId) -> bool {
524 slots.iter().enumerate().any(|(other, frames)| {
525 let other = AgentId(other);
526
527 frames.contains(&slot)
528 && other != from
529 && other != to
530 && !self.is_cut_off(other, to)
531 && self.is_cut_off(from, other)
532 })
533 }
534
535 /// Sends one copy of `message` from `from` to `to`, unless a partition blocks it, it
536 /// `collides` with a hidden sender's, or the network loses it; returns whether the copy
537 /// went on the air, lost or not.
538 fn send(
539 &mut self,
540 from: AgentId,
541 to: AgentId,
542 message: &Rc<A::Message>,
543 collides: bool,
544 ) -> bool {
545 if self.is_cut_off(from, to) {
546 self.stats.blocked += 1;
547 return false;
548 }
549
550 self.stats.sent += 1;
551 if collides {
552 self.stats.collided += 1;
553 return true;
554 }
555
556 if self.rng.below(1000) < u64::from(self.network.loss_per_mille) {
557 self.stats.lost += 1;
558 return true;
559 }
560
561 let delay = 1 + self.rng.below(self.network.max_delay.saturating_add(1));
562 self.in_flight.push(InFlight {
563 arrives: self.arrival(from, to, self.tick + delay),
564 order: self.next_order,
565 to,
566 message: Rc::clone(message),
567 });
568 self.next_order += 1;
569
570 true
571 }
572
573 /// When a copy from `from` to `to` that would arrive at `tick` does arrive: then, or,
574 /// between [clusters](Network::clusters), at the next exchange across them.
575 fn arrival(&self, from: AgentId, to: AgentId, tick: u64) -> u64 {
576 match &self.network.clusters {
577 Some(clusters) if !same_group(&clusters.groups, from, to) => {
578 tick.div_ceil(clusters.period) * clusters.period
579 }
580 _ => tick,
581 }
582 }
583
584 /// Whether `a` and `b` have no direct link, or an active partition separates them now.
585 fn is_cut_off(&self, a: AgentId, b: AgentId) -> bool {
586 !self.network.topology.connects(a, b)
587 || self
588 .network
589 .partitions
590 .iter()
591 .any(|partition| partition.separates(self.tick, a, b))
592 }
593
594 /// The team, indexed by agent.
595 #[must_use]
596 pub fn agents(&self) -> &[A] {
597 &self.agents
598 }
599
600 /// The team, to change it between steps: add a task, retire one, or let an agent leave.
601 pub fn agents_mut(&mut self) -> &mut [A] {
602 &mut self.agents
603 }
604
605 /// The current tick: how many steps have run.
606 #[must_use]
607 pub const fn tick(&self) -> u64 {
608 self.tick
609 }
610
611 /// Message counts so far.
612 #[must_use]
613 pub const fn stats(&self) -> Stats {
614 self.stats
615 }
616
617 /// Every agent's bundle, as one assignment. It is conflict-free once the team is
618 /// [settled](Simulation::is_settled); before, agents may still hold the same task.
619 #[must_use]
620 pub fn assignment(&self) -> Assignment {
621 Assignment::from_bundles(
622 self.agents
623 .iter()
624 .map(|agent| agent.bundle().clone())
625 .collect(),
626 )
627 }
628}
629
630/// Unit tests for the simulated network.
631#[cfg(test)]
632mod tests;