task-allocation 0.1.0

Decentralized multi-agent task allocation: consensus-based bundle algorithm (CBBA) and auctions that converge to conflict-free assignments over delayed, intermittent communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! A deterministic simulated network for running teams of agents: seeded delays, losses,
//! topologies and partitions.
//!
//! A [`Simulation`] runs any [`Participant`], such as a [`cbba::Agent`]. Each
//! [`Simulation::step`] is one tick:
//!
//! ```mermaid
//! flowchart LR
//!     deliver[deliver due messages] --> round[every agent's round]
//!     round --> broadcast[broadcast every outbox]
//!     broadcast --> deliver
//! ```
//!
//! Agents may also answer a delivered message right away; those answers go out with the
//! tick's broadcasts. A broadcast reaches every agent the sender has a link to in the
//! [`Topology`] and is not cut off from by an active [`Partition`]; others hear of it only
//! when it is relayed. Each copy is lost with probability [`Network::loss_per_mille`] /
//! 1000, and otherwise arrives after 1 to `1 + max_delay` ticks, so messages overtake each
//! other. Agents process the messages that arrive in a tick in arrival order. Everything
//! random comes from [`Network::seed`]: the same seed gives the same run.
//!
//! When a team is *settled* is up to the protocol ([`Participant::is_settled`]). For CBBA,
//! every agent believes in the same winners, every agent's bundle holds exactly the tasks it
//! wins, no bundle phase would change anything, and every message still in flight carries
//! those same winners. Nothing can change after that.

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;

/// How the simulated network behaves.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Network {
    /// Seeds every random choice: delays and losses.
    pub seed: u64,

    /// The most extra ticks a message may take, on top of the one tick every message takes.
    pub max_delay: u64,

    /// The chance, per mille, that one copy of a broadcast is lost. 0 is lossless; 1000 or
    /// more loses everything.
    pub loss_per_mille: u16,

    /// Which agents can reach each other at all.
    pub topology: Topology,

    /// Intervals in which groups of agents cannot reach each other.
    pub partitions: Vec<Partition>,
}

/// Which pairs of agents can exchange messages directly. Agents without a direct link only
/// hear of each other through relays.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Topology {
    /// Every agent reaches every other agent.
    #[default]
    Complete,

    /// Only the listed pairs reach each other, in both directions.
    Links(Vec<(AgentId, AgentId)>),
}

impl Topology {
    /// Whether `a` and `b` can exchange messages directly.
    #[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)),
        }
    }
}

/// A time interval in which agents in different groups cannot reach each other.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Partition {
    /// The first tick of the partition.
    pub from: u64,

    /// The tick at which the partition heals; it is active for ticks `from..until`.
    pub until: u64,

    /// The group of each agent, indexed by agent. Agents missing from the list form a group
    /// of their own each.
    pub groups: Vec<usize>,
}

impl Partition {
    /// Whether the partition separates agents `a` and `b` at `tick`.
    #[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))
    }
}

/// Message counts over a run.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
    /// Copies of broadcasts put on the network, one per reachable receiver.
    pub sent: u64,

    /// Copies that arrived.
    pub delivered: u64,

    /// Copies the network lost.
    pub lost: u64,

    /// Copies that could not be sent because the topology has no link to the receiver, or a
    /// partition cut it off.
    pub blocked: u64,
}

/// An agent that a [`Simulation`] can run: it works in rounds, broadcasts messages, and
/// handles the messages that reach it.
///
/// [`cbba::Agent`] implements it; so can other consensus protocols.
pub trait Participant: Sized {
    /// What the agent broadcasts.
    type Message;

    /// The agent's identifier.
    fn id(&self) -> AgentId;

    /// The tasks the agent holds now.
    fn bundle(&self) -> &Bundle<TaskId>;

    /// One round of the agent's own work at tick `now`, such as its bundle phase; pushes
    /// what it broadcasts onto `outbox`.
    fn act(&mut self, now: u64, outbox: &mut Vec<Self::Message>);

    /// Handles `message`, arriving at tick `now`; pushes what the agent broadcasts in
    /// response onto `outbox`.
    fn receive(&mut self, now: u64, message: &Self::Message, outbox: &mut Vec<Self::Message>);

