task_allocation/bwtc.rs
1//! The task consensus of bid-warped CBBA (BW-TC): agents bid as in CBBA, but exchange
2//! only what changed, and announce every bid they withdraw.
3//!
4//! **Experimental.** This is a candidate replacement for [`acbba`](crate::acbba)'s
5//! deconfliction tables, which do not settle reliably. Its published convergence proof
6//! assumes synchronous, reliable rounds.
7//!
8//! Each agent keeps the best bid it knows for every task, and a timestamp for every pair of
9//! bidder and task. After its bundle phase, it compares its bundle with the one it last
10//! announced: tasks it no longer holds go out as *drop bids*, new tasks as bids. A receiver
11//! takes an entry only when it is newer than what it has seen of that bidder on that task,
12//! so a withdrawn bid can never come back from a stale copy, however it is relayed. A newer
13//! drop removes the bidder's bid; a newer bid is kept, and passed on when it is the best
14//! known, while otherwise the receiver answers with the best bid it knows. Everything an agent learns or
15//! answers goes out together at the end of its next round.
16//!
17//! The consensus is Algorithms 4 to 6 of Johnson, Choi, Ponda and How, "Decentralized Task
18//! Allocation Using Local Information Consistency Assumptions", Journal of Aerospace
19//! Information Systems 14(2), 2017 (<https://doi.org/10.2514/1.I010461>). The paper also
20//! warps bids so that scores need not diminish; this module does not, so valuations must
21//! have [diminishing marginal gains](crate::check_diminishing), as for CBBA.
22//!
23//! Choices this implementation makes where the paper leaves room:
24//!
25//! - Timestamps come from a clock all agents share, passed in as `now`, counted in half
26//! ticks: a drop made at tick `t` is stamped `2t + 1` and a bid `2t + 2`, so a bid always
27//! comes after a drop the same agent made in the same round. This is the paper's `δ`.
28//! - A bid replaces a task's entry in an agent's bundle only when the bid changed; a task
29//! kept with the same gain is not announced again.
30//! - Nothing is ever repeated, so a lost message is lost for good: the paper says as much.
31//! Use it on networks that deliver every message.
32//!
33//! One deliberate deviation: the paper keeps one bid per task, the best known, and records
34//! the time of every bid it hears, kept or not. An agent that hears a bid while a better
35//! one stands then discards it, and when the better bid is dropped and the agent bids on
36//! the free task itself, the others' answers carry the discarded bid at a time it has
37//! already seen, so it ignores them: the team falls quiet with the agent believing it wins
38//! a task another agent holds. Here an agent keeps the latest bid of every bidder on every
39//! task, and the best of them counts. Since every withdrawal is announced, a kept bid stays
40//! valid until its drop arrives, and the runner-up takes over when the best bid is dropped;
41//! the agent then announces the runner-up along with the drop, since its neighbors may
42//! never have heard of it.
43
44use alloc::vec;
45use alloc::vec::Vec;
46
47use crate::bundle::Bundle;
48use crate::id::{AgentId, TaskId};
49use crate::sim::Participant;
50use crate::valuation::Valuation;
51
52/// A bid: who placed it, and its gain.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub struct Bid {
55 /// The agent that placed it.
56 pub bidder: AgentId,
57
58 /// Its marginal gain; positive.
59 pub gain: u64,
60}
61
62impl Bid {
63 /// Whether this bid beats `other`: a higher gain, or an equal gain by a smaller agent.
64 #[must_use]
65 pub fn outbids(self, other: Self) -> bool {
66 self.gain > other.gain || (self.gain == other.gain && self.bidder < other.bidder)
67 }
68}
69
70/// One piece of news about one task.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
72pub enum Entry {
73 /// A bid, made at `time`.
74 Bid {
75 /// The task bid on.
76 task: TaskId,
77
78 /// The bid.
79 bid: Bid,
80
81 /// When the bidder placed it, in half ticks.
82 time: u64,
83 },
84
85 /// A bidder's withdrawal of its bid on a task, made at `time`.
86 Drop {
87 /// The task.
88 task: TaskId,
89
90 /// The agent withdrawing its bid.
91 bidder: AgentId,
92
93 /// When it withdrew it, in half ticks.
94 time: u64,
95 },
96}
97
98impl Entry {
99 /// The task the entry is about.
100 #[must_use]
101 pub const fn task(self) -> TaskId {
102 match self {
103 Self::Bid { task, .. } | Self::Drop { task, .. } => task,
104 }
105 }
106}
107
108/// Everything an agent broadcasts at the end of one round.
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct Packet {
111 /// The agent that broadcast it.
112 pub sender: AgentId,
113
114 /// What it learned or answered since its last broadcast, in order.
115 pub entries: Vec<Entry>,
116}
117
118/// One BW-TC agent: its valuation, its bundle, and the best bid it knows for every task.
119///
120/// # Examples
121///
122/// ```
123/// use task_allocation::bwtc::Agent;
124/// use task_allocation::sim::{Network, Simulation};
125/// use task_allocation::{AgentId, TaskId, Valuation};
126///
127/// /// Values task `t` at `10 + t` for agent 0 and `20 - t` for agent 1, minus 2 per task held.
128/// struct Skewed(u64);
129///
130/// impl Valuation<TaskId> for Skewed {
131/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
132/// let task = task.index() as u64;
133/// let base = if self.0 == 0 { 10 + task } else { 20 - task };
134/// base.checked_sub(2 * path.len() as u64)
135/// }
136/// }
137///
138/// let agents = (0..2).map(|id| Agent::new(AgentId(id), 2, 4, 2, Skewed(id as u64))).collect();
139/// let network = Network { seed: 1, max_delay: 3, ..Network::default() };
140/// let mut simulation = Simulation::new(agents, network);
141///
142/// simulation.run_until_settled(200).expect("falls quiet in agreement");
143/// assert!(simulation.assignment().is_conflict_free());
144/// ```
145#[derive(Clone, Debug)]
146pub struct Agent<V> {
147 /// This agent's identifier.
148 id: AgentId,
149
150 /// How this agent values tasks.
151 valuation: V,
152
153 /// The most tasks this agent holds at once.
154 capacity: usize,
155
156 /// The tasks this agent holds, with the bid it placed on each.
157 bundle: Bundle<TaskId>,
158
159 /// The latest bid of each bidder on each task, as its gain, indexed by
160 /// `bidder * tasks + task`; `None` when the bidder has none, or dropped it.
161 gains: Vec<Option<u64>>,
162
163 /// The latest time this agent has seen of each bidder on each task, in half ticks,
164 /// indexed by `bidder * tasks + task`; zero before any.
165 stamps: Vec<u64>,
166
167 /// The tasks and gains of this agent's bundle as last announced.
168 announced: Vec<(TaskId, u64)>,
169
170 /// What this agent broadcasts at the end of its next round.
171 queue: Vec<Entry>,
172
173 /// Every task identifier, in order: the candidates of the bundle phase.
174 tasks: Vec<TaskId>,
175}
176
177impl<V: Valuation<TaskId>> Agent<V> {
178 /// Agent `id` of a team of `agents`, bidding on tasks `0..tasks` and holding at most
179 /// `capacity` of them.
180 ///
181 /// # Panics
182 ///
183 /// Panics when `id` is not below `agents`.
184 #[must_use]
185 pub fn new(id: AgentId, agents: usize, tasks: usize, capacity: usize, valuation: V) -> Self {
186 assert!(id.index() < agents, "the agent must be part of the team");
187
188 Self {
189 id,
190 valuation,
191 capacity,
192 bundle: Bundle::new(),
193 gains: vec![None; agents * tasks],
194 stamps: vec![0; agents * tasks],
195 announced: Vec::new(),
196 queue: Vec::new(),
197 tasks: (0..tasks).map(TaskId).collect(),
198 }
199 }
200
201 /// The bundle phase at tick `now`: adds the most valuable tasks this agent can win, then
202 /// queues a drop bid for every task it no longer holds and a bid for every new one.
203 pub fn build_bundle(&mut self, now: u64) {
204 let id = self.id;
205 let best: Vec<Option<Bid>> = self.tasks.iter().map(|&task| self.best(task)).collect();
206 self.bundle
207 .extend_greedily(&self.valuation, &self.tasks, self.capacity, |task, gain| {
208 wins(id, best[task.index()], gain)
209 });
210
211 self.announce_changes(now);
212 }
213
214 /// Whether the bundle phase would add a task now.
215 #[must_use]
216 pub fn can_bid(&self) -> bool {
217 let id = self.id;
218
219 self.bundle.len() < self.capacity
220 && self
221 .bundle
222 .best_candidate(&self.valuation, &self.tasks, |task, gain| {
223 wins(id, self.best(*task), gain)
224 })
225 .is_some()
226 }
227
228 /// The consensus phase for one packet: merges its drop bids, then its bids, queuing
229 /// what is new and answering bids it knows better ones for, then releases the first
230 /// task in the bundle this agent was outbid on, and every task added after it.
231 ///
232 /// Packets from this agent itself are ignored, as are entries about unknown tasks or
233 /// bidders outside the team.
234 pub fn receive(&mut self, packet: &Packet) {
235 if packet.sender == self.id {
236 return;
237 }
238
239 for entry in &packet.entries {
240 if let Entry::Drop { task, bidder, time } = *entry {
241 self.merge_drop(task, bidder, time);
242 }
243 }
244
245 for entry in &packet.entries {
246 if let Entry::Bid { task, bid, time } = *entry {
247 self.merge_bid(task, bid, time);
248 }
249 }
250
251 self.release_outbid();
252 }
253
254 /// Takes a drop bid of `bidder` on `task`, made at `time`, when it is new.
255 fn merge_drop(&mut self, task: TaskId, bidder: AgentId, time: u64) {
256 let Some(stamp) = self.stamp_mut(bidder, task) else {
257 return;
258 };
259 if *stamp >= time {
260 return;
261 }
262
263 *stamp = time;
264 self.queue.push(Entry::Drop { task, bidder, time });
265 self.set_gain(bidder, task, None);
266 self.queue_best(task);
267 }
268
269 /// Queues the best bid this agent knows for `task`, if any, with the time it was made:
270 /// after a drop, a runner-up may have taken over that neighbors never heard of.
271 fn queue_best(&mut self, task: TaskId) {
272 if let Some(best) = self.best(task) {
273 let time = self.stamp(best.bidder, task);
274 self.queue.push(Entry::Bid {
275 task,
276 bid: best,
277 time,
278 });
279 }
280 }
281
282 /// Takes `bid` on `task`, made at `time`, when it is new: keeps it, and passes it on
283 /// when it is now the best known bid, or answers with the best known bid otherwise.
284 fn merge_bid(&mut self, task: TaskId, bid: Bid, time: u64) {
285 let Some(stamp) = self.stamp_mut(bid.bidder, task) else {
286 return;
287 };
288 if *stamp >= time {
289 return;
290 }
291
292 *stamp = time;
293 self.set_gain(bid.bidder, task, Some(bid.gain));
294 let best = self.best(task).expect("the bid was just kept");
295 let time = self.stamp(best.bidder, task);
296 self.queue.push(Entry::Bid {
297 task,
298 bid: best,
299 time,
300 });
301 }
302
303 /// Drops the first task in the bundle this agent no longer wins, and every task added
304 /// after it, forgetting its own bids on them; the next bundle phase announces the drops.
305 fn release_outbid(&mut self) {
306 let id = self.id;
307 let Some(lost) = self
308 .bundle
309 .tasks()
310 .position(|&task| self.best(task).is_none_or(|best| best.bidder != id))
311 else {
312 return;
313 };
314
315 for task in self.bundle.release_from(lost) {
316 self.set_gain(id, task, None);
317 }
318 }
319
320 /// Queues a drop bid at `now` for every announced task the bundle no longer holds with
321 /// the same gain, and a bid for every task it holds anew, then records the bundle as
322 /// announced. Every task held counts as won by this agent's own bid, including one
323 /// released and taken back with the same gain, which is not announced again.
324 fn announce_changes(&mut self, now: u64) {
325 let id = self.id;
326 let current: Vec<(TaskId, u64)> = self
327 .bundle
328 .entries()
329 .map(|(&task, gain)| (task, gain))
330 .collect();
331
332 let announced = core::mem::take(&mut self.announced);
333 for &(task, gain) in &announced {
334 if !current.contains(&(task, gain)) {
335 let time = 2 * now + 1;
336 self.set_stamp(id, task, time);
337 if !current.iter().any(|&(held, _)| held == task) {
338 self.set_gain(id, task, None);
339 self.queue_best(task);
340 }
341 self.queue.push(Entry::Drop {
342 task,
343 bidder: id,
344 time,
345 });
346 }
347 }
348
349 for &(task, gain) in ¤t {
350 let bid = Bid { bidder: id, gain };
351 self.set_gain(id, task, Some(gain));
352 if !announced.contains(&(task, gain)) {
353 let time = 2 * now + 2;
354 self.set_stamp(id, task, time);
355 self.queue.push(Entry::Bid { task, bid, time });
356 }
357 }
358
359 self.announced = current;
360 }
361
362 /// Records `gain` as `bidder`'s latest bid on `task`, or `None` for none.
363 ///
364 /// # Panics
365 ///
366 /// Panics on an unknown task or a bidder outside the team; callers check packet
367 /// entries with [`stamp_mut`](Self::stamp_mut) first.
368 fn set_gain(&mut self, bidder: AgentId, task: TaskId, gain: Option<u64>) {
369 let tasks = self.tasks.len();
370 self.gains[bidder.index() * tasks + task.index()] = gain;
371 }
372
373 /// The latest time this agent has seen of `bidder` on `task`.
374 ///
375 /// # Panics
376 ///
377 /// Panics on an unknown task or a bidder outside the team.
378 fn stamp(&self, bidder: AgentId, task: TaskId) -> u64 {
379 self.stamps[bidder.index() * self.tasks.len() + task.index()]
380 }
381
382 /// Records `time` as the latest time seen of `bidder` on `task`.
383 ///
384 /// # Panics
385 ///
386 /// Panics on an unknown task or a bidder outside the team.
387 fn set_stamp(&mut self, bidder: AgentId, task: TaskId, time: u64) {
388 let tasks = self.tasks.len();
389 self.stamps[bidder.index() * tasks + task.index()] = time;
390 }
391
392 /// The latest time seen of `bidder` on `task`, to update; `None` for an unknown task or
393 /// a bidder outside the team.
394 fn stamp_mut(&mut self, bidder: AgentId, task: TaskId) -> Option<&mut u64> {
395 let tasks = self.tasks.len();
396 if task.index() >= tasks {
397 return None;
398 }
399
400 self.stamps.get_mut(bidder.index() * tasks + task.index())
401 }
402
403 /// The packet to broadcast now, if anything is queued; empties the queue.
404 pub fn packet(&mut self) -> Option<Packet> {
405 if self.queue.is_empty() {
406 return None;
407 }
408
409 Some(Packet {
410 sender: self.id,
411 entries: core::mem::take(&mut self.queue),
412 })
413 }
414}
415
416impl<V> Agent<V> {
417 /// This agent's identifier.
418 #[must_use]
419 pub const fn id(&self) -> AgentId {
420 self.id
421 }
422
423 /// This agent's valuation.
424 #[must_use]
425 pub const fn valuation(&self) -> &V {
426 &self.valuation
427 }
428
429 /// The tasks this agent holds, with the bid it placed on each.
430 #[must_use]
431 pub const fn bundle(&self) -> &Bundle<TaskId> {
432 &self.bundle
433 }
434
435 /// The best bid this agent knows for `task`: the best of the latest bids of every
436 /// bidder.
437 ///
438 /// # Panics
439 ///
440 /// Panics when `task` is not one of this agent's tasks.
441 #[must_use]
442 pub fn best(&self, task: TaskId) -> Option<Bid> {
443 let tasks = self.tasks.len();
444 assert!(task.index() < tasks, "unknown task");
445
446 self.gains
447 .iter()
448 .skip(task.index())
449 .step_by(tasks)
450 .enumerate()
451 .filter_map(|(bidder, gain)| {
452 gain.map(|gain| Bid {
453 bidder: AgentId(bidder),
454 gain,
455 })
456 })
457 .reduce(|best, bid| if bid.outbids(best) { bid } else { best })
458 }
459
460 /// Whether this agent's bundle holds exactly the tasks whose best known bid is its own.
461 #[must_use]
462 pub fn is_consistent(&self) -> bool {
463 let own = |task: TaskId| self.best(task).is_some_and(|best| best.bidder == self.id);
464 let won = self.tasks.iter().filter(|&&task| own(task)).count();
465
466 won == self.bundle.len() && self.bundle.tasks().all(|&task| own(task))
467 }
468}
469
470/// Whether agent `id`, bidding `gain`, beats `best`: a positive bid that outbids it, or any
471/// positive bid when nobody bids.
472fn wins(id: AgentId, best: Option<Bid>, gain: u64) -> bool {
473 gain > 0 && best.is_none_or(|best| Bid { bidder: id, gain }.outbids(best))
474}
475
476impl<V: Valuation<TaskId>> Participant for Agent<V> {
477 type Message = Packet;
478
479 fn id(&self) -> AgentId {
480 self.id
481 }
482
483 fn bundle(&self) -> &Bundle<TaskId> {
484 &self.bundle
485 }
486
487 /// Runs the bundle phase, then broadcasts everything queued, if anything.
488 fn act(&mut self, now: u64, outbox: &mut Vec<Packet>) {
489 self.build_bundle(now);
490 outbox.extend(self.packet());
491 }
492
493 /// Merges `packet`; what it calls for goes out at the end of the next round. A change
494 /// of the best known bid on a task the packet names counts as a change, as does a
495 /// released task; a newer time for the same bid does not.
496 fn receive(&mut self, _now: u64, packet: &Packet, _outbox: &mut Vec<Packet>) -> bool {
497 let view = |agent: &Self| -> (Vec<Option<Bid>>, usize) {
498 let best = packet
499 .entries
500 .iter()
501 .map(|entry| entry.task())
502 .filter(|task| task.index() < agent.tasks.len())
503 .map(|task| agent.best(task))
504 .collect();
505
506 (best, agent.bundle.len())
507 };
508 let before = view(self);
509 Agent::receive(self, packet);
510
511 view(self) != before
512 }
513
514 /// The sender, then every entry after the list's length: a tag, the task, the bidder,
515 /// the gain (unused by a drop) and the time.
516 fn message_bytes(packet: &Packet) -> u64 {
517 let entries = u64::try_from(packet.entries.len()).unwrap_or(u64::MAX);
518
519 4 + 4 + (1 + 4 + 4 + 8 + 8) * entries
520 }
521
522 /// The network is quiet, nothing is queued, every agent knows the same best bid for
523 /// every task, every bundle matches, and no bundle phase would add a task.
524 fn is_settled(team: &[Self], in_flight: &[&Packet]) -> bool {
525 let Some(first) = team.first() else {
526 return true;
527 };
528
529 in_flight.is_empty()
530 && team.iter().all(|agent| agent.queue.is_empty())
531 && team.iter().all(|agent| {
532 agent
533 .tasks
534 .iter()
535 .all(|&task| agent.best(task) == first.best(task))
536 })
537 && team.iter().all(Agent::is_consistent)
538 && !team.iter().any(Agent::can_bid)
539 }
540}
541
542/// Unit tests for [`Agent`].
543#[cfg(test)]
544mod tests;