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.
202 pub fn build_bundle(&mut self) -> usize {
203 let (bundle, claims, added) = self.rebuilt();
204 self.bundle = bundle;
205 self.claims = claims;
206
207 added
208 }
209
210 /// Whether the bundle phase would change anything now: this agent would add a task, or,
211 /// when it replans, rebuild its bundle differently.
212 ///
213 /// With [`Replan::Keep`] this looks for one winnable task. Otherwise it runs a whole
214 /// bundle phase on a copy, as costly as [`build_bundle`](Agent::build_bundle).
215 #[must_use]
216 pub fn can_bid(&self) -> bool {
217 if self.replan == Replan::Keep {
218 let id = self.id;
219 let claims = &self.claims;
220
221 return self.bundle.len() < self.capacity
222 && self
223 .bundle
224 .best_candidate(&self.valuation, &self.tasks, |task, gain| {
225 Self::wins(id, claims, *task, gain)
226 })
227 .is_some();
228 }
229
230 let (bundle, claims, _) = self.rebuilt();
231
232 bundle != self.bundle || claims != self.claims
233 }
234
235 /// The bundle and winner tables the bundle phase would produce, and how many tasks it
236 /// would add after the release.
237 fn rebuilt(&self) -> (Bundle<TaskId>, Vec<Claim>, usize) {
238 let mut bundle = self.bundle.clone();
239 let mut claims = self.claims.clone();
240 self.release_for_replan(&mut bundle, &mut claims);
241
242 let id = self.id;
243 let before = bundle.len();
244 bundle.extend_greedily(&self.valuation, &self.tasks, self.capacity, |task, gain| {
245 Self::wins(id, &claims, *task, gain)
246 });
247
248 for (task, gain) in bundle.entries().skip(before) {
249 claims[task.index()] = Claim {
250 winner: Some(id),
251 bid: gain,
252 };
253 }
254
255 let added = bundle.len() - before;
256 (bundle, claims, added)
257 }
258
259 /// Releases the tasks [`Replan`] says from `bundle`, forgetting this agent's own bids on
260 /// them in `claims`.
261 fn release_for_replan(&self, bundle: &mut Bundle<TaskId>, claims: &mut [Claim]) {
262 let keep = match self.replan {
263 Replan::Keep => return,
264 Replan::Full => 0,
265 Replan::Last(count) => bundle.len().saturating_sub(count),
266 };
267
268 for task in bundle.release_from(keep) {
269 let claim = &mut claims[task.index()];
270 if claim.winner == Some(self.id) {
271 *claim = Claim::NONE;
272 }
273 }
274 }
275
276 /// Whether agent `id`, bidding `gain` on `task`, beats the best bid in `claims`.
277 fn wins(id: AgentId, claims: &[Claim], task: TaskId, gain: u64) -> bool {
278 gain > 0
279 && Claim {
280 winner: Some(id),
281 bid: gain,
282 }
283 .outbids(claims[task.index()])
284 }
285
286 /// The message this agent broadcasts now: its winner tables and what it has seen of
287 /// every agent. Advances this agent's clock.
288 #[must_use]
289 pub fn message(&mut self) -> Message {
290 self.seen[self.id.index()] += 1;
291
292 Message {
293 sender: self.id,
294 claims: self.claims.clone(),
295 seen: self.seen.clone(),
296 }
297 }
298
299 /// The consensus phase for one message: merges `message` into this agent's winner
300 /// tables, and drops the tasks it was outbid on along with every task added after them.
301 /// Returns whether this agent's tables or bundle changed.
302 ///
303 /// Messages from this agent itself, from agents outside the team, of a different task
304 /// count, or older than what this agent has already seen of the sender are ignored.
305 pub fn receive(&mut self, message: &Message) -> bool {
306 self.receive_with_actions(message)
307 .is_some_and(|(changed, _)| changed)
308 }
309
310 /// The consensus phase for one message, as [`receive`](Agent::receive), also returning
311 /// the table's action for every task; `None` when the message is ignored.
312 pub(crate) fn receive_with_actions(
313 &mut self,
314 message: &Message,
315 ) -> Option<(bool, Vec<Action>)> {
316 if !self.accepts(message) {
317 return None;
318 }
319
320 let (mut changed, actions) = self.merge_claims(message);
321 self.merge_seen(message);
322 changed |= self.release_outbid();
323
324 Some((changed, actions))
325 }
326
327 /// Whether `message` is worth merging: from another member of the team, about the same
328 /// tasks, and not older than what this agent has seen of the sender.
329 fn accepts(&self, message: &Message) -> bool {
330 let sender = message.sender.index();
331
332 message.sender != self.id
333 && sender < self.seen.len()
334 && message.seen.len() == self.seen.len()
335 && message.claims.len() == self.claims.len()
336 && message.seen[sender] >= self.seen[sender]
337 }
338
339 /// Applies the conflict-resolution table to every task; returns whether any claim changed,
340 /// and the action taken for each task.
341 fn merge_claims(&mut self, message: &Message) -> (bool, Vec<Action>) {
342 let exchange = Exchange {
343 receiver: self.id,
344 sender: message.sender,
345 sender_seen: &message.seen,
346 receiver_seen: &self.seen,
347 };
348
349 let mut changed = false;
350 let mut actions = Vec::with_capacity(self.claims.len());
351 for (held, &sent) in self.claims.iter_mut().zip(&message.claims) {
352 let action = exchange.resolve(sent, *held);
353 let next = match action {
354 Action::Update => sent,
355 Action::Reset => Claim::NONE,
356 Action::Leave => *held,
357 };
358
359 changed |= next != *held;
360 *held = next;
361 actions.push(action);
362 }
363
364 (changed, actions)
365 }
366
367 /// Takes in the freshest clock values the sender knows of.
368 fn merge_seen(&mut self, message: &Message) {
369 for (mine, &theirs) in self.seen.iter_mut().zip(&message.seen) {
370 *mine = (*mine).max(theirs);
371 }
372 }
373
374 /// Gives up `task` and every task added after it, forgetting this agent's own bids on
375 /// all of them; returns whether `task` was in the bundle.
376 pub(crate) fn give_up(&mut self, task: TaskId) -> bool {
377 let Some(index) = self.bundle.index_of(&task) else {
378 return false;
379 };
380
381 for released in self.bundle.release_from(index) {
382 let claim = &mut self.claims[released.index()];
383 if claim.winner == Some(self.id) {
384 *claim = Claim::NONE;
385 }
386 }
387
388 true
389 }
390
391 /// Drops the first task in the bundle this agent no longer wins, and everything added
392 /// after it, forgetting its own bids on the later ones; returns whether anything was
393 /// dropped.
394 fn release_outbid(&mut self) -> bool {
395 let Some(lost) = self
396 .bundle
397 .tasks()
398 .position(|task| self.claims[task.index()].winner != Some(self.id))
399 else {
400 return false;
401 };
402
403 for task in self.bundle.release_from(lost).into_iter().skip(1) {
404 let claim = &mut self.claims[task.index()];
405 if claim.winner == Some(self.id) {
406 *claim = Claim::NONE;
407 }
408 }
409
410 true
411 }
412}
413
414impl<V> Agent<V> {
415 /// This agent's identifier.
416 #[must_use]
417 pub const fn id(&self) -> AgentId {
418 self.id
419 }
420
421 /// This agent's valuation.
422 #[must_use]
423 pub const fn valuation(&self) -> &V {
424 &self.valuation
425 }
426
427 /// The tasks this agent holds, with the bid it placed on each.
428 #[must_use]
429 pub const fn bundle(&self) -> &Bundle<TaskId> {
430 &self.bundle
431 }
432
433 /// The winner this agent believes in for `task`; `None` when it knows of no bid.
434 ///
435 /// # Panics
436 ///
437 /// Panics when `task` is not one of this agent's tasks.
438 #[must_use]
439 pub fn winner(&self, task: TaskId) -> Option<AgentId> {
440 self.claims[task.index()].winner
441 }
442
443 /// The winning bid this agent believes in for `task`; zero when it knows of no bid.
444 ///
445 /// # Panics
446 ///
447 /// Panics when `task` is not one of this agent's tasks.
448 #[must_use]
449 pub fn winning_bid(&self, task: TaskId) -> u64 {
450 self.claims[task.index()].bid
451 }
452
453 /// The winner this agent believes in for every task, in task order.
454 pub fn winners(&self) -> impl ExactSizeIterator<Item = Option<AgentId>> + '_ {
455 self.claims.iter().map(|claim| claim.winner)
456 }
457
458 /// The winner and winning bid this agent believes in for every task, in task order.
459 pub(crate) fn claims(&self) -> &[Claim] {
460 &self.claims
461 }
462
463 /// Whether this agent's bundle holds exactly the tasks it believes it wins.
464 #[must_use]
465 pub fn is_consistent(&self) -> bool {
466 let won = self
467 .claims
468 .iter()
469 .filter(|claim| claim.winner == Some(self.id))
470 .count();
471
472 won == self.bundle.len()
473 && self
474 .bundle
475 .tasks()
476 .all(|task| self.claims[task.index()].winner == Some(self.id))
477 }
478}
479
480/// Unit tests for [`Agent`].
481#[cfg(test)]
482mod tests;