Skip to main content

task_allocation/ccbba/
timed.rs

1//! CCBBA with temporal constraints: agents on timed routes, whose coupled tasks must start
2//! within limits of each other.
3//!
4//! A [`TimedAgent`] schedules its bundle on a [`Route`]. Every task it holds that depends on
5//! another task with a known start gets that task's window ([`Constraints::window`]): the
6//! route waits for the window to open and rejects a start after it closes. Messages carry
7//! the start of every winning bid, adopted whenever the conflict table takes the sender's
8//! claim. Each round, an agent also gives up tasks whose starts conflict with their
9//! partners', by the rules of Whitten, Choi, Johnson and How (2011); see the
10//! [module docs](super).
11
12use alloc::vec;
13use alloc::vec::Vec;
14use core::cell::RefCell;
15
16use super::{Agent, Constraints, Optimism};
17use crate::bundle::Bundle;
18use crate::cbba::{self, Action};
19use crate::id::{AgentId, TaskId};
20use crate::route::{Route, Timed, Visit};
21use crate::sim::Participant;
22use crate::valuation::BestInsertion;
23
24/// A route that keeps each task within a window imposed by the starts of its partners.
25#[derive(Clone, Debug)]
26pub struct Windowed<R> {
27    /// The agent's own route.
28    route: R,
29
30    /// For each task, the earliest and the latest start the partners allow; `None` for no
31    /// latest start.
32    windows: RefCell<Vec<(u64, Option<u64>)>>,
33}
34
35impl<R> Windowed<R> {
36    /// The agent's own route.
37    #[must_use]
38    pub const fn route(&self) -> &R {
39        &self.route
40    }
41}
42
43impl<R: Route> Route for Windowed<R> {
44    type Place = R::Place;
45
46    fn origin(&self) -> R::Place {
47        self.route.origin()
48    }
49
50    fn departure(&self) -> u64 {
51        self.route.departure()
52    }
53
54    fn place(&self, task: TaskId) -> R::Place {
55        self.route.place(task)
56    }
57
58    fn travel(&self, from: &R::Place, to: &R::Place) -> Option<u64> {
59        self.route.travel(from, to)
60    }
61
62    fn duration(&self, task: TaskId) -> u64 {
63        self.route.duration(task)
64    }
65
66    /// The route's own earliest start, or the partners' when later.
67    fn earliest_start(&self, task: TaskId) -> u64 {
68        let (earliest, _) = self.windows.borrow()[task.index()];
69
70        self.route.earliest_start(task).max(earliest)
71    }
72
73    /// The route's reward, or `None` when the task would start after its partners allow.
74    fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
75        let (_, latest) = self.windows.borrow()[task.index()];
76        let start = finish.saturating_sub(self.route.duration(task));
77        if latest.is_some_and(|latest| start > latest) {
78            return None;
79        }
80
81        self.route.reward(task, finish)
82    }
83}
84
85/// A [`TimedAgent`]'s broadcast: CBBA's message, plus the start of every winning bid the
86/// sender knows of.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct TimedMessage {
89    /// Winners, bids and freshness, as in CBBA.
90    claims: cbba::Message,
91
92    /// For each task, the start of its winning bid; `None` when unknown or unassigned.
93    starts: Vec<Option<u64>>,
94}
95
96impl TimedMessage {
97    /// The CBBA part: winners, bids and freshness.
98    #[must_use]
99    pub const fn claims(&self) -> &cbba::Message {
100        &self.claims
101    }
102
103    /// The start of `task`'s winning bid, as the sender knew it.
104    ///
105    /// # Panics
106    ///
107    /// Panics when `task` is not one of the message's tasks.
108    #[must_use]
109    pub fn start(&self, task: TaskId) -> Option<u64> {
110        self.starts[task.index()]
111    }
112}
113
114/// The valuation a [`TimedAgent`] bids with: its route, kept within its partners' windows,
115/// with each task inserted where it adds the most.
116type Scheduled<R> = BestInsertion<Timed<Windowed<R>>>;
117
118/// One CCBBA agent with temporal constraints, scheduling its bundle on a route.
119///
120/// # Examples
121///
122/// ```
123/// use task_allocation::ccbba::{Constraints, Optimism, TimedAgent};
124/// use task_allocation::route::{Route, rewards};
125/// use task_allocation::sim::{Network, Simulation};
126/// use task_allocation::{AgentId, TaskId};
127///
128/// /// An agent on a line at unit speed; both tasks are at position 10 and take 5.
129/// struct Line(u64);
130///
131/// impl Route for Line {
132///     type Place = u64;
133///     fn origin(&self) -> u64 { self.0 }
134///     fn place(&self, _task: TaskId) -> u64 { 10 }
135///     fn travel(&self, from: &u64, to: &u64) -> Option<u64> { Some(from.abs_diff(*to)) }
136///     fn duration(&self, _task: TaskId) -> u64 { 5 }
137///     fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
138///         rewards::deadline(10, finish, 100)
139///     }
140/// }
141///
142/// // Task 1 needs task 0, and must start 3 to 8 after it.
143/// let mut constraints = Constraints::new(2);
144/// constraints
145///     .add_timed_activity(
146///         &[TaskId(0), TaskId(1)],
147///         &[&[0, 1], &[0, 0]],
148///         &[&[Some(0), Some(-3)], &[Some(8), Some(0)]],
149///     )
150///     .unwrap();
151/// let optimism = Optimism { timeout: 5, solo_attempts: 2, any_attempts: 4 };
152///
153/// let agents = [Line(0), Line(12)]
154///     .into_iter()
155///     .enumerate()
156///     .map(|(id, line)| TimedAgent::new(AgentId(id), 2, 2, 1, line, constraints.clone(), optimism))
157///     .collect();
158/// let mut simulation = Simulation::new(agents, Network::default());
159///
160/// simulation.run_until_settled(100).expect("settles");
161/// let starts: Vec<_> = (0..2).map(|task| simulation.agents()[0].start(TaskId(task)).unwrap()).collect();
162/// assert!(starts[1] >= starts[0] + 3 && starts[1] <= starts[0] + 8);
163/// ```
164#[derive(Clone, Debug)]
165pub struct TimedAgent<R> {
166    /// The CCBBA agent, bidding with the windowed route.
167    agent: Agent<Scheduled<R>>,
168
169    /// The conflict table's action for each task of the last message, reused across
170    /// messages so receiving does not allocate.
171    actions: Vec<(TaskId, Action)>,
172}
173
174impl<R: Route> TimedAgent<R> {
175    /// Agent `id` of a team of `agents`, scheduling tasks `0..tasks` on `route` under
176    /// `constraints`, and holding at most `capacity` of them.
177    ///
178    /// # Panics
179    ///
180    /// Panics when `id` is not below `agents`, or when `constraints` cover a different
181    /// number of tasks.
182    #[must_use]
183    pub fn new(
184        id: AgentId,
185        agents: usize,
186        tasks: usize,
187        capacity: usize,
188        route: R,
189        constraints: Constraints,
190        optimism: Optimism,
191    ) -> Self {
192        let windowed = Windowed {
193            route,
194            windows: RefCell::new(vec![(0, None); tasks]),
195        };
196        let valuation = BestInsertion(Timed(windowed));
197
198        Self {
199            agent: Agent::new(
200                id,
201                agents,
202                tasks,
203                capacity,
204                valuation,
205                constraints,
206                optimism,
207            ),
208            actions: Vec::with_capacity(tasks),
209        }
210    }
211
212    /// One round: gives up tasks whose constraints fail, timing included, runs the bundle
213    /// phase within the partners' windows, and records the starts of the tasks it holds.
214    /// Returns the number of tasks added.
215    pub fn build_bundle(&mut self) -> usize {
216        self.refresh_windows();
217        let added = self.agent.build_bundle();
218        self.record_own_starts();
219
220        added
221    }
222
223    /// The message this agent broadcasts now.
224    #[must_use]
225    pub fn message(&mut self) -> TimedMessage {
226        TimedMessage {
227            claims: self.agent.message(),
228            starts: self.view_starts(),
229        }
230    }
231
232    /// The consensus phase for one message: CBBA's, adopting the sender's start for every
233    /// task whose claim it takes. Returns whether anything changed.
234    pub fn receive(&mut self, message: &TimedMessage) -> bool {
235        let actions = &mut self.actions;
236        actions.clear();
237        let Some(changed) = self
238            .agent
239            .inner
240            .receive_with_actions(&message.claims, |task, action| actions.push((task, action)))
241        else {
242            return false;
243        };
244
245        {
246            let gate = self.agent.inner.valuation();
247            let mut view = gate.view.borrow_mut();
248            for &(task, action) in &self.actions {
249                let start = &mut view.starts[task.index()];
250                match action {
251                    Action::Update => *start = message.starts.get(task.index()).copied().flatten(),
252                    Action::Reset => *start = None,
253                    Action::Leave => {}
254                }
255            }
256        }
257
258        self.agent.refresh_view();
259        self.forget_unassigned_starts();
260
261        changed
262    }
263
264    /// Whether the next round would change anything: what [`Agent::can_bid`] checks, or the
265    /// starts of the tasks this agent holds would move.
266    #[must_use]
267    pub fn can_bid(&self) -> bool {
268        self.refresh_windows();
269
270        self.agent.can_bid() || self.own_starts_would_move()
271    }
272
273    /// Computes every task's window from its opening and the starts of the tasks it depends
274    /// on, as this agent knows them, and hands them to the route.
275    fn refresh_windows(&self) {
276        let gate = self.agent.inner.valuation();
277        let view = gate.view.borrow();
278        let constraints = &gate.constraints;
279        let claims = self.agent.inner.claims();
280        let mut windows = gate.inner.0.0.windows.borrow_mut();
281
282        for (index, window) in windows.iter_mut().enumerate() {
283            let task = TaskId(index);
284            let mut earliest = i128::from(constraints.opening(task));
285            let mut latest: Option<i128> = None;
286            for other in constraints.requirements(task) {
287                let (Some(_), Some(start)) =
288                    (claims[other.index()].winner, view.starts[other.index()])
289                else {
290                    continue;
291                };
292
293                let (from, until) = constraints.window(task, other, start);
294                earliest = earliest.max(from.unwrap_or(0));
295                latest = match (latest, until) {
296                    (Some(current), Some(until)) => Some(current.min(until)),
297                    (current, until) => current.or(until),
298                };
299            }
300
301            *window = clamp_window(earliest, latest);
302        }
303    }
304
305    /// The visits of this agent's bundle on its route, within the partners' windows, or,
306    /// when the windows make the bundle infeasible, without them; `None` when even the route
307    /// alone cannot execute it.
308    fn own_visits(&self) -> Option<Vec<Visit>> {
309        let timed = &self.agent.inner.valuation().inner.0;
310        let path = self.agent.bundle().path();
311
312        timed
313            .schedule(path)
314            .or_else(|| Timed(&timed.0.route).schedule(path))
315    }
316
317    /// Records the start of every task this agent holds, and forgets starts of tasks
318    /// without a winner.
319    fn record_own_starts(&mut self) {
320        if let Some(visits) = self.own_visits() {
321            let gate = self.agent.inner.valuation();
322            let mut view = gate.view.borrow_mut();
323            for visit in visits {
324                view.starts[visit.task.index()] = Some(visit.start);
325            }
326        }
327
328        self.forget_unassigned_starts();
329    }
330
331    /// Whether recomputing the starts of the tasks this agent holds would change them.
332    fn own_starts_would_move(&self) -> bool {
333        let Some(visits) = self.own_visits() else {
334            return false;
335        };
336
337        let view = self.agent.inner.valuation().view.borrow();
338
339        visits
340            .iter()
341            .any(|visit| view.starts[visit.task.index()] != Some(visit.start))
342    }
343
344    /// Forgets the start of every task without a known winner.
345    fn forget_unassigned_starts(&self) {
346        let gate = self.agent.inner.valuation();
347        let claims = self.agent.inner.claims();
348        let mut view = gate.view.borrow_mut();
349        for (start, claim) in view.starts.iter_mut().zip(claims) {
350            if claim.winner.is_none() {
351                *start = None;
352            }
353        }
354    }
355
356    /// The start of every task's winning bid, as this agent knows it.
357    fn view_starts(&self) -> Vec<Option<u64>> {
358        self.agent.inner.valuation().view.borrow().starts.clone()
359    }
360}
361
362/// A window from bounds that may be negative: the earliest start at least zero, and a
363/// latest start before zero made infeasible.
364fn clamp_window(earliest: i128, latest: Option<i128>) -> (u64, Option<u64>) {
365    let earliest = u64::try_from(earliest.max(0)).unwrap_or(u64::MAX);
366    match latest {
367        None => (earliest, None),
368        Some(latest) if latest < 0 => (u64::MAX, Some(0)),
369        Some(latest) => (earliest, Some(u64::try_from(latest).unwrap_or(u64::MAX))),
370    }
371}
372
373impl<R> TimedAgent<R> {
374    /// This agent's identifier.
375    #[must_use]
376    pub const fn id(&self) -> AgentId {
377        self.agent.id()
378    }
379
380    /// This agent's route.
381    #[must_use]
382    pub const fn route(&self) -> &R {
383        &self.agent.valuation().0.0.route
384    }
385
386    /// The constraints this agent bids under.
387    #[must_use]
388    pub const fn constraints(&self) -> &Constraints {
389        self.agent.constraints()
390    }
391
392    /// The tasks this agent holds, with the bid it placed on each.
393    #[must_use]
394    pub const fn bundle(&self) -> &Bundle<TaskId> {
395        self.agent.bundle()
396    }
397
398    /// The winner this agent believes in for `task`; `None` when it knows of no bid.
399    ///
400    /// # Panics
401    ///
402    /// Panics when `task` is not one of this agent's tasks.
403    #[must_use]
404    pub fn winner(&self, task: TaskId) -> Option<AgentId> {
405        self.agent.winner(task)
406    }
407
408    /// The start of `task`'s winning bid, as this agent knows it.
409    ///
410    /// # Panics
411    ///
412    /// Panics when `task` is not one of this agent's tasks.
413    #[must_use]
414    pub fn start(&self, task: TaskId) -> Option<u64> {
415        self.agent.inner.valuation().view.borrow().starts[task.index()]
416    }
417}
418
419impl<R: Route> Participant for TimedAgent<R> {
420    type Message = TimedMessage;
421
422    fn id(&self) -> AgentId {
423        self.agent.id()
424    }
425
426    fn bundle(&self) -> &Bundle<TaskId> {
427        self.agent.bundle()
428    }
429
430    /// Runs a round and broadcasts the full state, starts included.
431    fn act(&mut self, _now: u64, outbox: &mut Vec<TimedMessage>) {
432        self.build_bundle();
433        outbox.push(self.message());
434    }
435
436    /// Runs the consensus phase for `message`.
437    fn receive(&mut self, _now: u64, message: &TimedMessage, _outbox: &mut Vec<TimedMessage>) {
438        TimedAgent::receive(self, message);
439    }
440
441    /// CCBBA's settled check, plus agreement on every start, among agents and in flight.
442    fn is_settled(team: &[Self], in_flight: &[&TimedMessage]) -> bool {
443        let Some(first) = team.first() else {
444            return true;
445        };
446
447        let claims = first.agent.inner.claims();
448        let starts = first.view_starts();
449
450        team.iter().all(|agent| agent.agent.inner.is_consistent())
451            && !team.iter().any(TimedAgent::can_bid)
452            && team
453                .iter()
454                .all(|agent| agent.agent.inner.claims() == claims && agent.view_starts() == starts)
455            && in_flight
456                .iter()
457                .all(|message| message.claims.claims() == claims && message.starts == starts)
458    }
459}
460
461/// Unit tests for [`TimedAgent`].
462#[cfg(test)]
463mod tests {
464    use super::{Constraints, Optimism, TimedAgent};
465    use crate::id::{AgentId, TaskId};
466    use crate::route::Route;
467
468    /// One task at position 5 on a line, worth 1 by time 100.
469    struct Point;
470
471    impl Route for Point {
472        type Place = u64;
473
474        fn origin(&self) -> u64 {
475            0
476        }
477
478        fn place(&self, _task: TaskId) -> u64 {
479            5
480        }
481
482        fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
483            Some(from.abs_diff(*to))
484        }
485
486        fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
487            (finish <= 100).then_some(1)
488        }
489    }
490
491    /// An agent reports what it holds and when, and announces it.
492    #[test]
493    fn reports_and_announces_its_starts() {
494        let optimism = Optimism {
495            timeout: 1,
496            solo_attempts: 1,
497            any_attempts: 1,
498        };
499        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, Constraints::new(1), optimism);
500        agent.build_bundle();
501        let message = agent.message();
502
503        assert_eq!(agent.id(), AgentId(0));
504        assert_eq!(agent.constraints(), &Constraints::new(1));
505        assert_eq!(agent.route().origin(), 0);
506        assert_eq!(agent.start(TaskId(0)), Some(5));
507        assert_eq!(message.start(TaskId(0)), Some(5));
508        assert_eq!(message.claims().winner(TaskId(0)), Some(AgentId(0)));
509        assert!(!agent.can_bid());
510    }
511
512    /// A task never starts before the opening of its window.
513    #[test]
514    fn openings_hold_back_the_start() {
515        let optimism = Optimism {
516            timeout: 1,
517            solo_attempts: 1,
518            any_attempts: 1,
519        };
520        let mut constraints = Constraints::new(1);
521        constraints.set_opening(TaskId(0), 20);
522        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, constraints, optimism);
523        agent.build_bundle();
524
525        assert_eq!(agent.start(TaskId(0)), Some(20));
526    }
527}