Skip to main content

task_allocation/
acbba.rs

1//! Asynchronous CBBA (ACBBA): agents build bundles and resolve conflicts on their own
2//! schedule, exchanging one task at a time, and only pass on what is new.
3//!
4//! **Experimental: ACBBA does not settle reliably.** None of the published decision
5//! tables settles every run, even on a network that loses nothing. With the default
6//! 2011 table, about 1 in 1,000 simulated runs on sparse networks never goes quiet, as a
7//! bid an agent has released outlives the release. For dependable results, use
8//! [`cbba`](crate::cbba), which tolerates delayed, lost and reordered messages too.
9//!
10//! Each agent keeps, for every task, the winner it believes in, the winning bid, and the time
11//! that bid was made. Its bundle phase bids as in [CBBA](crate::cbba) and announces each new
12//! bid. Every arriving [`Message`] is resolved with a deconfliction table by Johnson, Ponda,
13//! Choi and How, which also decides what to rebroadcast: the receiver's own entry, the
14//! sender's, an empty bid, or nothing. When the network has nothing new left to say, it
15//! goes quiet. The authors published three revisions of the table, which differ; an agent
16//! follows the one [`Rules`] names, by default the 2011 one from "Asynchronous
17//! Decentralized Task Allocation for Dynamic Environments" (AIAA Infotech@Aerospace 2011).
18//!
19//! Bid times come from a clock all agents share, passed in as `now`; timestamps of different
20//! agents are compared directly. [`sim`](crate::sim) uses its tick.
21//!
22//! Choices this implementation makes where the papers are silent:
23//!
24//! - The bundle phase announces each task it adds, as the agent's own entry.
25//! - An agent outbid on a task releases it and every task added after it, as in CBBA, and
26//!   announces the later ones, which it held itself, as empty bids at the current time.
27//!   Otherwise the others would keep believing it still wins them.
28//! - Rebroadcasts are batched: of everything an agent decides to send about one task in a
29//!   round, only the last message goes out. Answering every stale message one by one makes
30//!   stale information multiply: each answer reaches every neighbor and draws answers of its
31//!   own, while the winner keeps re-stamping its bid, so the network never goes quiet.
32//! - Messages are only sent in response to something new. A lost message is not repeated,
33//!   so on a lossy network the team can go quiet without agreeing. Even without losses,
34//!   a released bid that is newer than the true winner's can survive on a distant agent.
35//!   [`Agent::announce_every`] makes each agent re-announce its whole view at a fixed
36//!   interval, confirming its own winning bids with the current time.
37
38mod table;
39
40pub use table::{Claim, Rules};
41
42use alloc::vec;
43use alloc::vec::Vec;
44
45use crate::bundle::Bundle;
46use crate::id::{AgentId, TaskId};
47use crate::quiet::Quiet;
48use crate::sim::Participant;
49use crate::valuation::Valuation;
50use table::{Broadcast, Change, Exchange};
51
52/// One agent's entry for one task, broadcast to its neighbors.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub struct Message {
55    /// The agent that broadcast it: the bidder, or an agent passing it on.
56    pub sender: AgentId,
57
58    /// The task the entry is about.
59    pub task: TaskId,
60
61    /// The sender's entry for the task.
62    pub claim: Claim,
63}
64
65/// One ACBBA agent: its valuation, its bundle, and its view of every task's winner.
66///
67/// # Examples
68///
69/// ```
70/// use task_allocation::acbba::Agent;
71/// use task_allocation::sim::{Network, Simulation};
72/// use task_allocation::{AgentId, TaskId, Valuation};
73///
74/// /// Values task `t` at `10 + t` for agent 0 and `20 - t` for agent 1, minus 2 per task held.
75/// struct Skewed(u64);
76///
77/// impl Valuation<TaskId> for Skewed {
78///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
79///         let task = task.index() as u64;
80///         let base = if self.0 == 0 { 10 + task } else { 20 - task };
81///         base.checked_sub(2 * path.len() as u64)
82///     }
83/// }
84///
85/// let agents = (0..2).map(|id| Agent::new(AgentId(id), 4, 2, Skewed(id as u64))).collect();
86/// let network = Network { seed: 1, max_delay: 3, ..Network::default() };
87/// let mut simulation = Simulation::new(agents, network);
88///
89/// simulation.run_until_settled(200).expect("goes quiet in agreement");
90/// assert!(simulation.assignment().is_conflict_free());
91/// ```
92#[derive(Clone, Debug)]
93pub struct Agent<V> {
94    /// This agent's identifier.
95    id: AgentId,
96
97    /// How this agent values tasks.
98    valuation: V,
99
100    /// The most tasks this agent holds at once.
101    capacity: usize,
102
103    /// The tasks this agent holds, with the bid it placed on each.
104    bundle: Bundle<TaskId>,
105
106    /// For each task, the winner, bid and bid time this agent believes in.
107    claims: Vec<Claim>,
108
109    /// Every task identifier, in order: the candidates of the bundle phase.
110    tasks: Vec<TaskId>,
111
112    /// Times closer than this count as equal; `ε_t` in the paper.
113    epsilon: u64,
114
115    /// Re-announce the whole view every this many ticks; `None` never does.
116    announce_every: Option<u64>,
117
118    /// The decision table this agent follows.
119    rules: Rules,
120
121    /// Whether this agent breaks ties between two other winners; see
122    /// [`Agent::with_printed_ties`].
123    third_party_ties: bool,
124
125    /// How many bundle phases in a row this agent's winners and bids stayed the same; bid
126    /// times are left out, since re-announcements move them without changing anything.
127    quiet: Quiet<(Option<AgentId>, u64)>,
128}
129
130impl<V: Valuation<TaskId>> Agent<V> {
131    /// Agent `id`, bidding on tasks `0..tasks` and holding at most `capacity` of them.
132    ///
133    /// Times count as equal only when identical (`epsilon` of one tick), and the agent never
134    /// re-announces on its own.
135    #[must_use]
136    pub fn new(id: AgentId, tasks: usize, capacity: usize, valuation: V) -> Self {
137        Self {
138            id,
139            valuation,
140            capacity,
141            bundle: Bundle::new(),
142            claims: vec![Claim::NONE; tasks],
143            tasks: (0..tasks).map(TaskId).collect(),
144            epsilon: 1,
145            announce_every: None,
146            rules: Rules::default(),
147            third_party_ties: true,
148            quiet: Quiet::new(core::iter::repeat_n((None, 0), tasks)),
149        }
150    }
151
152    /// This agent, following the decision table `rules`.
153    #[must_use]
154    pub const fn with_rules(mut self, rules: Rules) -> Self {
155        self.rules = rules;
156        self
157    }
158
159    /// This agent, leaving ties between two other winners as the published tables do, in
160    /// rows 9 and 27, instead of giving them to the smaller winner. With integer scores,
161    /// two neighbors that disagree about such a tie can answer each other forever.
162    #[must_use]
163    pub const fn with_printed_ties(mut self) -> Self {
164        self.third_party_ties = false;
165        self
166    }
167
168    /// This agent, counting times closer than `epsilon` ticks as equal.
169    #[must_use]
170    pub const fn with_epsilon(mut self, epsilon: u64) -> Self {
171        self.epsilon = epsilon;
172        self
173    }
174
175    /// This agent, re-announcing its entry for every task every `period` ticks, with its own
176    /// winning bids confirmed at the current time. This is not part of the published
177    /// algorithm.
178    ///
179    /// It makes up for lost messages, and it lets the true winner of a task override a
180    /// stale claim that looks newer: under the table's time rules, a lower but newer bid
181    /// beats a higher but older one, so a bid an agent made and later released can outlive
182    /// the release on a distant agent, even without losses.
183    ///
184    /// # Panics
185    ///
186    /// Panics when `period` is zero.
187    #[must_use]
188    pub fn announce_every(mut self, period: u64) -> Self {
189        assert!(period > 0, "the announcement period must be positive");
190        self.announce_every = Some(period);
191        self
192    }
193
194    /// The bundle phase at time `now`: adds the most valuable tasks this agent can win until
195    /// its bundle is full or nothing is left to win, and returns the announcements of the
196    /// new bids.
197    ///
198    /// Each call counts as a round for [`quiet_rounds`](Agent::quiet_rounds).
199    pub fn build_bundle(&mut self, now: u64) -> Vec<Message> {
200        let announcements = self.bundle_phase(now);
201        self.quiet
202            .observe(self.claims.iter().map(|claim| (claim.winner, claim.bid)));
203
204        announcements
205    }
206
207    /// The bundle phase proper, as [`build_bundle`](Agent::build_bundle) describes it.
208    fn bundle_phase(&mut self, now: u64) -> Vec<Message> {
209        let id = self.id;
210        let claims = &self.claims;
211        let before = self.bundle.len();
212        self.bundle
213            .extend_greedily(&self.valuation, &self.tasks, self.capacity, |task, gain| {
214                wins(id, claims[task.index()], gain)
215            });
216
217        let mut announcements = Vec::new();
218        for (&task, gain) in self.bundle.entries().skip(before) {
219            let claim = Claim {
220                winner: Some(id),
221                bid: gain,
222                time: now,
223            };
224            self.claims[task.index()] = claim;
225            announcements.push(self.message(task, claim));
226        }
227
228        announcements
229    }
230
231    /// How many bundle phases in a row this agent's winners and bids stayed the same; bid
232    /// times alone do not count as a change.
233    #[must_use]
234    pub const fn quiet_rounds(&self) -> u64 {
235        self.quiet.rounds()
236    }
237
238    /// This agent's own guess that the team has settled: its winners and bids stayed the
239    /// same for at least `span` bundle phases, the *separation time* of the 2011 paper
240    /// (pp. 8–9). A heuristic that can be wrong both ways; see
241    /// [`cbba::Agent::is_locally_settled`](crate::cbba::Agent::is_locally_settled).
242    #[must_use]
243    pub const fn is_locally_settled(&self, span: u64) -> bool {
244        self.quiet.rounds() >= span
245    }
246
247    /// Whether the bundle phase would add a task now.
248    #[must_use]
249    pub fn can_bid(&self) -> bool {
250        let id = self.id;
251        let claims = &self.claims;
252
253        self.bundle.len() < self.capacity
254            && self
255                .bundle
256                .best_candidate(&self.valuation, &self.tasks, |task, gain| {
257                    wins(id, claims[task.index()], gain)
258                })
259                .is_some()
260    }
261
262    /// Resolves `message`, arriving at time `now`, and returns what to rebroadcast.
263    ///
264    /// Messages from this agent itself and about unknown tasks are ignored.
265    pub fn receive(&mut self, now: u64, message: &Message) -> Vec<Message> {
266        let task = message.task;
267        if message.sender == self.id || task.index() >= self.claims.len() {
268            return Vec::new();
269        }
270
271        let exchange = Exchange {
272            receiver: self.id,
273            sender: message.sender,
274            epsilon: self.epsilon,
275            rules: self.rules,
276            third_party_ties: self.third_party_ties,
277        };
278        let decision = exchange.decide(message.claim, self.claims[task.index()]);
279        self.apply(task, decision.change, message.claim, now);
280
281        let mut outgoing: Vec<Message> = self
282            .rebroadcast(task, decision.broadcast, message.claim, now)
283            .into_iter()
284            .collect();
285        outgoing.extend(self.release_outbid(now));
286
287        outgoing
288    }
289
290    /// Changes this agent's entry for `task` as decided.
291    fn apply(&mut self, task: TaskId, change: Change, sent: Claim, now: u64) {
292        let held = &mut self.claims[task.index()];
293        match change {
294            Change::Update => *held = sent,
295            Change::UpdateTime => held.time = now,
296            Change::UpdatePast => {
297                let time = if sent.time > held.time {
298                    sent.time
299                } else {
300                    held.time + self.epsilon
301                };
302                *held = Claim { time, ..sent };
303            }
304            Change::KeepPast => {
305                if held.time <= sent.time {
306                    held.time = sent.time + self.epsilon;
307                }
308            }
309            Change::Reset => {
310                *held = match self.rules {
311                    Rules::Gnc2010 => Claim::NONE,
312                    Rules::Infotech2011 | Rules::Thesis2012 => Claim::empty_at(now),
313                }
314            }
315            Change::Leave => {}
316        }
317    }
318
319    /// The message to rebroadcast about `task`, if any.
320    fn rebroadcast(
321        &self,
322        task: TaskId,
323        broadcast: Broadcast,
324        sent: Claim,
325        now: u64,
326    ) -> Option<Message> {
327        let claim = match broadcast {
328            Broadcast::Nothing => return None,
329            Broadcast::Own => self.claims[task.index()],
330            Broadcast::Sender => sent,
331            Broadcast::EmptyNow => Claim::empty_at(now),
332        };
333
334        Some(self.message(task, claim))
335    }
336
337    /// Drops the first task in the bundle this agent no longer wins, and everything added
338    /// after it; returns empty bids at `now` for the later tasks it held itself.
339    fn release_outbid(&mut self, now: u64) -> Vec<Message> {
340        let Some(lost) = self
341            .bundle
342            .tasks()
343            .position(|task| self.claims[task.index()].winner != Some(self.id))
344        else {
345            return Vec::new();
346        };
347
348        let mut announcements = Vec::new();
349        for task in self.bundle.release_from(lost).into_iter().skip(1) {
350            if self.claims[task.index()].winner == Some(self.id) {
351                let empty = Claim::empty_at(now);
352                self.claims[task.index()] = empty;
353                announcements.push(self.message(task, empty));
354            }
355        }
356
357        announcements
358    }
359
360    /// This agent's entry for every task, as messages, after confirming its own winning
361    /// bids with the current time, as "update time" in the table does.
362    fn announce_all(&mut self, now: u64) -> Vec<Message> {
363        for claim in &mut self.claims {
364            if claim.winner == Some(self.id) {
365                claim.time = now;
366            }
367        }
368
369        self.tasks
370            .iter()
371            .map(|&task| self.message(task, self.claims[task.index()]))
372            .collect()
373    }
374}
375
376impl<V> Agent<V> {
377    /// This agent's identifier.
378    #[must_use]
379    pub const fn id(&self) -> AgentId {
380        self.id
381    }
382
383    /// This agent's valuation.
384    #[must_use]
385    pub const fn valuation(&self) -> &V {
386        &self.valuation
387    }
388
389    /// The tasks this agent holds, with the bid it placed on each.
390    #[must_use]
391    pub const fn bundle(&self) -> &Bundle<TaskId> {
392        &self.bundle
393    }
394
395    /// This agent's entry for `task`.
396    ///
397    /// # Panics
398    ///
399    /// Panics when `task` is not one of this agent's tasks.
400    #[must_use]
401    pub fn claim(&self, task: TaskId) -> Claim {
402        self.claims[task.index()]
403    }
404
405    /// Whether this agent's bundle holds exactly the tasks it believes it wins.
406    #[must_use]
407    pub fn is_consistent(&self) -> bool {
408        let won = self
409            .claims
410            .iter()
411            .filter(|claim| claim.winner == Some(self.id))
412            .count();
413
414        won == self.bundle.len()
415            && self
416                .bundle
417                .tasks()
418                .all(|task| self.claims[task.index()].winner == Some(self.id))
419    }
420
421    /// A message from this agent about `task`.
422    const fn message(&self, task: TaskId, claim: Claim) -> Message {
423        Message {
424            sender: self.id,
425            task,
426            claim,
427        }
428    }
429}
430
431/// Keeps only the last message about each task in `outbox`, in their original order.
432fn keep_last_per_task(outbox: &mut Vec<Message>) {
433    let mut seen: Vec<TaskId> = Vec::with_capacity(outbox.len());
434    let mut kept: Vec<Message> = Vec::with_capacity(outbox.len());
435    for message in outbox.drain(..).rev() {
436        if !seen.contains(&message.task) {
437            seen.push(message.task);
438            kept.push(message);
439        }
440    }
441
442    kept.reverse();
443    *outbox = kept;
444}
445
446/// Whether agent `id`, bidding `gain`, beats `claim`: a positive bid that is higher, or equal
447/// and placed by a smaller agent.
448fn wins(id: AgentId, claim: Claim, gain: u64) -> bool {
449    gain > 0
450        && match claim.winner {
451            None => true,
452            Some(winner) => gain > claim.bid || (gain == claim.bid && id < winner),
453        }
454}
455
456impl<V: Valuation<TaskId>> Participant for Agent<V> {
457    type Message = Message;
458
459    fn id(&self) -> AgentId {
460        self.id
461    }
462
463    fn bundle(&self) -> &Bundle<TaskId> {
464        &self.bundle
465    }
466
467    /// Runs the bundle phase and announces the new bids, plus the whole view when a
468    /// re-announcement is due. Of everything queued this round about one task, only the
469    /// last message goes out. Under [`Rules::Gnc2010`], a queued claim that names this
470    /// agent for a task it no longer holds is dropped, reading section IV.A of the paper:
471    /// the outgoing messages "accurately represent the state of the current bundle build".
472    fn act(&mut self, now: u64, outbox: &mut Vec<Message>) {
473        outbox.extend(self.build_bundle(now));
474
475        if self
476            .announce_every
477            .is_some_and(|period| now % period == period - 1)
478        {
479            outbox.extend(self.announce_all(now));
480        }
481
482        keep_last_per_task(outbox);
483        if self.rules == Rules::Gnc2010 {
484            outbox.retain(|message| {
485                message.claim.winner != Some(self.id) || self.bundle.contains(&message.task)
486            });
487        }
488    }
489
490    /// Resolves `message` and rebroadcasts right away. A change of the task's winner or
491    /// bid counts as a change, as does a released task; a moved bid time alone does not.
492    fn receive(&mut self, now: u64, message: &Message, outbox: &mut Vec<Message>) -> bool {
493        let view = |agent: &Self| {
494            let claim = agent.claims.get(message.task.index());
495
496            (
497                claim.map(|claim| (claim.winner, claim.bid)),
498                agent.bundle.len(),
499            )
500        };
501        let before = view(self);
502        outbox.extend(Agent::receive(self, now, message));
503
504        view(self) != before
505    }
506
507    /// The sender, the task, and the claim: winner, bid and time.
508    fn message_bytes(_message: &Message) -> u64 {
509        4 + 4 + 4 + 8 + 8
510    }
511
512    /// Every agent believes in the same winner and bid for every task, every bundle
513    /// matches, no bundle phase would add a task, and every message in flight names the
514    /// agreed winner and bid. Such messages can only move bid times, never winners, so the
515    /// assignment is final even while re-announcements keep the network busy. A lost
516    /// message can leave a quiet network split, so quiet alone is not enough.
517    fn is_settled(team: &[Self], in_flight: &[&Message]) -> bool {
518        let Some(first) = team.first() else {
519            return true;
520        };
521
522        let agreed = |task: TaskId, claim: Claim| {
523            let theirs = first.claims[task.index()];
524            claim.winner == theirs.winner && claim.bid == theirs.bid
525        };
526
527        team.iter().all(Agent::is_consistent)
528            && !team.iter().any(Agent::can_bid)
529            && team.iter().all(|agent| {
530                agent
531                    .tasks
532                    .iter()
533                    .all(|&task| agreed(task, agent.claims[task.index()]))
534            })
535            && in_flight.iter().all(|message| {
536                message.task.index() < first.claims.len() && agreed(message.task, message.claim)
537            })
538    }
539}
540
541/// Unit tests for [`Agent`].
542#[cfg(test)]
543mod tests;