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