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. A path whose
7//! own tasks break the timing limits between them is rejected too, so one agent never takes
8//! two tasks that must start together.
9//!
10//! Messages carry the start of every winning bid, adopted whenever the conflict table takes
11//! the sender's claim. Each round, an agent also gives up tasks whose starts conflict with
12//! their partners', by the rules of Whitten, Choi, Johnson and How (2011); see the
13//! [module docs](super).
14
15use alloc::vec;
16use alloc::vec::Vec;
17use core::cell::RefCell;
18
19use super::{Agent, Constraints, Optimism};
20use crate::bundle::Bundle;
21use crate::cbba::{self, Action};
22use crate::id::{AgentId, TaskId};
23use crate::route::{Route, Timed, Visit};
24use crate::sim::Participant;
25use crate::valuation::{BestInsertion, PathScore};
26
27/// A route that keeps each task within a window imposed by the starts of its partners.
28#[derive(Clone, Debug)]
29pub struct Windowed<R> {
30    /// The agent's own route.
31    route: R,
32
33    /// For each task, the earliest and the latest start the partners allow; `None` for no
34    /// latest start.
35    windows: RefCell<Vec<(u64, Option<u64>)>>,
36}
37
38impl<R> Windowed<R> {
39    /// The agent's own route.
40    #[must_use]
41    pub const fn route(&self) -> &R {
42        &self.route
43    }
44}
45
46impl<R: Route> Route for Windowed<R> {
47    type Place = R::Place;
48
49    fn origin(&self) -> R::Place {
50        self.route.origin()
51    }
52
53    fn departure(&self) -> u64 {
54        self.route.departure()
55    }
56
57    fn place(&self, task: TaskId) -> R::Place {
58        self.route.place(task)
59    }
60
61    fn travel(&self, from: &R::Place, to: &R::Place) -> Option<u64> {
62        self.route.travel(from, to)
63    }
64
65    fn duration(&self, task: TaskId) -> u64 {
66        self.route.duration(task)
67    }
68
69    /// The route's own earliest start, or the partners' when later.
70    fn earliest_start(&self, task: TaskId) -> u64 {
71        let (earliest, _) = self.windows.borrow()[task.index()];
72
73        self.route.earliest_start(task).max(earliest)
74    }
75
76    /// The route's reward, or `None` when the task would start after its partners allow.
77    fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
78        let (_, latest) = self.windows.borrow()[task.index()];
79        let start = finish.saturating_sub(self.route.duration(task));
80        if latest.is_some_and(|latest| start > latest) {
81            return None;
82        }
83
84        self.route.reward(task, finish)
85    }
86}
87
88/// A [`TimedAgent`]'s broadcast: CBBA's message, plus the start of every winning bid the
89/// sender knows of.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct TimedMessage {
92    /// Winners, bids and freshness, as in CBBA.
93    claims: cbba::Message,
94
95    /// For each task, the start of its winning bid; `None` when unknown or unassigned.
96    starts: Vec<Option<u64>>,
97}
98
99impl TimedMessage {
100    /// The CBBA part: winners, bids and freshness.
101    #[must_use]
102    pub const fn claims(&self) -> &cbba::Message {
103        &self.claims
104    }
105
106    /// The start of `task`'s winning bid, as the sender knew it.
107    ///
108    /// # Panics
109    ///
110    /// Panics when `task` is not one of the message's tasks.
111    #[must_use]
112    pub fn start(&self, task: TaskId) -> Option<u64> {
113        self.starts[task.index()]
114    }
115}
116
117/// The valuation a [`TimedAgent`] bids with: its route, kept within its partners' windows
118/// and the timing limits among its own tasks, with each task inserted where it adds the
119/// most.
120type Scheduled<R> = BestInsertion<Coordinated<R>>;
121
122/// A timed route that also keeps the timing limits among the tasks of one path.
123///
124/// The partners' windows only cover tasks other agents hold. Within one bundle phase, a
125/// task this agent has just added would not narrow the window of the next one, so without
126/// this check one agent could take two tasks that must start together, at different
127/// starts, and give one up again in every round.
128#[derive(Clone, Debug)]
129struct Coordinated<R> {
130    /// The route within the partners' windows.
131    timed: Timed<Windowed<R>>,
132
133    /// The constraints whose timing limits the path must keep.
134    constraints: Constraints,
135}
136
137impl<R: Route> Coordinated<R> {
138    /// Whether `path`, with `task` if given, holds two tasks of one activity, whose starts
139    /// then need checking against each other.
140    fn links(&self, path: &[TaskId], task: Option<TaskId>) -> bool {
141        let tasks = || path.iter().copied().chain(task);
142
143        tasks().any(|member| {
144            self.constraints
145                .activity_tasks(member)
146                .any(|partner| tasks().any(|other| other == partner))
147        })
148    }
149}
150
151impl<R: Route> PathScore<TaskId> for Coordinated<R> {
152    /// The timed route's score, or `None` when two tasks of `path` start outside the timing
153    /// limits between them.
154    fn path_score(&self, path: &[TaskId]) -> Option<u64> {
155        if !self.links(path, None) {
156            return self.timed.path_score(path);
157        }
158
159        let visits = self.timed.schedule(path)?;
160        let agree = visits.iter().enumerate().all(|(index, visit)| {
161            visits[index + 1..].iter().all(|other| {
162                self.constraints
163                    .starts_agree(visit.task, visit.start, other.task, other.start)
164            })
165        });
166
167        agree.then(|| {
168            visits
169                .iter()
170                .fold(0, |total: u64, visit| total.saturating_add(visit.reward))
171        })
172    }
173
174    /// The timed route's scores, without building each candidate path, unless `task`
175    /// shares an activity with a task of `path`.
176    fn insertion_scores(
177        &self,
178        path: &[TaskId],
179        task: &TaskId,
180        each: &mut dyn FnMut(usize, Option<u64>),
181    ) {
182        if !self.links(path, Some(*task)) {
183            return self.timed.insertion_scores(path, task, each);
184        }
185
186        let mut candidate = Vec::with_capacity(path.len() + 1);
187        candidate.extend_from_slice(path);
188        candidate.push(*task);
189        for position in (0..=path.len()).rev() {
190            if position < path.len() {
191                candidate.swap(position, position + 1);
192            }
193
194            each(position, self.path_score(&candidate));
195        }
196    }
197}
198
199/// One CCBBA agent with temporal constraints, scheduling its bundle on a route.
200///
201/// # Examples
202///
203/// ```
204/// use task_allocation::ccbba::{Constraints, Optimism, TimedAgent};
205/// use task_allocation::route::{Route, rewards};
206/// use task_allocation::sim::{Network, Simulation};
207/// use task_allocation::{AgentId, TaskId};
208///
209/// /// An agent on a line at unit speed; both tasks are at position 10 and take 5.
210/// struct Line(u64);
211///
212/// impl Route for Line {
213///     type Place = u64;
214///     fn origin(&self) -> u64 { self.0 }
215///     fn place(&self, _task: TaskId) -> u64 { 10 }
216///     fn travel(&self, from: &u64, to: &u64) -> Option<u64> { Some(from.abs_diff(*to)) }
217///     fn duration(&self, _task: TaskId) -> u64 { 5 }
218///     fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
219///         rewards::deadline(10, finish, 100)
220///     }
221/// }
222///
223/// // Task 1 needs task 0, and must start 3 to 8 after it.
224/// let mut constraints = Constraints::new(2);
225/// constraints
226///     .add_timed_activity(
227///         &[TaskId(0), TaskId(1)],
228///         &[&[0, 1], &[0, 0]],
229///         &[&[Some(0), Some(-3)], &[Some(8), Some(0)]],
230///     )
231///     .unwrap();
232/// let optimism = Optimism { timeout: 5, solo_attempts: 2, any_attempts: 4 };
233///
234/// let agents = [Line(0), Line(12)]
235///     .into_iter()
236///     .enumerate()
237///     .map(|(id, line)| TimedAgent::new(AgentId(id), 2, 2, 1, line, constraints.clone(), optimism))
238///     .collect();
239/// let mut simulation = Simulation::new(agents, Network::default());
240///
241/// simulation.run_until_settled(100).expect("settles");
242/// let starts: Vec<_> = (0..2).map(|task| simulation.agents()[0].start(TaskId(task)).unwrap()).collect();
243/// assert!(starts[1] >= starts[0] + 3 && starts[1] <= starts[0] + 8);
244/// ```
245#[derive(Clone, Debug)]
246pub struct TimedAgent<R> {
247    /// The CCBBA agent, bidding with the windowed route.
248    agent: Agent<Scheduled<R>>,
249
250    /// The conflict table's action for each task of the last message, reused across
251    /// messages so receiving does not allocate.
252    actions: Vec<(TaskId, Action)>,
253}
254
255impl<R: Route> TimedAgent<R> {
256    /// Agent `id` of a team of `agents`, scheduling tasks `0..tasks` on `route` under
257    /// `constraints`, and holding at most `capacity` of them.
258    ///
259    /// # Panics
260    ///
261    /// Panics when `id` is not below `agents`, or when `constraints` cover a different
262    /// number of tasks.
263    #[must_use]
264    pub fn new(
265        id: AgentId,
266        agents: usize,
267        tasks: usize,
268        capacity: usize,
269        route: R,
270        constraints: Constraints,
271        optimism: Optimism,
272    ) -> Self {
273        let windowed = Windowed {
274            route,
275            windows: RefCell::new(vec![(0, None); tasks]),
276        };
277        let valuation = BestInsertion(Coordinated {
278            timed: Timed(windowed),
279            constraints: constraints.clone(),
280        });
281
282        Self {
283            agent: Agent::new(
284                id,
285                agents,
286                tasks,
287                capacity,
288                valuation,
289                constraints,
290                optimism,
291            ),
292            actions: Vec::with_capacity(tasks),
293        }
294    }
295
296    /// One round: gives up tasks whose constraints fail, timing included, runs the bundle
297    /// phase within the partners' windows, and records the starts of the tasks it holds.
298    /// Returns the number of tasks added.
299    pub fn build_bundle(&mut self) -> usize {
300        self.refresh_windows();
301        let added = self.agent.build_bundle();
302        self.record_own_starts();
303
304        added
305    }
306
307    /// The message this agent broadcasts now.
308    #[must_use]
309    pub fn message(&mut self) -> TimedMessage {
310        TimedMessage {
311            claims: self.agent.message(),
312            starts: self.view_starts(),
313        }
314    }
315
316    /// The consensus phase for one message: CBBA's, adopting the sender's start for every
317    /// task whose claim it takes. Returns whether anything changed.
318    pub fn receive(&mut self, message: &TimedMessage) -> bool {
319        let actions = &mut self.actions;
320        actions.clear();
321        let Some(changed) = self
322            .agent
323            .inner
324            .receive_with_actions(&message.claims, |task, action| actions.push((task, action)))
325        else {
326            return false;
327        };
328
329        {
330            let gate = self.agent.inner.valuation();
331            let mut view = gate.view.borrow_mut();
332            for &(task, action) in &self.actions {
333                let start = &mut view.starts[task.index()];
334                match action {
335                    Action::Update => *start = message.starts.get(task.index()).copied().flatten(),
336                    Action::Reset => *start = None,
337                    Action::Leave => {}
338                }
339            }
340        }
341
342        self.agent.refresh_view();
343        self.forget_unassigned_starts();
344
345        changed
346    }
347
348    /// Whether the next round would change anything: what [`Agent::can_bid`] checks, or the
349    /// starts of the tasks this agent holds would move.
350    #[must_use]
351    pub fn can_bid(&self) -> bool {
352        self.refresh_windows();
353
354        self.agent.can_bid() || self.own_starts_would_move()
355    }
356
357    /// Computes every task's window from its opening and the starts of the tasks it depends
358    /// on, as this agent knows them, and hands them to the route.
359    fn refresh_windows(&self) {
360        let gate = self.agent.inner.valuation();
361        let view = gate.view.borrow();
362        let constraints = &gate.constraints;
363        let claims = self.agent.inner.claims();
364        let mut windows = gate.inner.0.timed.0.windows.borrow_mut();
365
366        for (index, window) in windows.iter_mut().enumerate() {
367            let task = TaskId(index);
368            let mut earliest = i128::from(constraints.opening(task));
369            let mut latest: Option<i128> = None;
370            for other in constraints.requirements(task) {
371                let (Some(_), Some(start)) =
372                    (claims[other.index()].winner, view.starts[other.index()])
373                else {
374                    continue;
375                };
376
377                let (from, until) = constraints.window(task, other, start);
378                earliest = earliest.max(from.unwrap_or(0));
379                latest = match (latest, until) {
380                    (Some(current), Some(until)) => Some(current.min(until)),
381                    (current, until) => current.or(until),
382                };
383            }
384
385            *window = clamp_window(earliest, latest);
386        }
387    }
388
389    /// The visits of this agent's bundle on its route, within the partners' windows, or,
390    /// when the windows make the bundle infeasible, without them; `None` when even the route
391    /// alone cannot execute it.
392    fn own_visits(&self) -> Option<Vec<Visit>> {
393        let timed = &self.agent.inner.valuation().inner.0.timed;
394        let path = self.agent.bundle().path();
395
396        timed
397            .schedule(path)
398            .or_else(|| Timed(&timed.0.route).schedule(path))
399    }
400
401    /// Records the start of every task this agent holds, and forgets starts of tasks
402    /// without a winner.
403    fn record_own_starts(&mut self) {
404        if let Some(visits) = self.own_visits() {
405            let gate = self.agent.inner.valuation();
406            let mut view = gate.view.borrow_mut();
407            for visit in visits {
408                view.starts[visit.task.index()] = Some(visit.start);
409            }
410        }
411
412        self.forget_unassigned_starts();
413    }
414
415    /// Whether recomputing the starts of the tasks this agent holds would change them.
416    fn own_starts_would_move(&self) -> bool {
417        let Some(visits) = self.own_visits() else {
418            return false;
419        };
420
421        let view = self.agent.inner.valuation().view.borrow();
422
423        visits
424            .iter()
425            .any(|visit| view.starts[visit.task.index()] != Some(visit.start))
426    }
427
428    /// Forgets the start of every task without a known winner.
429    fn forget_unassigned_starts(&self) {
430        let gate = self.agent.inner.valuation();
431        let claims = self.agent.inner.claims();
432        let mut view = gate.view.borrow_mut();
433        for (start, claim) in view.starts.iter_mut().zip(claims) {
434            if claim.winner.is_none() {
435                *start = None;
436            }
437        }
438    }
439
440    /// The start of every task's winning bid, as this agent knows it.
441    fn view_starts(&self) -> Vec<Option<u64>> {
442        self.agent.inner.valuation().view.borrow().starts.clone()
443    }
444}
445
446/// A window from bounds that may be negative: the earliest start at least zero, and a
447/// latest start before zero made infeasible.
448fn clamp_window(earliest: i128, latest: Option<i128>) -> (u64, Option<u64>) {
449    let earliest = u64::try_from(earliest.max(0)).unwrap_or(u64::MAX);
450    match latest {
451        None => (earliest, None),
452        Some(latest) if latest < 0 => (u64::MAX, Some(0)),
453        Some(latest) => (earliest, Some(u64::try_from(latest).unwrap_or(u64::MAX))),
454    }
455}
456
457impl<R> TimedAgent<R> {
458    /// This agent's identifier.
459    #[must_use]
460    pub const fn id(&self) -> AgentId {
461        self.agent.id()
462    }
463
464    /// This agent's route.
465    #[must_use]
466    pub const fn route(&self) -> &R {
467        &self.agent.valuation().0.timed.0.route
468    }
469
470    /// The constraints this agent bids under.
471    #[must_use]
472    pub const fn constraints(&self) -> &Constraints {
473        self.agent.constraints()
474    }
475
476    /// The tasks this agent holds, with the bid it placed on each.
477    #[must_use]
478    pub const fn bundle(&self) -> &Bundle<TaskId> {
479        self.agent.bundle()
480    }
481
482    /// The winner this agent believes in for `task`; `None` when it knows of no bid.
483    ///
484    /// # Panics
485    ///
486    /// Panics when `task` is not one of this agent's tasks.
487    #[must_use]
488    pub fn winner(&self, task: TaskId) -> Option<AgentId> {
489        self.agent.winner(task)
490    }
491
492    /// The start of `task`'s winning bid, as this agent knows it.
493    ///
494    /// # Panics
495    ///
496    /// Panics when `task` is not one of this agent's tasks.
497    #[must_use]
498    pub fn start(&self, task: TaskId) -> Option<u64> {
499        self.agent.inner.valuation().view.borrow().starts[task.index()]
500    }
501}
502
503impl<R: Route> Participant for TimedAgent<R> {
504    type Message = TimedMessage;
505
506    fn id(&self) -> AgentId {
507        self.agent.id()
508    }
509
510    fn bundle(&self) -> &Bundle<TaskId> {
511        self.agent.bundle()
512    }
513
514    /// Runs a round and broadcasts the full state, starts included.
515    fn act(&mut self, _now: u64, outbox: &mut Vec<TimedMessage>) {
516        self.build_bundle();
517        outbox.push(self.message());
518    }
519
520    /// Runs the consensus phase for `message`.
521    fn receive(
522        &mut self,
523        _now: u64,
524        message: &TimedMessage,
525        _outbox: &mut Vec<TimedMessage>,
526    ) -> bool {
527        TimedAgent::receive(self, message)
528    }
529
530    /// CBBA's message, then every task's start, each a tag and a time.
531    fn message_bytes(message: &TimedMessage) -> u64 {
532        let starts = u64::try_from(message.starts.len()).unwrap_or(u64::MAX);
533
534        message.claims.bytes() + 4 + 9 * starts
535    }
536
537    /// CCBBA's settled check, plus agreement on every start, among agents and in flight.
538    fn is_settled(team: &[Self], in_flight: &[&TimedMessage]) -> bool {
539        let Some(first) = team.first() else {
540            return true;
541        };
542
543        let claims = first.agent.inner.claims();
544        let starts = first.view_starts();
545
546        team.iter().all(|agent| agent.agent.inner.is_consistent())
547            && !team.iter().any(TimedAgent::can_bid)
548            && team
549                .iter()
550                .all(|agent| agent.agent.inner.claims() == claims && agent.view_starts() == starts)
551            && in_flight
552                .iter()
553                .all(|message| message.claims.claims() == claims && message.starts == starts)
554    }
555}
556
557/// Unit tests for [`TimedAgent`].
558#[cfg(test)]
559mod tests {
560    use alloc::vec;
561    use core::cell::RefCell;
562
563    use super::{Constraints, Coordinated, Optimism, TimedAgent, Windowed};
564    use crate::id::{AgentId, TaskId};
565    use crate::route::{Route, Timed};
566    use crate::valuation::PathScore;
567
568    /// One task at position 5 on a line, worth 1 by time 100.
569    struct Point;
570
571    impl Route for Point {
572        type Place = u64;
573
574        fn origin(&self) -> u64 {
575            0
576        }
577
578        fn place(&self, _task: TaskId) -> u64 {
579            5
580        }
581
582        fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
583            Some(from.abs_diff(*to))
584        }
585
586        fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
587            (finish <= 100).then_some(1)
588        }
589    }
590
591    /// An agent reports what it holds and when, and announces it.
592    #[test]
593    fn reports_and_announces_its_starts() {
594        let optimism = Optimism {
595            timeout: 1,
596            solo_attempts: 1,
597            any_attempts: 1,
598        };
599        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, Constraints::new(1), optimism);
600        agent.build_bundle();
601        let message = agent.message();
602
603        assert_eq!(agent.id(), AgentId(0));
604        assert_eq!(agent.constraints(), &Constraints::new(1));
605        assert_eq!(agent.route().origin(), 0);
606        assert_eq!(agent.start(TaskId(0)), Some(5));
607        assert_eq!(message.start(TaskId(0)), Some(5));
608        assert_eq!(message.claims().winner(TaskId(0)), Some(AgentId(0)));
609        assert!(!agent.can_bid());
610    }
611
612    /// A task never starts before the opening of its window.
613    #[test]
614    fn openings_hold_back_the_start() {
615        let optimism = Optimism {
616            timeout: 1,
617            solo_attempts: 1,
618            any_attempts: 1,
619        };
620        let mut constraints = Constraints::new(1);
621        constraints.set_opening(TaskId(0), 20);
622        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, constraints, optimism);
623        agent.build_bundle();
624
625        assert_eq!(agent.start(TaskId(0)), Some(20));
626    }
627
628    /// [`Point`]'s task, taking 4 to do.
629    struct Busy;
630
631    impl Route for Busy {
632        type Place = u64;
633
634        fn origin(&self) -> u64 {
635            Point.origin()
636        }
637
638        fn place(&self, task: TaskId) -> u64 {
639            Point.place(task)
640        }
641
642        fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
643            Point.travel(from, to)
644        }
645
646        fn duration(&self, _task: TaskId) -> u64 {
647            4
648        }
649
650        fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
651            Point.reward(task, finish)
652        }
653    }
654
655    /// One agent cannot do two tasks that must start together, since it does them one
656    /// after the other; either alone, or both with room between them, is fine.
657    #[test]
658    fn own_tasks_keep_their_timing_limits() {
659        let coordinated = |limit: i64| {
660            let mut constraints = Constraints::new(2);
661            constraints
662                .add_timed_activity(
663                    &[TaskId(0), TaskId(1)],
664                    &[&[0, 1], &[1, 0]],
665                    &[&[Some(0), Some(limit)], &[Some(limit), Some(0)]],
666                )
667                .expect("a well-formed pair");
668
669            Coordinated {
670                timed: Timed(Windowed {
671                    route: Busy,
672                    windows: RefCell::new(vec![(0, None); 2]),
673                }),
674                constraints,
675            }
676        };
677
678        let together = coordinated(0);
679        assert_eq!(together.path_score(&[TaskId(0)]), Some(1));
680        assert_eq!(together.path_score(&[TaskId(0), TaskId(1)]), None);
681        assert_eq!(coordinated(4).path_score(&[TaskId(0), TaskId(1)]), Some(2));
682    }
683}