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 let mut released = Vec::new();
147 self.release_from_with(index, |task| released.push(task));
148
149 released
150 }
151
152 /// Removes every task added at bundle index `index` or later, as
153 /// [`release_from`](Bundle::release_from) does, handing each to `released` in the order
154 /// they were added instead of collecting them. It does not allocate.
155 pub fn release_from_with(&mut self, index: usize, mut released: impl FnMut(Task))
156 where
157 Task: PartialEq,
158 {
159 if index >= self.added.len() {
160 return;
161 }
162
163 let dropped = &self.added[index..];
164 self.path
165 .retain(|task| !dropped.iter().any(|(held, _)| held == task));
166
167 for (task, _) in self.added.drain(index..) {
168 released(task);
169 }
170 }
171
172 /// Removes every task.
173 pub fn clear(&mut self) {
174 self.added.clear();
175 self.path.clear();
176 }
177}
178
179impl<Task: PartialEq> Bundle<Task> {
180 /// Whether the bundle holds `task`.
181 #[must_use]
182 pub fn contains(&self, task: &Task) -> bool {
183 self.path.contains(task)
184 }
185
186 /// The bundle index of `task`: how many tasks were added before it; `None` when the
187 /// bundle does not hold it.
188 #[must_use]
189 pub fn index_of(&self, task: &Task) -> Option<usize> {
190 self.added.iter().position(|(held, _)| held == task)
191 }
192}
193
194impl<Task: Clone + PartialEq> Bundle<Task> {
195 /// The candidate with the highest gain on the current path that `accept` allows, with
196 /// its insertion; `None` when no candidate is feasible and accepted.
197 ///
198 /// Tasks the bundle already holds are skipped. Of equal gains, the candidate listed first
199 /// wins. `accept` is asked about each feasible task, with its gain, that would beat the
200 /// best so far; a bidding agent uses it to skip tasks it cannot outbid.
201 pub fn best_candidate<'c, V, F>(
202 &self,
203 valuation: &V,
204 candidates: &'c [Task],
205 mut accept: F,
206 ) -> Option<(&'c Task, Insertion)>
207 where
208 V: Valuation<Task> + ?Sized,
209 F: FnMut(&Task, u64) -> bool,
210 {
211 let mut best: Option<(&Task, Insertion)> = None;
212 for task in candidates {
213 if self.contains(task) {
214 continue;
215 }
216
217 let Some(insertion) = valuation.best_insertion(&self.path, task) else {
218 continue;
219 };
220
221 let beats_best = best.is_none_or(|(_, current)| insertion.gain > current.gain);
222 if beats_best && accept(task, insertion.gain) {
223 best = Some((task, insertion));
224 }
225 }
226
227 best
228 }
229
230 /// Adds the best accepted candidate, again and again, until the bundle holds `capacity`
231 /// tasks or no candidate is left; returns the number of tasks added.
232 ///
233 /// This is the greedy bundle construction of CBBA's bundle phase: each round adds the
234 /// task with the highest marginal gain on the current path (see
235 /// [`best_candidate`](Bundle::best_candidate)) at its best position.
236 pub fn extend_greedily<V, F>(
237 &mut self,
238 valuation: &V,
239 candidates: &[Task],
240 capacity: usize,
241 mut accept: F,
242 ) -> usize
243 where
244 V: Valuation<Task> + ?Sized,
245 F: FnMut(&Task, u64) -> bool,
246 {
247 let before = self.len();
248 while self.len() < capacity {
249 let Some((task, insertion)) = self.best_candidate(valuation, candidates, &mut accept)
250 else {
251 break;
252 };
253
254 self.insert(task.clone(), insertion);
255 }
256
257 self.len() - before
258 }
259}
260
261/// Unit tests for [`Bundle`].
262#[cfg(test)]
263mod tests;