task_allocation/bundle.rs
1//! An agent's bundle: the tasks it holds, in the order it took them on, plus their path.
2//!
3//! The *bundle order* is the order in which the agent added tasks, and each entry records
4//! the marginal gain the task had when it was added. The *path* is the same tasks in
5//! execution order, as [`Valuation::best_insertion`] placed them.
6//!
7//! Consensus algorithms need both. Gains are only valid for the tasks added before, so when
8//! an agent loses a task it also drops every task it added after it
9//! ([`Bundle::release_from`]): their gains assumed the lost task was still there.
10//!
11//! ```mermaid
12//! flowchart LR
13//! candidates[candidate tasks] --> best[best insertion per task]
14//! best --> pick[highest accepted gain]
15//! pick --> insert[insert into path, record gain]
16//! insert -->|below capacity| best
17//! ```
18
19use alloc::vec::Vec;
20
21use crate::valuation::{Insertion, Valuation};
22
23/// The tasks an agent holds, in bundle order and in path order.
24///
25/// # Invariants
26///
27/// - The bundle and the path hold the same tasks, each at most once.
28/// - Gains are those the tasks had when they were added, given the tasks added before them.
29///
30/// # Examples
31///
32/// ```
33/// use task_allocation::{Bundle, Valuation};
34///
35/// /// Values task `t` at `t`, but each task costs one more point than the last.
36/// struct Busy;
37///
38/// impl Valuation<u64> for Busy {
39/// fn marginal_score(&self, path: &[u64], task: &u64) -> Option<u64> {
40/// task.checked_sub(path.len() as u64)
41/// }
42/// }
43///
44/// let mut bundle = Bundle::new();
45/// let added = bundle.extend_greedily(&Busy, &[3, 9, 5], 2, |_, gain| gain > 0);
46///
47/// assert_eq!(added, 2);
48/// assert_eq!(bundle.tasks().collect::<Vec<_>>(), [&9, &5]);
49/// assert_eq!(bundle.value(), 9 + 4);
50/// ```
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Bundle<Task> {
53 /// The tasks with their gains, in the order they were added.
54 added: Vec<(Task, u64)>,
55
56 /// The same tasks in execution order.
57 path: Vec<Task>,
58}
59
60impl<Task> Default for Bundle<Task> {
61 fn default() -> Self {
62 Self::new()
63 }
64}
65
66impl<Task> Bundle<Task> {
67 /// An empty bundle.
68 #[must_use]
69 pub const fn new() -> Self {
70 Self {
71 added: Vec::new(),
72 path: Vec::new(),
73 }
74 }
75
76 /// The number of tasks held.
77 #[must_use]
78 pub fn len(&self) -> usize {
79 self.added.len()
80 }
81
82 /// Whether the bundle holds no task.
83 #[must_use]
84 pub fn is_empty(&self) -> bool {
85 self.added.is_empty()
86 }
87
88 /// The tasks in execution order.
89 #[must_use]
90 pub fn path(&self) -> &[Task] {
91 &self.path
92 }
93
94 /// The tasks in the order they were added.
95 pub fn tasks(&self) -> impl ExactSizeIterator<Item = &Task> + '_ {
96 self.added.iter().map(|(task, _)| task)
97 }
98
99 /// The tasks with the gain each had when it was added, in the order they were added.
100 pub fn entries(&self) -> impl ExactSizeIterator<Item = (&Task, u64)> + '_ {
101 self.added.iter().map(|(task, gain)| (task, *gain))
102 }
103
104 /// The bundle's value: the sum of the recorded gains.
105 ///
106 /// Saturates at [`u64::MAX`].
107 #[must_use]
108 pub fn value(&self) -> u64 {
109 self.added
110 .iter()
111 .fold(0, |total, (_, gain)| total.saturating_add(*gain))
112 }
113
114 /// Adds `task` at the end of the bundle order and at `insertion.position` in the path,
115 /// recording `insertion.gain`.
116 ///
117 /// The caller keeps the bundle free of duplicates; see [`Bundle::contains`].
118 ///
119 /// # Panics
120 ///
121 /// Panics when `insertion.position` is greater than the path's length.
122 pub fn insert(&mut self, task: Task, insertion: Insertion)
123 where
124 Task: Clone,
125 {
126 assert!(
127 insertion.position <= self.path.len(),
128 "insertion position {} beyond the path's length {}",
129 insertion.position,
130 self.path.len()
131 );
132
133 self.path.insert(insertion.position, task.clone());
134 self.added.push((task, insertion.gain));
135 }
136
137 /// Removes every task added at bundle index `index` or later, and returns them in the
138 /// order they were added. An `index` at or past the end removes nothing.
139 ///
140 /// Use it when the agent loses the task at `index`: the gains of later tasks assumed that
141 /// task was still held.
142 pub fn release_from(&mut self, index: usize) -> Vec<Task>
143 where
144 Task: PartialEq,
145 {
146 if index >= self.added.len() {
147 return Vec::new();
148 }
149
150 let released: Vec<Task> = self.added.drain(index..).map(|(task, _)| task).collect();
151 self.path.retain(|task| !released.contains(task));
152
153 released
154 }
155
156 /// Removes every task.
157 pub fn clear(&mut self) {
158 self.added.clear();
159 self.path.clear();
160 }
161}
162
163impl<Task: PartialEq> Bundle<Task> {
164 /// Whether the bundle holds `task`.
165 #[must_use]
166 pub fn contains(&self, task: &Task) -> bool {
167 self.path.contains(task)
168 }
169
170 /// The bundle index of `task`: how many tasks were added before it; `None` when the
171 /// bundle does not hold it.
172 #[must_use]
173 pub fn index_of(&self, task: &Task) -> Option<usize> {
174 self.added.iter().position(|(held, _)| held == task)
175 }
176}
177
178impl<Task: Clone + PartialEq> Bundle<Task> {
179 /// The candidate with the highest gain on the current path that `accept` allows, with
180 /// its insertion; `None` when no candidate is feasible and accepted.
181 ///
182 /// Tasks the bundle already holds are skipped. Of equal gains, the candidate listed first
183 /// wins. `accept` is asked about each feasible task, with its gain, that would beat the
184 /// best so far; a bidding agent uses it to skip tasks it cannot outbid.
185 pub fn best_candidate<'c, V, F>(
186 &self,
187 valuation: &V,
188 candidates: &'c [Task],
189 mut accept: F,
190 ) -> Option<(&'c Task, Insertion)>
191 where
192 V: Valuation<Task> + ?Sized,
193 F: FnMut(&Task, u64) -> bool,
194 {
195 let mut best: Option<(&Task, Insertion)> = None;
196 for task in candidates {
197 if self.contains(task) {
198 continue;
199 }
200
201 let Some(insertion) = valuation.best_insertion(&self.path, task) else {
202 continue;
203 };
204
205 let beats_best = best.is_none_or(|(_, current)| insertion.gain > current.gain);
206 if beats_best && accept(task, insertion.gain) {
207 best = Some((task, insertion));
208 }
209 }
210
211 best
212 }
213
214 /// Adds the best accepted candidate, again and again, until the bundle holds `capacity`
215 /// tasks or no candidate is left; returns the number of tasks added.
216 ///
217 /// This is the greedy bundle construction of CBBA's bundle phase: each round adds the
218 /// task with the highest marginal gain on the current path (see
219 /// [`best_candidate`](Bundle::best_candidate)) at its best position.
220 pub fn extend_greedily<V, F>(
221 &mut self,
222 valuation: &V,
223 candidates: &[Task],
224 capacity: usize,
225 mut accept: F,
226 ) -> usize
227 where
228 V: Valuation<Task> + ?Sized,
229 F: FnMut(&Task, u64) -> bool,
230 {
231 let before = self.len();
232 while self.len() < capacity {
233 let Some((task, insertion)) = self.best_candidate(valuation, candidates, &mut accept)
234 else {
235 break;
236 };
237
238 self.insert(task.clone(), insertion);
239 }
240
241 self.len() - before
242 }
243}
244
245/// Unit tests for [`Bundle`].
246#[cfg(test)]
247mod tests;