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//!
60//! A running team can change: [`Agent::add_task`] adds a task to every agent's tables,
61//! [`Agent::retire_task`] withdraws a done or cancelled one, and an agent that
62//! [leaves](Agent::leave) is [forgotten](Agent::forget_agent) by the others. Bundles the
63//! change does not touch stay as they are.
64//!
65//! In a frame-driven loop, such as a game's, [`Agent::with_bundle_budget`] caps the tasks one
66//! bundle phase adds, so a phase's cost fits a frame and a bundle fills over several rounds.
67//! Without replanning, the bundle and consensus phases do not allocate once the bundle has
68//! reached its capacity before, including when the agent is outbid; only building a
69//! [`Message`] does.
70
71mod dynamic;
72mod message;
73pub(crate) mod table;
74
75pub use message::Message;
76
77use alloc::vec;
78use alloc::vec::Vec;
79
80use crate::bundle::Bundle;
81use crate::id::{AgentId, TaskId};
82use crate::valuation::Valuation;
83pub(crate) use table::Action;
84use table::{Claim, Exchange};
85
86/// One CBBA agent: its valuation, its bundle, and what it knows about every task's winner.
87///
88/// # Examples
89///
90/// Two agents that can each take one task, exchanging messages directly:
91///
92/// ```
93/// use task_allocation::{AgentId, TaskId, Valuation, cbba::Agent};
94///
95/// /// Values the two tasks at fixed rewards, for at most one task.
96/// struct Single([u64; 2]);
97///
98/// impl Valuation<TaskId> for Single {
99///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
100///         path.is_empty().then_some(self.0[task.index()])
101///     }
102/// }
103///
104/// let mut a = Agent::new(AgentId(0), 2, 2, 1, Single([5, 4]));
105/// let mut b = Agent::new(AgentId(1), 2, 2, 1, Single([6, 1]));
106///
107/// for _ in 0..3 {
108///     a.build_bundle();
109///     b.build_bundle();
110///     let (to_b, to_a) = (a.message(), b.message());
111///     b.receive(&to_b);
112///     a.receive(&to_a);
113/// }
114///
115/// assert_eq!(a.bundle().path(), [TaskId(1)]);
116/// assert_eq!(b.bundle().path(), [TaskId(0)]);
117/// assert_eq!(a.winner(TaskId(0)), Some(AgentId(1)));
118/// ```
119#[derive(Clone, Debug)]
120pub struct Agent<V> {
121    /// This agent's identifier.
122    id: AgentId,
123
124    /// How this agent values tasks.
125    valuation: V,
126
127    /// The most tasks this agent holds at once.
128    capacity: usize,
129
130    /// The tasks this agent holds, with the bid it placed on each.
131    bundle: Bundle<TaskId>,
132
133    /// For each task, the winner and winning bid this agent believes in.
134    claims: Vec<Claim>,
135
136    /// For each agent, the latest clock value of it this agent has seen, directly or
137    /// relayed. The entry for this agent is its own clock: the number of messages it sent.
138    seen: Vec<u64>,
139
140    /// Every task identifier, in order: the candidates of the bundle phase.
141    tasks: Vec<TaskId>,
142
143    /// How much of its bundle this agent releases before each bundle phase.
144    replan: Replan,
145
146    /// The most tasks one bundle phase adds; `None` for no limit.
147    budget: Option<usize>,
148
149    /// For each agent, whether this agent has been told it left the team; its claims are
150    /// void and its messages ignored.
151    departed: Vec<bool>,
152
153    /// For each task, whether it was retired: done or cancelled, never bid on again.
154    retired: Vec<bool>,
155
156    /// Whether this agent itself left the team: it holds nothing and stays silent.
157    left: bool,
158}
159
160/// How much of its bundle an agent releases before each bundle phase, to reconsider it.
161///
162/// With [`Replan::Keep`], an agent only ever adds to its bundle, so a slot it filled while
163/// a since-withdrawn bid blocked a better task stays filled. Releasing the bundle and
164/// rebuilding it against the current winners frees such slots. With diminishing marginal
165/// gains and every task known from the start, the team then settles on the
166/// [sequential greedy assignment](crate::centralized::sequential_greedy), up to the order of
167/// tied gains (Buckman, Choi and How, "Partial Replanning for Decentralized Dynamic Task
168/// Allocation", AIAA `SciTech` 2019, <https://arxiv.org/abs/1806.04836>).
169///
170/// Releasing only the tasks added last trades that coordination for fewer bundle changes
171/// per round, and fewer valuation calls.
172#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
173pub enum Replan {
174    /// Keep the bundle and only add to it: CBBA as published in 2009.
175    #[default]
176    Keep,
177
178    /// Release the whole bundle and rebuild it from scratch.
179    Full,
180
181    /// Release the given number of tasks added last, which under diminishing gains carry
182    /// the lowest bids, and rebuild from there.
183    Last(usize),
184}
185
186impl<V: Valuation<TaskId>> Agent<V> {
187    /// Agent `id` of a team of `agents`, bidding on tasks `0..tasks` and holding at most
188    /// `capacity` of them.
189    ///
190    /// # Panics
191    ///
192    /// Panics when `id` is not below `agents`.
193    #[must_use]
194    pub fn new(id: AgentId, agents: usize, tasks: usize, capacity: usize, valuation: V) -> Self {
195        assert!(
196            id.index() < agents,
197            "{id} is not part of a team of {agents} agents"
198        );
199
200        Self {
201            id,
202            valuation,
203            capacity,
204            bundle: Bundle::new(),
205            claims: vec![Claim::NONE; tasks],
206            seen: vec![0; agents],
207            tasks: (0..tasks).map(TaskId).collect(),
208            replan: Replan::Keep,
209            budget: None,
210            departed: vec![false; agents],
211            retired: vec![false; tasks],
212            left: false,
213        }
214    }
215
216    /// This agent, releasing part of its bundle before every bundle phase as `replan` says.
217    ///
218    /// The default, [`Replan::Keep`], is CBBA as published in 2009.
219    ///
220    /// # Panics
221    ///
222    /// Panics when a [bundle budget](Agent::with_bundle_budget) below the capacity is set and
223    /// `replan` releases as much per phase as the budget re-adds, or more: [`Replan::Full`],
224    /// or [`Replan::Last`] of the budget or more.
225    #[must_use]
226    pub const fn with_replan(mut self, replan: Replan) -> Self {
227        assert!(
228            budget_fits(replan, self.budget, self.capacity),
229            "a bundle budget below the capacity cannot re-add what this replan releases"
230        );
231        self.replan = replan;
232        self
233    }
234
235    /// This agent, adding at most `additions` tasks per bundle phase, so that the phase's
236    /// work fits a frame: each added task costs one pass over every task the agent can still
237    /// win. A bundle then fills over several rounds, and the team keeps negotiating meanwhile.
238    ///
239    /// The limit counts tasks added after the release. A budget below the capacity
240    /// therefore only works with [`Replan::Keep`], or with [`Replan::Last`] of fewer than
241    /// `additions`: a replan that releases as many or more would stop the bundle from growing
242    /// for good, while the team counts as settled.
243    ///
244    /// # Panics
245    ///
246    /// Panics when `additions` is zero, since the agent could never bid, and when it is below
247    /// the capacity while the agent replans as much as it allows or more ([`Replan::Full`],
248    /// or [`Replan::Last`] of `additions` or more).
249    #[must_use]
250    pub fn with_bundle_budget(mut self, additions: usize) -> Self {
251        assert!(
252            additions > 0,
253            "a bundle phase must be allowed to add a task"
254        );
255        assert!(
256            budget_fits(self.replan, Some(additions), self.capacity),
257            "a bundle budget below the capacity cannot re-add what this replan releases"
258        );
259        self.budget = Some(additions);
260        self
261    }
262
263    /// The bundle phase: releases what [`Replan`] says, then adds the most valuable tasks
264    /// this agent can win until its bundle is full or nothing is left to win; returns the
265    /// number of tasks added after the release.
266    ///
267    /// Each added task's bid is its marginal gain, and this agent becomes its winner in its
268    /// own tables. With [`Replan::Keep`], the bundle grows in place, without allocating once
269    /// the bundle has reached its capacity before.
270    pub fn build_bundle(&mut self) -> usize {
271        if self.replan == Replan::Keep {
272            let limit = self.limit(self.bundle.len());
273            let Self {
274                id,
275                valuation,
276                bundle,
277                claims,
278                tasks,
279                ..
280            } = self;
281
282            return extend_and_claim(*id, valuation, tasks, limit, bundle, claims);
283        }
284
285        let (bundle, claims, added) = self.rebuilt();
286        self.bundle = bundle;
287        self.claims = claims;
288
289        added
290    }
291
292    /// Whether the bundle phase would change anything now: this agent would add a task, or,
293    /// when it replans, rebuild its bundle differently.
294    ///
295    /// With [`Replan::Keep`] this looks for one winnable task. Otherwise it runs a whole
296    /// bundle phase on a copy, as costly as [`build_bundle`](Agent::build_bundle).
297    #[must_use]
298    pub fn can_bid(&self) -> bool {
299        if self.replan == Replan::Keep {
300            let id = self.id;
301            let claims = &self.claims;
302
303            return self.bundle.len() < self.capacity
304                && self
305                    .bundle
306                    .best_candidate(&self.valuation, &self.tasks, |task, gain| {
307                        Self::wins(id, claims, *task, gain)
308                    })
309                    .is_some();
310        }
311
312        let (bundle, claims, _) = self.rebuilt();
313
314        bundle != self.bundle || claims != self.claims
315    }
316
317    /// The bundle and winner tables the bundle phase would produce, and how many tasks it
318    /// would add after the release.
319    fn rebuilt(&self) -> (Bundle<TaskId>, Vec<Claim>, usize) {
320        let mut bundle = self.bundle.clone();
321        let mut claims = self.claims.clone();
322        self.release_for_replan(&mut bundle, &mut claims);
323
324        let added = extend_and_claim(
325            self.id,
326            &self.valuation,
327            &self.tasks,
328            self.limit(bundle.len()),
329            &mut bundle,
330            &mut claims,
331        );
332
333        (bundle, claims, added)
334    }
335
336    /// The bundle size this bundle phase may reach, starting from `held` tasks: the
337    /// capacity, or fewer when the budget allows fewer additions.
338    fn limit(&self, held: usize) -> usize {
339        self.budget.map_or(self.capacity, |additions| {
340            self.capacity.min(held.saturating_add(additions))
341        })
342    }
343
344    /// Releases the tasks [`Replan`] says from `bundle`, forgetting this agent's own bids on
345    /// them in `claims`.
346    fn release_for_replan(&self, bundle: &mut Bundle<TaskId>, claims: &mut [Claim]) {
347        let keep = match self.replan {
348            Replan::Keep => return,
349            Replan::Full => 0,
350            Replan::Last(count) => bundle.len().saturating_sub(count),
351        };
352
353        for task in bundle.release_from(keep) {
354            let claim = &mut claims[task.index()];
355            if claim.winner == Some(self.id) {
356                *claim = Claim::NONE;
357            }
358        }
359    }
360
361    /// Whether agent `id`, bidding `gain` on `task`, beats the best bid in `claims`.
362    fn wins(id: AgentId, claims: &[Claim], task: TaskId, gain: u64) -> bool {
363        gain > 0
364            && Claim {
365                winner: Some(id),
366                bid: gain,
367            }
368            .outbids(claims[task.index()])
369    }
370
371    /// The message this agent broadcasts now: its winner tables and what it has seen of
372    /// every agent. Advances this agent's clock.
373    #[must_use]
374    pub fn message(&mut self) -> Message {
375        self.seen[self.id.index()] += 1;
376
377        Message {
378            sender: self.id,
379            claims: self.claims.clone(),
380            seen: self.seen.clone(),
381        }
382    }
383
384    /// The consensus phase for one message: merges `message` into this agent's winner
385    /// tables, and drops the tasks it was outbid on along with every task added after them.
386    /// Returns whether this agent's tables or bundle changed.
387    ///
388    /// Messages from this agent itself, from agents outside the team or [departed](Agent::forget_agent),
389    /// or older than what this agent has already seen of the sender are ignored. A message
390    /// about fewer or more tasks than this agent knows is merged over the tasks both know.
391    pub fn receive(&mut self, message: &Message) -> bool {
392        self.receive_with_actions(message, |_, _| {})
393            .unwrap_or(false)
394    }
395
396    /// The consensus phase for one message, as [`receive`](Agent::receive), also reporting
397    /// the table's action for every task to `on_action`; `None` when the message is ignored.
398    pub(crate) fn receive_with_actions(
399        &mut self,
400        message: &Message,
401        on_action: impl FnMut(TaskId, Action),
402    ) -> Option<bool> {
403        if !self.accepts(message) {
404            return None;
405        }
406
407        let mut changed = self.merge_claims(message, on_action);
408        self.merge_seen(message);
409        changed |= self.release_outbid();
410
411        Some(changed)
412    }
413
414    /// Whether `message` is worth merging: from another member of the team, about the same
415    /// tasks, and not older than what this agent has seen of the sender.
416    fn accepts(&self, message: &Message) -> bool {
417        let sender = message.sender.index();
418
419        message.sender != self.id
420            && sender < self.seen.len()
421            && !self.departed[sender]
422            && message.seen.len() == self.seen.len()
423            && message.seen[sender] >= self.seen[sender]
424    }
425
426    /// Applies the conflict-resolution table to every task both sides know, reporting each
427    /// action to `on_action`; returns whether any claim changed. Claims of retired tasks and
428    /// of departed agents are voided, however they arrive.
429    fn merge_claims(
430        &mut self,
431        message: &Message,
432        mut on_action: impl FnMut(TaskId, Action),
433    ) -> bool {
434        let exchange = Exchange {
435            receiver: self.id,
436            sender: message.sender,
437            sender_seen: &message.seen,
438            receiver_seen: &self.seen,
439        };
440
441        let (departed, retired) = (&self.departed, &self.retired);
442        let mut changed = false;
443        for (index, (held, &sent)) in self.claims.iter_mut().zip(&message.claims).enumerate() {
444            let action = exchange.resolve(sent, *held);
445            let next = match action {
446                Action::Update => sent,
447                Action::Reset => Claim::NONE,
448                Action::Leave => *held,
449            };
450            let void = retired[index] || next.winner.is_some_and(|winner| departed[winner.index()]);
451            let next = if void { Claim::NONE } else { next };
452
453            changed |= next != *held;
454            *held = next;
455            on_action(TaskId(index), action);
456        }
457
458        changed
459    }
460
461    /// Takes in the freshest clock values the sender knows of.
462    fn merge_seen(&mut self, message: &Message) {
463        for (mine, &theirs) in self.seen.iter_mut().zip(&message.seen) {
464            *mine = (*mine).max(theirs);
465        }
466    }
467
468    /// Gives up `task` and every task added after it, forgetting this agent's own bids on
469    /// all of them; returns whether `task` was in the bundle.
470    pub(crate) fn give_up(&mut self, task: TaskId) -> bool {
471        let Some(index) = self.bundle.index_of(&task) else {
472            return false;
473        };
474
475        self.release_own(index);
476
477        true
478    }
479
480    /// Releases every task added at bundle index `index` or later, forgetting this agent's
481    /// own bids on them, without allocating.
482    fn release_own(&mut self, index: usize) {
483        let Self {
484            id, bundle, claims, ..
485        } = self;
486
487        bundle.release_from_with(index, |task| {
488            let claim = &mut claims[task.index()];
489            if claim.winner == Some(*id) {
490                *claim = Claim::NONE;
491            }
492        });
493    }
494
495    /// Drops the first task in the bundle this agent no longer wins, and everything added
496    /// after it, forgetting its own bids on the later ones; returns whether anything was
497    /// dropped.
498    fn release_outbid(&mut self) -> bool {
499        let Some(lost) = self
500            .bundle
501            .tasks()
502            .position(|task| self.claims[task.index()].winner != Some(self.id))
503        else {
504            return false;
505        };
506
507        // The lost task already names another winner, so only the later ones are forgotten.
508        self.release_own(lost);
509
510        true
511    }
512}
513
514/// Whether a bundle `budget` lets every bundle phase add more than `replan` releases, so
515/// that bundles can still reach `capacity`.
516const fn budget_fits(replan: Replan, budget: Option<usize>, capacity: usize) -> bool {
517    let Some(budget) = budget else {
518        return true;
519    };
520
521    budget >= capacity
522        || match replan {
523            Replan::Keep => true,
524            Replan::Full => false,
525            Replan::Last(released) => released < budget,
526        }
527}
528
529/// Extends `bundle` greedily with the tasks agent `id` can win against `claims`, up to
530/// `capacity`, and records the agent as the winner of each added task, at its gain; returns
531/// the number of tasks added.
532fn extend_and_claim<V: Valuation<TaskId>>(
533    id: AgentId,
534    valuation: &V,
535    tasks: &[TaskId],
536    capacity: usize,
537    bundle: &mut Bundle<TaskId>,
538    claims: &mut [Claim],
539) -> usize {
540    let before = bundle.len();
541    bundle.extend_greedily(valuation, tasks, capacity, |task, gain| {
542        Agent::<V>::wins(id, claims, *task, gain)
543    });
544
545    for (task, gain) in bundle.entries().skip(before) {
546        claims[task.index()] = Claim {
547            winner: Some(id),
548            bid: gain,
549        };
550    }
551
552    bundle.len() - before
553}
554
555impl<V> Agent<V> {
556    /// This agent's identifier.
557    #[must_use]
558    pub const fn id(&self) -> AgentId {
559        self.id
560    }
561
562    /// This agent's valuation.
563    #[must_use]
564    pub const fn valuation(&self) -> &V {
565        &self.valuation
566    }
567
568    /// The tasks this agent holds, with the bid it placed on each.
569    #[must_use]
570    pub const fn bundle(&self) -> &Bundle<TaskId> {
571        &self.bundle
572    }
573
574    /// The winner this agent believes in for `task`; `None` when it knows of no bid.
575    ///
576    /// # Panics
577    ///
578    /// Panics when `task` is not one of this agent's tasks.
579    #[must_use]
580    pub fn winner(&self, task: TaskId) -> Option<AgentId> {
581        self.claims[task.index()].winner
582    }
583
584    /// The winning bid this agent believes in for `task`; zero when it knows of no bid.
585    ///
586    /// # Panics
587    ///
588    /// Panics when `task` is not one of this agent's tasks.
589    #[must_use]
590    pub fn winning_bid(&self, task: TaskId) -> u64 {
591        self.claims[task.index()].bid
592    }
593
594    /// The winner this agent believes in for every task, in task order.
595    pub fn winners(&self) -> impl ExactSizeIterator<Item = Option<AgentId>> + '_ {
596        self.claims.iter().map(|claim| claim.winner)
597    }
598
599    /// The winner and winning bid this agent believes in for every task, in task order.
600    pub(crate) fn claims(&self) -> &[Claim] {
601        &self.claims
602    }
603
604    /// Whether this agent's bundle holds exactly the tasks it believes it wins.
605    #[must_use]
606    pub fn is_consistent(&self) -> bool {
607        let won = self
608            .claims
609            .iter()
610            .filter(|claim| claim.winner == Some(self.id))
611            .count();
612
613        won == self.bundle.len()
614            && self
615                .bundle
616                .tasks()
617                .all(|task| self.claims[task.index()].winner == Some(self.id))
618    }
619}
620
621/// Unit tests for [`Agent`].
622#[cfg(test)]
623mod tests;