task_allocation/ccbba.rs
1//! Coupled-constraint CBBA (CCBBA): CBBA for tasks that need, or exclude, each other.
2//!
3//! Some tasks only make sense together, such as a strike that needs a sensor, and some
4//! exclude each other. [`Constraints`] describes these relations in activities. An
5//! [`Agent`] runs [CBBA](crate::cbba) with the extensions of Whitten, Choi, Johnson and How,
6//! "Decentralized Task Allocation with Coupled Constraints in Complex Missions", American
7//! Control Conference 2011:
8//!
9//! - **Pessimistic bidding**: an agent bids on a task only once every task it depends on has
10//! a winner. Tasks with no mutual dependency are bid on this way.
11//! - **Optimistic bidding**: on a task with at least one mutual dependency, an agent may
12//! bid first and wait for its partners, for all its dependencies, one-way ones included,
13//! as in the paper (`O_jq` non-empty). If they do not appear within [`Optimism::timeout`] rounds, it gives
14//! the task up and loses one of a limited number of attempts. Once the attempts are used
15//! up, it bids pessimistically.
16//! - **Mutual exclusion**: an agent bids on a task only if it outbids every task excluded by
17//! it, and gives a task up once an excluded task's winner outbids it.
18//!
19//! Each round, an agent first gives up the tasks whose constraints fail, then runs the
20//! bundle phase; messages and the conflict table are CBBA's.
21//!
22//! The paper promises no convergence, and there is none in general: constrained gains do
23//! not diminish, by design. An agent can keep outbidding a partner on a task whose
24//! dependency only that partner's bundle provides, so the partner releases the dependency,
25//! the agent gives the task up, the partner rebuilds both, and the cycle repeats. The tests
26//! pin such a case. The timeouts and attempt counts are the caller's choice; the paper
27//! gives no values.
28//!
29//! Choices this implementation makes where the paper is silent:
30//!
31//! - Eligibility is decided at the start of each bundle phase, from the winners known then.
32//! A task that depends on another the agent adds in the same phase becomes eligible in the
33//! next round.
34//! - The count of rounds an optimistic task waited resets once its dependencies are met.
35//! - Ties in mutual exclusion go to the smaller agent, as everywhere in this crate; a strict
36//! comparison would make both tasks give way.
37
38mod constraints;
39mod timed;
40
41pub use constraints::{ConstraintError, Constraints};
42pub use timed::{TimedAgent, TimedMessage, Windowed};
43
44use alloc::vec;
45use alloc::vec::Vec;
46use core::cell::RefCell;
47
48use crate::bundle::Bundle;
49use crate::cbba::table::Claim;
50use crate::cbba::{self, Message};
51use crate::id::{AgentId, TaskId};
52use crate::sim::Participant;
53use crate::valuation::{Insertion, Valuation};
54
55/// How long, and how often, an agent bids optimistically on a task in a mutual dependency.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub struct Optimism {
58 /// Rounds an agent keeps such a task while a task it depends on has no winner; `o` in
59 /// the paper.
60 pub timeout: u32,
61
62 /// Attempts at bidding on such a task even while none of the tasks it depends on has a
63 /// winner; `w_solo` in the paper.
64 pub solo_attempts: u32,
65
66 /// Attempts at bidding on such a task once at least one of the tasks it depends on has
67 /// a winner; `w_any` in the paper, usually larger than `solo_attempts`.
68 ///
69 /// As in the paper, an agent may bid while either budget lasts (`any` only with a
70 /// dependency met), and every timeout spends one attempt from both.
71 pub any_attempts: u32,
72}
73
74/// What a [`Gate`] knows when deciding whether its agent may bid on a task.
75#[derive(Clone, Debug)]
76struct View {
77 /// For each task, the winner and winning bid as of the start of the bundle phase.
78 claims: Vec<Claim>,
79
80 /// For each task, the remaining solo attempts.
81 solo: Vec<u32>,
82
83 /// For each task, the remaining attempts with some dependencies met.
84 any: Vec<u32>,
85
86 /// For each task, the start time of its winning bid, when known; always `None` for
87 /// agents without timing.
88 starts: Vec<Option<u64>>,
89}
90
91/// A valuation that hides tasks the agent may not bid on, so CBBA's bundle phase skips them.
92#[derive(Clone, Debug)]
93struct Gate<V> {
94 /// The agent's own valuation.
95 inner: V,
96
97 /// The constraints between tasks.
98 constraints: Constraints,
99
100 /// The agent this gate belongs to.
101 id: AgentId,
102
103 /// The state eligibility depends on, refreshed before every bundle phase.
104 view: RefCell<View>,
105}
106
107impl<V> Gate<V> {
108 /// The agent's own valuation.
109 const fn inner(&self) -> &V {
110 &self.inner
111 }
112
113 /// The constraints between tasks.
114 const fn constraints(&self) -> &Constraints {
115 &self.constraints
116 }
117
118 /// How many of `task`'s dependencies have a winner, and how many it has.
119 fn satisfied(&self, claims: &[Claim], task: TaskId) -> (usize, usize) {
120 let mut met = 0;
121 let mut required = 0;
122 for requirement in self.constraints.requirements(task) {
123 required += 1;
124 if claims[requirement.index()].winner.is_some() {
125 met += 1;
126 }
127 }
128
129 (met, required)
130 }
131
132 /// Whether the agent has optimistic attempts left at `task`; without, it bids, and
133 /// releases, pessimistically.
134 fn has_attempts(&self, task: TaskId) -> bool {
135 let view = self.view.borrow();
136
137 view.solo[task.index()] > 0 || view.any[task.index()] > 0
138 }
139
140 /// Whether the agent may bid on `task` at all, before looking at its gain.
141 fn may_bid(&self, task: TaskId) -> bool {
142 let view = self.view.borrow();
143 let (met, required) = self.satisfied(&view.claims, task);
144 if met == required {
145 return true;
146 }
147
148 self.constraints.is_mutual(task)
149 && (view.solo[task.index()] > 0 || (view.any[task.index()] > 0 && met > 0))
150 }
151
152 /// Whether a bid of `gain` on `task` outbids every task excluded by it.
153 fn beats_exclusions(&self, task: TaskId, gain: u64) -> bool {
154 let view = self.view.borrow();
155 let bid = Claim {
156 winner: Some(self.id),
157 bid: gain,
158 };
159
160 self.constraints.exclusions(task).all(|other| {
161 view.claims[other.index()].winner.is_none() || bid.outbids(view.claims[other.index()])
162 })
163 }
164}
165
166impl<V: Valuation<TaskId>> Valuation<TaskId> for Gate<V> {
167 fn marginal_score(&self, bundle: &[TaskId], task: &TaskId) -> Option<u64> {
168 self.best_insertion(bundle, task)
169 .map(|insertion| insertion.gain)
170 }
171
172 fn best_insertion(&self, path: &[TaskId], task: &TaskId) -> Option<Insertion> {
173 if !self.may_bid(*task) {
174 return None;
175 }
176
177 let insertion = self.inner.best_insertion(path, task)?;
178
179 self.beats_exclusions(*task, insertion.gain)
180 .then_some(insertion)
181 }
182}
183
184/// One CCBBA agent: a CBBA agent whose bids respect coupled constraints.
185///
186/// # Examples
187///
188/// ```
189/// use task_allocation::ccbba::{Agent, Constraints, Optimism};
190/// use task_allocation::sim::{Network, Simulation};
191/// use task_allocation::{AgentId, TaskId, Valuation};
192///
193/// /// A strike (task 0) and the sensing it needs (task 1), each worth something to one agent.
194/// struct Fixed([u64; 2]);
195///
196/// impl Valuation<TaskId> for Fixed {
197/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
198/// path.is_empty().then_some(self.0[task.index()])
199/// }
200/// }
201///
202/// let mut constraints = Constraints::new(2);
203/// constraints.add_activity(&[TaskId(0), TaskId(1)], &[&[0, 1], &[1, 0]]).unwrap();
204/// let optimism = Optimism { timeout: 5, solo_attempts: 2, any_attempts: 4 };
205///
206/// let agents = [Fixed([9, 0]), Fixed([0, 3])]
207/// .into_iter()
208/// .enumerate()
209/// .map(|(id, valuation)| Agent::new(AgentId(id), 2, 2, 1, valuation, constraints.clone(), optimism))
210/// .collect();
211/// let mut simulation = Simulation::new(agents, Network::default());
212///
213/// simulation.run_until_settled(100).expect("settles");
214/// let assignment = simulation.assignment();
215/// assert_eq!(assignment.holder(TaskId(0)), Some(AgentId(0)));
216/// assert_eq!(assignment.holder(TaskId(1)), Some(AgentId(1)));
217/// assert!(constraints.is_satisfied_by(&assignment));
218/// ```
219#[derive(Clone, Debug)]
220pub struct Agent<V> {
221 /// The CBBA agent doing the bidding and consensus.
222 inner: cbba::Agent<Gate<V>>,
223
224 /// How long and how often this agent bids optimistically.
225 optimism: Optimism,
226
227 /// For each task, the rounds this agent has held it while a dependency had no winner;
228 /// `ν` in the paper.
229 waited: Vec<u32>,
230}
231
232impl<V: Valuation<TaskId>> Agent<V> {
233 /// Agent `id` of a team of `agents`, bidding on tasks `0..tasks` under `constraints` and
234 /// holding at most `capacity` of them.
235 ///
236 /// # Panics
237 ///
238 /// Panics when `id` is not below `agents`, or when `constraints` cover a different
239 /// number of tasks.
240 #[must_use]
241 pub fn new(
242 id: AgentId,
243 agents: usize,
244 tasks: usize,
245 capacity: usize,
246 valuation: V,
247 constraints: Constraints,
248 optimism: Optimism,
249 ) -> Self {
250 assert_eq!(
251 constraints.tasks(),
252 tasks,
253 "constraints must cover exactly the tasks"
254 );
255
256 let gate = Gate {
257 inner: valuation,
258 constraints,
259 id,
260 view: RefCell::new(View {
261 claims: vec![Claim::NONE; tasks],
262 solo: vec![optimism.solo_attempts; tasks],
263 any: vec![optimism.any_attempts; tasks],
264 starts: vec![None; tasks],
265 }),
266 };
267
268 Self {
269 inner: cbba::Agent::new(id, agents, tasks, capacity, gate),
270 optimism,
271 waited: vec![0; tasks],
272 }
273 }
274
275 /// One round: gives up the tasks whose constraints fail, then runs the bundle phase.
276 /// Returns the number of tasks the bundle phase added.
277 pub fn build_bundle(&mut self) -> usize {
278 self.enforce();
279 self.refresh_view();
280
281 let added = self.inner.build_bundle();
282 self.refresh_view();
283
284 added
285 }
286
287 /// The message this agent broadcasts now; see [`cbba::Agent::message`].
288 #[must_use]
289 pub fn message(&mut self) -> Message {
290 self.inner.message()
291 }
292
293 /// The consensus phase for one message; see [`cbba::Agent::receive`].
294 pub fn receive(&mut self, message: &Message) -> bool {
295 let changed = self.inner.receive(message);
296 self.refresh_view();
297
298 changed
299 }
300
301 /// Whether the next round would change anything: a task would be given up, an
302 /// optimistic task is still waiting for its partners, or the bundle phase would add a
303 /// task.
304 #[must_use]
305 pub fn can_bid(&self) -> bool {
306 self.violation().is_some() || self.is_waiting() || self.inner.can_bid()
307 }
308
309 /// Whether a held task has a dependency without a winner.
310 fn is_waiting(&self) -> bool {
311 let gate = self.inner.valuation();
312 let claims = self.inner.claims();
313
314 self.inner.bundle().tasks().any(|&task| {
315 let (met, required) = gate.satisfied(claims, task);
316 met < required
317 })
318 }
319
320 /// Copies the current winners into the gate, which decides eligibility from them.
321 fn refresh_view(&self) {
322 let mut view = self.inner.valuation().view.borrow_mut();
323 view.claims.clear();
324 view.claims.extend_from_slice(self.inner.claims());
325 }
326
327 /// Gives up tasks whose constraints fail until none do, counting the rounds optimistic
328 /// tasks wait for their partners.
329 fn enforce(&mut self) {
330 self.count_waiting();
331
332 while let Some((task, timed_out)) = self.violation() {
333 self.inner.give_up(task);
334 self.waited[task.index()] = 0;
335 if timed_out {
336 self.spend_attempt(task);
337 }
338
339 self.refresh_view();
340 }
341 }
342
343 /// Counts one more round for every held task with a dependency lacking a winner, and
344 /// resets the count of every other task, including tasks released since the last round,
345 /// however they were released.
346 fn count_waiting(&mut self) {
347 let gate = self.inner.valuation();
348 let claims = self.inner.claims();
349 let bundle = self.inner.bundle();
350 for (index, waited) in self.waited.iter_mut().enumerate() {
351 let task = TaskId(index);
352 if !bundle.contains(&task) {
353 *waited = 0;
354 continue;
355 }
356
357 let (met, required) = gate.satisfied(claims, task);
358 *waited = if met < required { *waited + 1 } else { 0 };
359 }
360 }
361
362 /// The first held task whose constraints fail, and whether giving it up spends an
363 /// optimistic attempt; `None` when all hold.
364 ///
365 /// A task fails when a dependency has no winner and it is pessimistic or timed out, when
366 /// the winner of an excluded task outbids it, or when its start conflicts with a
367 /// partner's. As in the paper (Section IV-F), a timeout or a timing conflict on a task
368 /// bid optimistically spends an attempt; an exclusion does not.
369 fn violation(&self) -> Option<(TaskId, bool)> {
370 let gate = self.inner.valuation();
371 let claims = self.inner.claims();
372
373 self.inner.bundle().tasks().find_map(|&task| {
374 let (met, required) = gate.satisfied(claims, task);
375 let unmet = met < required;
376 let optimistic = gate.constraints.is_mutual(task) && gate.has_attempts(task);
377 let timed_out = self.waited[task.index()] >= self.optimism.timeout;
378 if unmet && (!optimistic || timed_out) {
379 return Some((task, optimistic));
380 }
381
382 let mine = claims[task.index()];
383 let outbid = gate.constraints.exclusions(task).any(|other| {
384 claims[other.index()].winner.is_some() && !mine.outbids(claims[other.index()])
385 });
386 if outbid {
387 return Some((task, false));
388 }
389
390 self.yields_in_time(task).then_some((task, optimistic))
391 })
392 }
393
394 /// Whether this agent must give up `task` because its start conflicts with the start of
395 /// another assigned task in its activity.
396 ///
397 /// A task that depends on the other one alone gives way; one the other depends on alone
398 /// stays. Of two mutually dependent tasks, the one that starts earlier into its time
399 /// window gives way, since it could have started later; ties go to the smaller holder,
400 /// then the smaller task.
401 fn yields_in_time(&self, task: TaskId) -> bool {
402 let gate = self.inner.valuation();
403 let view = gate.view.borrow();
404 let claims = self.inner.claims();
405 let constraints = &gate.constraints;
406 let Some(start) = view.starts[task.index()] else {
407 return false;
408 };
409
410 let mine = (
411 offset(constraints, task, start),
412 core::cmp::Reverse(self.inner.id()),
413 core::cmp::Reverse(task),
414 );
415 constraints.activity_tasks(task).any(|other| {
416 let (Some(holder), Some(other_start)) =
417 (claims[other.index()].winner, view.starts[other.index()])
418 else {
419 return false;
420 };
421
422 if constraints.starts_agree(task, start, other, other_start) {
423 return false;
424 }
425
426 match (
427 constraints.depends_on(task, other),
428 constraints.depends_on(other, task),
429 ) {
430 (true, false) => true,
431 (true, true) => {
432 let theirs = (
433 offset(constraints, other, other_start),
434 core::cmp::Reverse(holder),
435 core::cmp::Reverse(other),
436 );
437 mine < theirs
438 }
439 _ => false,
440 }
441 })
442 }
443
444 /// Uses up one solo and one any attempt at `task`.
445 fn spend_attempt(&self, task: TaskId) {
446 let mut view = self.inner.valuation().view.borrow_mut();
447 let solo = &mut view.solo[task.index()];
448 *solo = solo.saturating_sub(1);
449 let any = &mut view.any[task.index()];
450 *any = any.saturating_sub(1);
451 }
452}
453
454/// How far into its time window `task` starts at `start`; negative before the opening.
455fn offset(constraints: &Constraints, task: TaskId, start: u64) -> i128 {
456 i128::from(start) - i128::from(constraints.opening(task))
457}
458
459impl<V> Agent<V> {
460 /// This agent's identifier.
461 #[must_use]
462 pub const fn id(&self) -> AgentId {
463 self.inner.id()
464 }
465
466 /// This agent's own valuation.
467 #[must_use]
468 pub const fn valuation(&self) -> &V {
469 self.inner.valuation().inner()
470 }
471
472 /// The constraints this agent bids under.
473 #[must_use]
474 pub const fn constraints(&self) -> &Constraints {
475 self.inner.valuation().constraints()
476 }
477
478 /// The tasks this agent holds, with the bid it placed on each.
479 #[must_use]
480 pub const fn bundle(&self) -> &Bundle<TaskId> {
481 self.inner.bundle()
482 }
483
484 /// The winner this agent believes in for `task`; `None` when it knows of no bid.
485 ///
486 /// # Panics
487 ///
488 /// Panics when `task` is not one of this agent's tasks.
489 #[must_use]
490 pub fn winner(&self, task: TaskId) -> Option<AgentId> {
491 self.inner.winner(task)
492 }
493
494 /// The winning bid this agent believes in for `task`; zero when it knows of no bid.
495 ///
496 /// # Panics
497 ///
498 /// Panics when `task` is not one of this agent's tasks.
499 #[must_use]
500 pub fn winning_bid(&self, task: TaskId) -> u64 {
501 self.inner.winning_bid(task)
502 }
503}
504
505impl<V: Valuation<TaskId>> Participant for Agent<V> {
506 type Message = Message;
507
508 fn id(&self) -> AgentId {
509 self.inner.id()
510 }
511
512 fn bundle(&self) -> &Bundle<TaskId> {
513 self.inner.bundle()
514 }
515
516 /// Gives up failing tasks, runs the bundle phase, and broadcasts the full state.
517 fn act(&mut self, _now: u64, outbox: &mut Vec<Message>) {
518 self.build_bundle();
519 outbox.push(self.message());
520 }
521
522 /// Runs CBBA's consensus phase for `message`.
523 fn receive(&mut self, _now: u64, message: &Message, _outbox: &mut Vec<Message>) {
524 Agent::receive(self, message);
525 }
526
527 /// CBBA's settled check, plus: no agent would give up a task. Then every held task's
528 /// dependencies have winners and no excluded task outbids it.
529 fn is_settled(team: &[Self], in_flight: &[&Message]) -> bool {
530 let Some(first) = team.first() else {
531 return true;
532 };
533
534 team.iter().all(|agent| agent.inner.is_consistent())
535 && !team.iter().any(Agent::can_bid)
536 && team
537 .iter()
538 .all(|agent| agent.inner.claims() == first.inner.claims())
539 && in_flight
540 .iter()
541 .all(|message| message.claims() == first.inner.claims())
542 }
543}
544
545/// Unit tests for [`Agent`] and [`Constraints`].
546#[cfg(test)]
547mod tests;