    /// Whether `team` has settled, with `in_flight` still on its way: the agents agree on a
    /// conflict-free assignment that nothing in flight and no further round can change.
    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()
    }

    /// Runs the bundle phase and broadcasts the agent's full state, every round.
    fn act(&mut self, _now: u64, outbox: &mut Vec<cbba::Message>) {
        self.build_bundle();
        outbox.push(self.message());
    }

    /// Runs the consensus phase for `message`; CBBA answers in the next round, not now.
    fn receive(&mut self, _now: u64, message: &cbba::Message, _outbox: &mut Vec<cbba::Message>) {
        cbba::Agent::receive(self, message);
    }

    /// The team agrees on every winner, every bundle matches, no agent's bundle phase would
    /// change anything, and every message in flight carries the agreed winners. A team
    /// that has not bid yet is not settled.
    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())
    }
}

/// Message copies on their way.
type Copies<M> = Vec<InFlight<M>>;

/// A message copy on its way to one agent.
#[derive(Clone, Debug)]
struct InFlight<M> {
    /// The tick at which the copy arrives.
    arrives: u64,

    /// Sending order, to deliver copies arriving in the same tick deterministically.
    order: u64,

    /// The receiver.
    to: AgentId,

    /// The message, shared by all copies of one broadcast.
    message: Rc<M>,
}

/// A team of agents on a simulated network.
///
/// # Examples
///
/// ```
/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent, sim::{Network, Simulation}};
///
/// /// Values task `t` at `10 + t`, minus 3 for every task already held.
/// struct Worker;
///
/// impl Valuation<TaskId> for Worker {
///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
///         (10 + task.index() as u64).checked_sub(3 * path.len() as u64)
///     }
/// }
///
/// let agents = (0..3).map(|id| Agent::new(AgentId(id), 3, 5, 2, Worker)).collect();
/// let network = Network { seed: 7, max_delay: 3, loss_per_mille: 200, ..Network::default() };
/// let mut simulation = Simulation::new(agents, network);
///
/// let ticks = simulation.run_until_settled(500).expect("settles");
/// assert!(simulation.assignment().is_conflict_free());
/// assert!(ticks <= 500);
/// ```
#[derive(Clone, Debug)]
pub struct Simulation<A: Participant> {
    /// The team, indexed by agent.
    agents: Vec<A>,

    /// The network's behavior.
    network: Network,

    /// The source of delays and losses.
    rng: SplitMix64,

    /// The current tick: how many steps have run.
    tick: u64,

    /// Copies still on their way.
    in_flight: Copies<A::Message>,

    /// The sending order of the next copy.
    next_order: u64,

    /// Message counts so far.
    stats: Stats,
}

impl<A: Participant> Simulation<A> {
    /// A simulation of `agents` on `network`, at tick zero with nothing in flight.
    ///
    /// # Panics
    ///
    /// Panics when the agents are not identified `0..agents.len()` in order.
    #[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(),
        }
    }

    /// Runs one tick: delivers the messages due, runs every agent's round, and broadcasts
    /// what the agents put in their outboxes.
    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;
    }

    /// Steps until the team is [settled](Simulation::is_settled), at most `max_ticks` times;
    /// returns the tick at which it settled, or `None` when it did not within the limit.
    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
    }

    /// Whether the team has settled: see [`Participant::is_settled`]. Nothing changes after
    /// that.
    #[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)
    }

    /// Delivers every copy due by the current tick, in arrival order, collecting what the
    /// receivers broadcast in response in `outboxes`.
    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, &copy.message, &mut outboxes[to]);
            self.stats.delivered += 1;
        }
    }

    /// Broadcasts every message in every agent's outbox.
    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);
                }
            }
        }
    }

    /// Sends one copy of `message` from `from` to `to`, unless a partition blocks it or the
    /// network loses it.
    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;
    }

    /// Whether `a` and `b` have no direct link, or an active partition separates them now.
    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))
    }

    /// The team, indexed by agent.
    #[must_use]
    pub fn agents(&self) -> &[A] {
        &self.agents
    }

    /// The current tick: how many steps have run.
    #[must_use]
    pub const fn tick(&self) -> u64 {
        self.tick
    }

    /// Message counts so far.
    #[must_use]
    pub const fn stats(&self) -> Stats {
        self.stats
    }

    /// Every agent's bundle, as one assignment. It is conflict-free once the team is
    /// [settled](Simulation::is_settled); before, agents may still hold the same task.
    #[must_use]
    pub fn assignment(&self) -> Assignment {
        Assignment::from_bundles(
            self.agents
                .iter()
                .map(|agent| agent.bundle().clone())
                .collect(),
        )
    }
}

/// Unit tests for the simulated network.
#[cfg(test)]
mod tests;