Skip to main content

task_allocation/valuation/
diminishing.rs

1//! Brute-force check that a valuation's marginal gains diminish.
2//!
3//! A valuation has *diminishing marginal gains* (DMG) when adding work never makes another
4//! task more valuable: for every path `p`, every task `k` added to it and every other task
5//! `j`, the gain of `j` after `p + k` is at most its gain after `p`. A task that was
6//! infeasible stays infeasible. CBBA relies on this to converge: without it, agents can
7//! outbid each other forever.
8
9use alloc::vec::Vec;
10use core::fmt;
11
12use super::Valuation;
13
14/// A counterexample to diminishing marginal gains: adding `added` to `path` raised the gain
15/// of `task`.
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct Violation<Task> {
18    /// The path before `added` was inserted, in execution order.
19    pub path: Vec<Task>,
20
21    /// The task whose insertion raised the gain of `task`.
22    pub added: Task,
23
24    /// The task whose gain went up.
25    pub task: Task,
26
27    /// The gain of `task` on `path`; `None` when it was infeasible.
28    pub before: Option<u64>,
29
30    /// The gain of `task` once `added` is in the path; `None` when it is infeasible.
31    pub after: Option<u64>,
32}
33
34impl<Task: fmt::Debug> fmt::Display for Violation<Task> {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(
37            f,
38            "adding {:?} to path {:?} raised the gain of {:?} from {:?} to {:?}",
39            self.added, self.path, self.task, self.before, self.after
40        )
41    }
42}
43
44impl<Task: fmt::Debug> core::error::Error for Violation<Task> {}
45
46/// Checks that `valuation` has diminishing marginal gains over `tasks`, for agents that hold
47/// at most `capacity` tasks.
48///
49/// Gains matter only on paths shorter than `capacity`, where the agent can still take a
50/// task, so only those are compared.
51///
52/// Paths are built the way allocation algorithms build them: each task goes where
53/// [`Valuation::best_insertion`] puts it. The check explores every build order, so it is
54/// meant for small task sets: about `tasks.len()! / (tasks.len() - capacity)!` paths.
55///
56/// # Errors
57///
58/// Returns the first [`Violation`] found: a path, a task added to it, and another task whose
59/// gain went up (or became feasible) as a result.
60///
61/// # Examples
62///
63/// ```
64/// use task_allocation::{Valuation, check_diminishing};
65///
66/// /// Pays for each task, but more once the agent is already busy: not diminishing.
67/// struct Eager;
68///
69/// impl Valuation<u64> for Eager {
70///     fn marginal_score(&self, path: &[u64], task: &u64) -> Option<u64> {
71///         Some(task + path.len() as u64)
72///     }
73/// }
74///
75/// let violation = check_diminishing(&Eager, &[1, 2], 2).unwrap_err();
76/// assert_eq!((violation.before, violation.after), (Some(2), Some(3)));
77/// ```
78pub fn check_diminishing<Task, V>(
79    valuation: &V,
80    tasks: &[Task],
81    capacity: usize,
82) -> Result<(), Violation<Task>>
83where
84    Task: Clone,
85    V: Valuation<Task> + ?Sized,
86{
87    let mut search = Search {
88        valuation,
89        tasks,
90        capacity,
91        path: Vec::new(),
92        used: alloc::vec![false; tasks.len()],
93    };
94
95    search.explore()
96}
97
98/// The state of the depth-first search over build orders.
99struct Search<'a, Task, V: ?Sized> {
100    /// The valuation under test.
101    valuation: &'a V,
102
103    /// The tasks paths are built from.
104    tasks: &'a [Task],
105
106    /// The longest path to explore.
107    capacity: usize,
108
109    /// The current path, in execution order.
110    path: Vec<Task>,
111
112    /// Whether each task of `tasks` is on the current path.
113    used: Vec<bool>,
114}
115
116impl<Task, V> Search<'_, Task, V>
117where
118    Task: Clone,
119    V: Valuation<Task> + ?Sized,
120{
121    /// Checks every extension of the current path by one task, then recurses into it.
122    fn explore(&mut self) -> Result<(), Violation<Task>> {
123        if self.path.len() >= self.capacity {
124            return Ok(());
125        }
126
127        for added in 0..self.tasks.len() {
128            if self.used[added] {
129                continue;
130            }
131
132            let Some(insertion) = self
133                .valuation
134                .best_insertion(&self.path, &self.tasks[added])
135            else {
136                continue;
137            };
138
139            let mut extended = self.path.clone();
140            extended.insert(insertion.position, self.tasks[added].clone());
141            if extended.len() < self.capacity {
142                self.check_extension(added, &extended)?;
143            }
144
145            self.descend(added, extended)?;
146        }
147
148        Ok(())
149    }
150
151    /// Checks that no other task gained from adding task `added`, which turned the current
152    /// path into `extended`.
153    fn check_extension(&self, added: usize, extended: &[Task]) -> Result<(), Violation<Task>> {
154        for task in 0..self.tasks.len() {
155            if task == added || self.used[task] {
156                continue;
157            }
158
159            let before = self.valuation.marginal_score(&self.path, &self.tasks[task]);
160            let after = self.valuation.marginal_score(extended, &self.tasks[task]);
161            if after > before {
162                return Err(Violation {
163                    path: self.path.clone(),
164                    added: self.tasks[added].clone(),
165                    task: self.tasks[task].clone(),
166                    before,
167                    after,
168                });
169            }
170        }
171
172        Ok(())
173    }
174
175    /// Makes `extended` the current path, explores it, and restores the current path.
176    fn descend(&mut self, added: usize, extended: Vec<Task>) -> Result<(), Violation<Task>> {
177        let previous = core::mem::replace(&mut self.path, extended);
178        self.used[added] = true;
179
180        let result = self.explore();
181
182        self.used[added] = false;
183        self.path = previous;
184
185        result
186    }
187}