Skip to main content

task_allocation/
cbba.rs

1//! The consensus-based bundle algorithm (CBBA).
2//!
3//! Each agent alternates two phases, communicating only with whoever it can currently reach:
4//!
5//! 1. **Bundle phase** ([`Agent::build_bundle`]): the agent greedily adds tasks to its
6//!    bundle, each time the one with the highest marginal gain it can win, bidding that gain.
7//!    It can win a task when its bid beats the best bid it knows of: higher, or equal and
8//!    placed by an agent with a larger identifier.
9//! 2. **Consensus phase** ([`Agent::receive`]): the agent merges a neighbor's [`Message`]
10//!    into its own winner tables, task by task, with the published conflict-resolution table.
11//!    When it learns it was outbid on a task in its bundle, it drops that task and every task
12//!    it added after it, since their bids assumed the lost task.
13//!
14//! Messages carry the sender's whole state, so they can be delayed, dropped, duplicated or
15//! reordered, and the topology can change: an agent ignores a message older than what it
16//! already knows of the sender, and later messages repair what an earlier one got wrong.
17//!
18//! With [diminishing marginal gains](crate::check_diminishing), once every pair of agents
19//! keeps getting messages through, directly or relayed, the team settles on an assignment
20//! where:
21//!
22//! - every agent believes in the same winner for every task, and no task has two holders;
23//! - every winning bid is the holder's real marginal gain, given the tasks it added before;
24//! - no agent with room left could outbid the winner of a task it does not hold.
25//!
26//! The literature states that, with diminishing gains, CBBA settles on the
27//! [sequential greedy assignment](crate::centralized::sequential_greedy) (Choi, Brunet and
28//! How, as restated by Buckman, Choi and How, 2019). With this implementation that often
29//! holds, but not always: an agent outbid by a bid that is later withdrawn may already have
30//! filled the slot with another task, and keeps it; and equal gains can be resolved in a
31//! different order. The tests pin both cases, the first with a step-by-step trace. Agents
32//! that [replan](Replan::Full), releasing their bundle before every bundle phase, free such
33//! slots, and settle on a sequential greedy assignment for some order of tied gains.
34//!
35//! The algorithm is from Choi, Brunet and How, "Consensus-Based Decentralized Auctions for
36//! Robust Task Allocation", IEEE Transactions on Robotics 25(4), 2009. Its state and release
37//! rule follow the restatement in Section II.B of Johnson, Ponda, Choi and How,
38//! "Asynchronous Decentralized Task Allocation for Dynamic Environments", AIAA
39//! Infotech@Aerospace 2011, and its conflict table was checked entry by entry against the
40//! open-source CBBA-Python implementation (<https://github.com/zehuilu/CBBA-Python>). Timestamps here are
41//! logical clocks: every agent counts the messages it sends, and agents track the latest count
42//! they have seen of each other agent, directly or relayed. No synchronized clocks are needed.
43//!
44//! ```mermaid
45//! sequenceDiagram
46//!     participant A as agent 0
47//!     participant B as agent 1
48//!     A->>A: build_bundle
49//!     B->>B: build_bundle
50//!     A->>B: message
51//!     B->>A: message
52//!     A->>A: receive, release outbid tasks
53//!     B->>B: receive, release outbid tasks
54//!     A->>A: build_bundle
55//! ```
56//!
57//! [`sim`](crate::sim) runs a team over a simulated network with delays, losses and
58//! partitions.
59
60mod message;
61pub(crate) mod table;
62
63pub use message::Message;
64
65use alloc::vec;
66use alloc::vec::Vec;
67
68use crate::bundle::Bundle;
69use crate::id::{AgentId, TaskId};
70use crate::valuation::Valuation;
71pub(crate) use table::Action;
72use table::{Claim, Exchange};
73
74/// One CBBA agent: its valuation, its bundle, and what it knows about every task's winner.
75///
76/// # Examples
77///
78/// Two agents that can each take one task, exchanging messages directly:
79///
80/// ```
81/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent};
82///
83/// /// Values the two tasks at fixed rewards, for at most one task.
84/// struct Single([u64; 2]);
85///
86/// impl Valuation<TaskId> for Single {
87///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
88///         path.is_empty().then_some(self.0[task.index()])
89///     }
90/// }
91///
92/// let mut a = Agent::new(AgentId(0), 2, 2, 1, Single([5, 4]));
93/// let mut b = Agent::new(AgentId(1), 2, 2, 1, Single([6, 1]));
94///
95/// for _ in 0..3 {
96///     a.build_bundle();
97///     b.build_bundle();
98///     let (to_b, to_a) = (a.message(), b.message());
99///     b.receive(&to_b);
100///     a.receive(&to_a);
101/// }
102///
103/// assert_eq!(a.bundle().path(), [TaskId(1)]);
104/// assert_eq!(b.bundle().path(), [TaskId(0)]);
105/// assert_eq!(a.winner(TaskId(0)), Some(AgentId(1)));
106/// ```
107#[derive(Clone, Debug)]
108pub struct Agent<V> {
109    /// This agent's identifier.
110    id: AgentId,
111
112    /// How this agent values tasks.
113    valuation: V,
114
115    /// The most tasks this agent holds at once.
116    capacity: usize,
117
118    /// The tasks this agent holds, with the bid it placed on each.
119    bundle: Bundle<TaskId>,
120
121    /// For each task, the winner and winning bid this agent believes in.
122    claims: Vec<Claim>,
123
124    /// For each agent, the latest clock value of it this agent has seen, directly or
125    /// relayed. The entry for this agent is its own clock: the number of messages it sent.
126    seen: Vec<u64>,
127
128    /// Every task identifier, in order: the candidates of the bundle phase.
129    tasks: Vec<TaskId>,
130
131    /// How much of its bundle this agent releases before each bundle phase.
132    replan: Replan,
133}
134
135/// How much of its bundle an agent releases before each bundle phase, to reconsider it.
136///
137/// With [`Replan::Keep`], an agent only ever adds to its bundle, so a slot it filled while
138/// a since-withdrawn bid blocked a better task stays filled. Releasing the bundle and
139/// rebuilding it against the current winners frees such slots. With diminishing marginal
140/// gains and every task known from the start, the team then settles on the
141/// [sequential greedy assignment](crate::centralized::sequential_greedy), up to the order of
142/// tied gains (Buckman, Choi and How, "Partial Replanning for Decentralized Dynamic Task
143/// Allocation", AIAA `SciTech` 2019, <https://arxiv.org/abs/1806.04836>).
144///
145/// Releasing only the tasks added last trades that coordination for fewer bundle changes
146/// per round, and fewer valuation calls.
147#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
148pub enum Replan {
149    /// Keep the bundle and only add to it: CBBA as published in 2009.
150    #[default]
151    Keep,
152
153    /// Release the whole bundle and rebuild it from scratch.
154    Full,
155
156    /// Release the given number of tasks added last, which under diminishing gains carry
157    /// the lowest bids, and rebuild from there.
158    Last(usize),
159}
160
161impl<V: Valuation<TaskId>> Agent<V> {
162    /// Agent `id` of a team of `agents`, bidding on tasks `0..tasks` and holding at most
163    /// `capacity` of them.
164    ///
165    /// # Panics
166    ///
167    /// Panics when `id` is not below `agents`.
168    #[must_use]
169    pub fn new(id: AgentId, agents: usize, tasks: usize, capacity: usize, valuation: V) -> Self {
170        assert!(
171            id.index() < agents,
172            "{id} is not part of a team of {agents} agents"
173        );
174
175        Self {
176            id,
177            valuation,
178            capacity,
179            bundle: Bundle::new(),
180            claims: vec![Claim::NONE; tasks],
181            seen: vec![0; agents],
182            tasks: (0..tasks).map(TaskId).collect(),
183            replan: Replan::Keep,
184        }
185    }
186
187    /// This agent, releasing part of its bundle before every bundle phase as `replan` says.
188    ///
189    /// The default, [`Replan::Keep`], is CBBA as published in 2009.
190    #[must_use]
191    pub const fn with_replan(mut self, replan: Replan) -> Self {
192        self.replan = replan;
193        self
194    }
195
196    /// The bundle phase: releases what [`Replan`] says, then adds the most valuable tasks
197    /// this agent can win until its bundle is full or nothing is left to win; returns the
198    /// number of tasks added after the release.
199    ///
200    /// Each added task's bid is its marginal gain, and this agent becomes its winner in its
201    /// own tables. With [`Replan::Keep`], the bundle grows in place, without allocating once
202    /// the bundle has reached its capacity before.
203    pub fn build_bundle(&mut self) -> usize {
204        if self.replan == Replan::Keep {
205            let Self {
206                id,
207                valuation,
208                capacity,
209                bundle,
210                claims,
211                tasks,
212                ..
213            } = self;
214
215            return extend_and_claim(*id, valuation, tasks, *capacity, bundle, claims);
216        }
217
218        let (bundle, claims, added) = self.rebuilt();
219        self.bundle = bundle;
220        self.claims = claims;
221
222        added
223    }
224
225    /// Whether the bundle phase would change anything now: this agent would add a task, or,
226    /// when it replans, rebuild its bundle differently.
227    ///
228    /// With [`Replan::Keep`] this looks for one winnable task. Otherwise it runs a whole
229    /// bundle phase on a copy, as costly as [`build_bundle`](Agent::build_bundle).
230    #[must_use]
231    pub fn can_bid(&self) -> bool {
232        if self.replan == Replan::Keep {
233            let id = self.id;
234            let claims = &self.claims;
235
236            return self.bundle.len() < self.capacity
237                && self
238                    .bundle
239                    .best_candidate(&self.valuation, &self.tasks, |task, gain| {
240                        Self::wins(id, claims, *task, gain)
241                    })
242                    .is_some();
243        }
244
245        let (bundle, claims, _) = self.rebuilt();
246
247        bundle != self.bundle || claims != self.claims
248    }
249
250    /// The bundle and winner tables the bundle phase would produce, and how many tasks it
251    /// would add after the release.
252    fn rebuilt(&self) -> (Bundle<TaskId>, Vec<Claim>, usize) {
253        let mut bundle = self.bundle.clone();
254        let mut claims = self.claims.clone();
255        self.release_for_replan(&mut bundle, &mut claims);
256
257        let added = extend_and_claim(
258            self.id,
259            &self.valuation,
260            &self.tasks,
261            self.capacity,
262            &mut bundle,
263            &mut claims,
264        );
265
266        (bundle, claims, added)
267    }
268
269    /// Releases the tasks [`Replan`] says from `bundle`, forgetting this agent's own bids on
270    /// them in `claims`.
271    fn release_for_replan(&self, bundle: &mut Bundle<TaskId>, claims: &mut [Claim]) {
272        let keep = match self.replan {
273            Replan::Keep => return,
274            Replan::Full => 0,
275            Replan::Last(count) => bundle.len().saturating_sub(count),
276        };
277
278        for task in bundle.release_from(keep) {
279            let claim = &mut claims[task.index()];
280            if claim.winner == Some(self.id) {
281                *claim = Claim::NONE;
282            }
283        }
284    }
285
286    /// Whether agent `id`, bidding `gain` on `task`, beats the best bid in `claims`.
287    fn wins(id: AgentId, claims: &[Claim], task: TaskId, gain: u64) -> bool {
288        gain > 0
289            && Claim {
290                winner: Some(id),
291                bid: gain,
292            }
293            .outbids(claims[task.index()])
294    }
295
296    /// The message this agent broadcasts now: its winner tables and what it has seen of
297    /// every agent. Advances this agent's clock.
298    #[must_use]
299    pub fn message(&mut self) -> Message {
300        self.seen[self.id.index()] += 1;
301
302        Message {
303            sender: self.id,
304            claims: self.claims.clone(),
305            seen: self.seen.clone(),
306        }
307    }
308
309    /// The consensus phase for one message: merges `message` into this agent's winner
310    /// tables, and drops the tasks it was outbid on along with every task added after them.
311    /// Returns whether this agent's tables or bundle changed.
312    ///
313    /// Messages from this agent itself, from agents outside the team, of a different task
314    /// count, or older than what this agent has already seen of the sender are ignored.
315    pub fn receive(&mut self, message: &Message) -> bool {
316        self.receive_with_actions(message, |_, _| {})
317            .unwrap_or(false)
318    }
319
320    /// The consensus phase for one message, as [`receive`](Agent::receive), also reporting
321    /// the table's action for every task to `on_action`; `None` when the message is ignored.
322    pub(crate) fn receive_with_actions(
323        &mut self,
324        message: &Message,
325        on_action: impl FnMut(TaskId, Action),
326    ) -> Option<bool> {
327        if !self.accepts(message) {
328            return None;
329        }
330
331        let mut changed = self.merge_claims(message, on_action);
332        self.merge_seen(message);
333        changed |= self.release_outbid();
334
335        Some(changed)
336    }
337
338    /// Whether `message` is worth merging: from another member of the team, about the same
339    /// tasks, and not older than what this agent has seen of the sender.
340    fn accepts(&self, message: &Message) -> bool {
341        let sender = message.sender.index();
342
343        message.sender != self.id
344            && sender < self.seen.len()
345            && message.seen.len() == self.seen.len()
346            && message.claims.len() == self.claims.len()
347            && message.seen[sender] >= self.seen[sender]
348    }
349
350    /// Applies the conflict-resolution table to every task, reporting each action to
351    /// `on_action`; returns whether any claim changed.
352    fn merge_claims(
353        &mut self,
354        message: &Message,
355        mut on_action: impl FnMut(TaskId, Action),
356    ) -> bool {
357        let exchange = Exchange {
358            receiver: self.id,
359            sender: message.sender,
360            sender_seen: &message.seen,
361            receiver_seen: &self.seen,
362        };
363
364        let mut changed = false;
365        for (index, (held, &sent)) in self.claims.iter_mut().zip(&message.claims).enumerate() {
366            let action = exchange.resolve(sent, *held);
367            let next = match action {
368                Action::Update => sent,
369                Action::Reset => Claim::NONE,
370                Action::Leave => *held,
371            };
372
373            changed |= next != *held;
374            *held = next;
375            on_action(TaskId(index), action);
376        }
377
378        changed
379    }
380
381    /// Takes in the freshest clock values the sender knows of.
382    fn merge_seen(&mut self, message: &Message) {
383        for (mine, &theirs) in self.seen.iter_mut().zip(&message.seen) {
384            *mine = (*mine).max(theirs);
385        }
386    }
387
388    /// Gives up `task` and every task added after it, forgetting this agent's own bids on
389    /// all of them; returns whether `task` was in the bundle.
390    pub(crate) fn give_up(&mut self, task: TaskId) -> bool {
391        let Some(index) = self.bundle.index_of(&task) else {
392            return false;
393        };
394
395        for released in self.bundle.release_from(index) {
396            let claim = &mut self.claims[released.index()];
397            if claim.winner == Some(self.id) {
398                *claim = Claim::NONE;
399            }
400        }
401
402        true
403    }
404
405    /// Drops the first task in the bundle this agent no longer wins, and everything added
406    /// after it, forgetting its own bids on the later ones; returns whether anything was
407    /// dropped.
408    fn release_outbid(&mut self) -> bool {
409        let Some(lost) = self
410            .bundle
411            .tasks()
412            .position(|task| self.claims[task.index()].winner != Some(self.id))
413        else {
414            return false;
415        };
416
417        for task in self.bundle.release_from(lost).into_iter().skip(1) {
418            let claim = &mut self.claims[task.index()];
419            if claim.winner == Some(self.id) {
420                *claim = Claim::NONE;
421            }
422        }
423
424        true
425    }
426}
427
428/// Extends `bundle` greedily with the tasks agent `id` can win against `claims`, up to
429/// `capacity`, and records the agent as the winner of each added task, at its gain; returns
430/// the number of tasks added.
431fn extend_and_claim<V: Valuation<TaskId>>(
432    id: AgentId,
433    valuation: &V,
434    tasks: &[TaskId],
435    capacity: usize,
436    bundle: &mut Bundle<TaskId>,
437    claims: &mut [Claim],
438) -> usize {
439    let before = bundle.len();
440    bundle.extend_greedily(valuation, tasks, capacity, |task, gain| {
441        Agent::<V>::wins(id, claims, *task, gain)
442    });
443
444    for (task, gain) in bundle.entries().skip(before) {
445        claims[task.index()] = Claim {
446            winner: Some(id),
447            bid: gain,
448        };
449    }
450
451    bundle.len() - before
452}
453
454impl<V> Agent<V> {
455    /// This agent's identifier.
456    #[must_use]
457    pub const fn id(&self) -> AgentId {
458        self.id
459    }
460
461    /// This agent's valuation.
462    #[must_use]
463    pub const fn valuation(&self) -> &V {
464        &self.valuation
465    }
466
467    /// The tasks this agent holds, with the bid it placed on each.
468    #[must_use]
469    pub const fn bundle(&self) -> &Bundle<TaskId> {
470        &self.bundle
471    }
472
473    /// The winner this agent believes in for `task`; `None` when it knows of no bid.
474    ///
475    /// # Panics
476    ///
477    /// Panics when `task` is not one of this agent's tasks.
478    #[must_use]
479    pub fn winner(&self, task: TaskId) -> Option<AgentId> {
480        self.claims[task.index()].winner
481    }
482
483    /// The winning bid this agent believes in for `task`; zero when it knows of no bid.
484    ///
485    /// # Panics
486    ///
487    /// Panics when `task` is not one of this agent's tasks.
488    #[must_use]
489    pub fn winning_bid(&self, task: TaskId) -> u64 {
490        self.claims[task.index()].bid
491    }
492
493    /// The winner this agent believes in for every task, in task order.
494    pub fn winners(&self) -> impl ExactSizeIterator<Item = Option<AgentId>> + '_ {
495        self.claims.iter().map(|claim| claim.winner)
496    }
497
498    /// The winner and winning bid this agent believes in for every task, in task order.
499    pub(crate) fn claims(&self) -> &[Claim] {
500        &self.claims
501    }
502
503    /// Whether this agent's bundle holds exactly the tasks it believes it wins.
504    #[must_use]
505    pub fn is_consistent(&self) -> bool {
506        let won = self
507            .claims
508            .iter()
509            .filter(|claim| claim.winner == Some(self.id))
510            .count();
511
512        won == self.bundle.len()
513            && self
514                .bundle
515                .tasks()
516                .all(|task| self.claims[task.index()].winner == Some(self.id))
517    }
518}
519
520/// Unit tests for [`Agent`].
521#[cfg(test)]
522mod tests;