Skip to main content

multiobjective_search/
sip.rs

1//! SIP-MOSP: asynchronous parallel exact multi-objective search with
2//! versioned frontier snapshots and indexed dominance pruning.
3//!
4//! Xu, Zhang, Qian, Liu, Wu, Tang: "Asynchronous Parallel Search for Exact
5//! Multi-Objective Shortest Paths with Versioned Frontier Snapshots and
6//! Indexed Dominance Pruning", arXiv 2609.11944, 2026.
7//!
8//! *Search workers* expand labels from private best-first queues, each
9//! under its own cyclic objective order, and prune the children against
10//! published, immutable snapshots of the endpoint's and the goals'
11//! frontiers. A surviving child goes to the *update worker* that owns its
12//! endpoint (one owner per state, by hash), or to the single *goal worker*.
13//! An owner alone modifies the exact ("canonical") frontier of its states:
14//! it re-checks the candidate unless the snapshot it was checked against
15//! is still current, inserts it, publishes the next snapshot version and
16//! hands the label to the less loaded of two search workers. Snapshots are
17//! a lexicographically sorted, indexed base ([`IndexedFront`]) plus a short
18//! delta of recent additions, so most publications share the base.
19//!
20//! ```mermaid
21//! graph LR
22//!     sw["search workers<br/>(private queues)"] -- "child, snapshot version" --> uw["update worker<br/>owning the endpoint"]
23//!     sw -- "goal child" --> gw[goal worker]
24//!     uw -- "admitted label" --> sw
25//!     uw -. publish .-> snap[("snapshots<br/>base + delta + index")]
26//!     gw -. publish .-> snap
27//!     snap -. read .-> sw
28//! ```
29//!
30//! The result is the exact Pareto-optimal front whatever the thread timing
31//! (the paper's Theorem 1); which path represents a cost vector may
32//! differ between runs.
33
34use alloc::collections::{BTreeMap, BinaryHeap};
35use alloc::sync::Arc;
36use alloc::vec::Vec;
37use core::cmp::{Ordering, Reverse};
38use core::hash::{Hash, Hasher};
39use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering as Atomic};
40use std::collections::HashMap;
41use std::hash::DefaultHasher;
42use std::sync::{Condvar, Mutex, RwLock};
43
44use search_core::{Cost, Heuristic};
45
46use crate::cost::add;
47use crate::graph::Graph;
48use crate::output::{Output, Solution, Stats};
49use crate::pareto::{Front, FrontIndex, IndexedFront};
50
51/// Worker counts, the snapshot index and its thresholds for [`sip_mosp`].
52///
53/// The thresholds only decide when a snapshot is consolidated and how its
54/// base is summarized; they never change the answer.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct SipConfig {
57    /// Search workers, at least 1.
58    pub search_workers: usize,
59    /// Update workers for non-goal states, at least 1. A goal worker runs
60    /// in addition.
61    pub update_workers: usize,
62    /// The index over snapshot bases: [`FrontIndex::Blocks`] is SIP-MOSP-BM,
63    /// [`FrontIndex::Tree`] SIP-MOSP-ST.
64    pub index: FrontIndex,
65    /// Frontiers smaller than this are published as an unindexed base only
66    /// (the paper's `θ_I`). Default 64.
67    pub index_threshold: usize,
68    /// The delta is folded into a rebuilt base once it holds
69    /// `max(delta_min, |F| / delta_divisor)` vectors (the paper's adaptive
70    /// `θ_Δ(|F|)`). Default 8.
71    pub delta_min: usize,
72    /// See [`SipConfig::delta_min`]; at least 1. Default 8.
73    pub delta_divisor: usize,
74    /// Vectors per block of [`FrontIndex::Blocks`]; at least 1. Default 16.
75    pub block_size: usize,
76}
77
78impl SipConfig {
79    /// Two search and two update workers, the block-minimum index, and the
80    /// default thresholds.
81    pub const DEFAULT: Self = Self {
82        search_workers: 2,
83        update_workers: 2,
84        index: FrontIndex::Blocks,
85        index_threshold: 64,
86        delta_min: 8,
87        delta_divisor: 8,
88        block_size: 16,
89    };
90
91    /// The delta capacity for a frontier of `frontier` vectors.
92    fn delta_capacity(&self, frontier: usize) -> usize {
93        (frontier / self.delta_divisor).max(self.delta_min)
94    }
95}
96
97impl Default for SipConfig {
98    /// [`SipConfig::DEFAULT`].
99    fn default() -> Self {
100        Self::DEFAULT
101    }
102}
103
104/// SIP-MOSP: finds one path for every Pareto-optimal cost vector from
105/// `start` to a state that satisfies `is_goal`, with one thread per search
106/// and update worker plus a goal worker.
107///
108/// Requirements, not checked at run time:
109///
110/// - edge costs are non-negative;
111/// - `heuristic` is admissible in every objective and zero on every goal
112///   (the paper uses exact per-objective distances, which are
113///   consistent). Each search worker uses its own clone.
114///
115/// Solutions are sorted lexicographically, one per Pareto-optimal cost
116/// vector; the same vectors as [`namoa_star`](crate::namoa_star) in every
117/// run. Goal states are not expanded.
118///
119/// # Panics
120///
121/// Panics if a worker count, `delta_divisor` or `block_size` is zero, or if a
122/// worker thread panics.
123///
124/// # Examples
125///
126/// ```
127/// use multiobjective_search::{Graph, SipConfig, ZeroHeuristic, namoa_star, sip_mosp};
128///
129/// /// A small diamond with three objectives.
130/// struct Diamond;
131///
132/// impl Graph for Diamond {
133///     type State = u8;
134///     type Weight = [u32; 3];
135///
136///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
137///         match state {
138///             0 => out.extend([(1, [1, 2, 3]), (2, [3, 2, 1]), (3, [5, 5, 5])]),
139///             1 | 2 => out.push((3, [1, 1, 1])),
140///             _ => {}
141///         }
142///     }
143/// }
144///
145/// let out = sip_mosp(&Diamond, ZeroHeuristic, 0, |s| *s == 3, SipConfig::default());
146/// let exact = namoa_star(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
147/// let costs = |o: &multiobjective_search::Output<u8, [u32; 3]>| {
148///     o.solutions.iter().map(|s| s.cost).collect::<Vec<_>>()
149/// };
150/// assert_eq!(costs(&out), costs(&exact));
151/// ```
152pub fn sip_mosp<G, H, C, P, const N: usize>(
153    graph: &G,
154    mut heuristic: H,
155    start: G::State,
156    is_goal: P,
157    config: SipConfig,
158) -> Output<G::State, [C; N]>
159where
160    G: Graph<Weight = [C; N]> + Sync,
161    G::State: Hash + Send + Sync,
162    H: Heuristic<G::State, [C; N]> + Clone + Send,
163    C: Cost + Send + Sync,
164    P: Fn(&G::State) -> bool + Sync,
165{
166    assert!(
167        config.search_workers > 0 && config.update_workers > 0,
168        "SIP-MOSP needs at least one search and one update worker"
169    );
170    assert!(
171        config.delta_divisor > 0 && config.block_size > 0,
172        "the delta divisor and the block size must be positive"
173    );
174
175    let Some(h) = heuristic.estimate(&start) else {
176        return Output {
177            solutions: Vec::new(),
178            stats: Stats::default(),
179        };
180    };
181
182    let shared = Shared::new(config);
183    let start_label = Arc::new(Label {
184        state: start,
185        g: [C::ZERO; N],
186        f: h,
187        parent: None,
188        seen: 0,
189    });
190    shared.generated.fetch_add(1, Atomic::Relaxed);
191
192    let goal_labels = std::thread::scope(|scope| {
193        for r in 0..config.search_workers {
194            let (shared, heuristic, is_goal) = (&shared, heuristic.clone(), &is_goal);
195            scope.spawn(move || search_worker(shared, graph, heuristic, is_goal, r));
196        }
197
198        for p in 0..config.update_workers {
199            let shared = &shared;
200            scope.spawn(move || update_worker(shared, p));
201        }
202
203        let goal = scope.spawn(|| goal_worker(&shared));
204        shared.route(start_label, &is_goal);
205
206        goal.join().expect("the goal worker panicked")
207    });
208
209    let stats = Stats {
210        expanded: shared.expanded.load(Atomic::Relaxed),
211        generated: shared.generated.load(Atomic::Relaxed),
212    };
213
214    Output {
215        solutions: goal_labels
216            .into_iter()
217            .map(|label| rebuild(&label))
218            .collect(),
219        stats,
220    }
221}
222
223/// A label: one concrete path, shared by its children through `parent`.
224struct Label<S, C, const N: usize> {
225    /// The state the path ends in.
226    state: S,
227    /// Cost of the path.
228    g: [C; N],
229    /// `g + h`.
230    f: [C; N],
231    /// The path without its last edge; `None` for the start.
232    parent: Option<Arc<Label<S, C, N>>>,
233    /// Version of the endpoint's (or, for a goal, the goal) snapshot the
234    /// label was checked against when generated.
235    seen: u64,
236}
237
238/// A label in a private queue, ordered by `key` and then arrival.
239struct Entry<S, C, const N: usize> {
240    /// `f` under the worker's objective order.
241    key: [C; N],
242    /// Arrival number, for a deterministic order among equal keys.
243    seq: usize,
244    /// The label.
245    label: Arc<Label<S, C, N>>,
246}
247
248impl<S, C: Ord, const N: usize> PartialEq for Entry<S, C, N> {
249    fn eq(&self, other: &Self) -> bool {
250        self.cmp(other) == Ordering::Equal
251    }
252}
253
254impl<S, C: Ord, const N: usize> Eq for Entry<S, C, N> {}
255
256impl<S, C: Ord, const N: usize> PartialOrd for Entry<S, C, N> {
257    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
258        Some(self.cmp(other))
259    }
260}
261
262impl<S, C: Ord, const N: usize> Ord for Entry<S, C, N> {
263    fn cmp(&self, other: &Self) -> Ordering {
264        (&self.key, self.seq).cmp(&(&other.key, other.seq))
265    }
266}
267
268/// An immutable published frontier: the indexed base plus the recent
269/// additions (`S_v^k = (B, Δ, I, k)`).
270struct Snapshot<C, const N: usize> {
271    /// The consolidated, indexed base, shared between versions.
272    base: Arc<IndexedFront<C, N>>,
273    /// Vectors added since the base was built.
274    delta: Vec<[C; N]>,
275    /// Component-wise minimum of `delta`; `None` when it is empty.
276    delta_min: Option<[C; N]>,
277    /// The version `k`, counted per frontier from 0.
278    version: u64,
279}
280
281impl<C: Cost, const N: usize> Snapshot<C, N> {
282    /// The empty snapshot, version 0.
283    fn empty() -> Self {
284        Self {
285            base: Arc::new(IndexedFront::new(Vec::new(), FrontIndex::None)),
286            delta: Vec::new(),
287            delta_min: None,
288            version: 0,
289        }
290    }
291
292    /// `SnapshotDominates` (Algorithm 4): the delta first, guarded by its
293    /// minimum, then the base through its index.
294    fn dominates(&self, q: &[C; N]) -> bool {
295        let below = |p: &[C; N]| p.iter().zip(q).all(|(a, b)| a <= b);
296        if self.delta_min.as_ref().is_some_and(below) && self.delta.iter().any(below) {
297            return true;
298        }
299
300        self.base.weakly_dominates(q)
301    }
302
303    /// The next version after admitting `g` into `front` (lines 13 to 24
304    /// of Algorithm 3): a fresh unindexed base for a small frontier, a
305    /// rebuilt indexed base when the delta is full or the frontier just
306    /// outgrew the threshold, and otherwise the shared base with `g`
307    /// appended to the delta.
308    fn next(&self, front: &Front<C, N>, g: [C; N], config: &SipConfig) -> Self {
309        let version = self.version + 1;
310        let rebuild = |index| Self {
311            base: Arc::new(IndexedFront::with_block_size(
312                front.as_slice().to_vec(),
313                index,
314                config.block_size,
315            )),
316            delta: Vec::new(),
317            delta_min: None,
318            version,
319        };
320
321        if front.len() < config.index_threshold {
322            return rebuild(FrontIndex::None);
323        }
324
325        let unindexed = self.base.len() < config.index_threshold;
326        if unindexed || self.delta.len() + 1 >= config.delta_capacity(front.len()) {
327            return rebuild(config.index);
328        }
329
330        let mut delta = self.delta.clone();
331        delta.push(g);
332        let delta_min = Some(match self.delta_min {
333            Some(m) => core::array::from_fn(|i| m[i].min(g[i])),
334            None => g,
335        });
336
337        Self {
338            base: Arc::clone(&self.base),
339            delta,
340            delta_min,
341            version,
342        }
343    }
344}
345
346/// A worker's incoming queue: many producers, one consumer.
347struct Inbox<T> {
348    /// Arrivals not yet moved into the worker's private queue.
349    items: Mutex<Vec<T>>,
350    /// Signalled on every arrival and on termination.
351    ready: Condvar,
352    /// Labels sent to this worker and not yet processed; the search
353    /// workers' load for the power-of-two-choices placement.
354    load: AtomicUsize,
355}
356
357impl<T> Inbox<T> {
358    /// An empty inbox.
359    fn new() -> Self {
360        Self {
361            items: Mutex::new(Vec::new()),
362            ready: Condvar::new(),
363            load: AtomicUsize::new(0),
364        }
365    }
366}
367
368/// A published-snapshot table for the states one update worker owns.
369type Shard<S, C, const N: usize> = RwLock<HashMap<S, Arc<Snapshot<C, N>>>>;
370
371/// Everything the workers share.
372struct Shared<S, C, const N: usize> {
373    /// The configuration.
374    config: SipConfig,
375    /// Incoming queues of the search workers.
376    search: Vec<Inbox<Arc<Label<S, C, N>>>>,
377    /// Incoming queues of the update workers.
378    update: Vec<Inbox<Arc<Label<S, C, N>>>>,
379    /// Incoming queue of the goal worker.
380    goal: Inbox<Arc<Label<S, C, N>>>,
381    /// Published snapshots per update worker.
382    shards: Vec<Shard<S, C, N>>,
383    /// The published goal snapshot.
384    goal_snapshot: RwLock<Arc<Snapshot<C, N>>>,
385    /// Labels sent and not yet fully processed; the search has ended when
386    /// it drops to zero.
387    pending: AtomicUsize,
388    /// Set once `pending` reached zero.
389    done: AtomicBool,
390    /// Labels expanded by search workers.
391    expanded: AtomicUsize,
392    /// Labels generated, the start included.
393    generated: AtomicUsize,
394}
395
396impl<S: Clone + Hash + Eq, C: Cost, const N: usize> Shared<S, C, N> {
397    /// Queues and snapshot tables for `config`.
398    fn new(config: SipConfig) -> Self {
399        Self {
400            config,
401            search: (0..config.search_workers).map(|_| Inbox::new()).collect(),
402            update: (0..config.update_workers).map(|_| Inbox::new()).collect(),
403            goal: Inbox::new(),
404            shards: (0..config.update_workers)
405                .map(|_| RwLock::new(HashMap::new()))
406                .collect(),
407            goal_snapshot: RwLock::new(Arc::new(Snapshot::empty())),
408            pending: AtomicUsize::new(0),
409            done: AtomicBool::new(false),
410            expanded: AtomicUsize::new(0),
411            generated: AtomicUsize::new(0),
412        }
413    }
414
415    /// The update worker that owns `state`.
416    fn owner(&self, state: &S) -> usize {
417        bucket(state, 0, self.config.update_workers)
418    }
419
420    /// The published snapshot of a non-goal `state`.
421    fn snapshot(&self, state: &S) -> Arc<Snapshot<C, N>> {
422        let shard = self.shards[self.owner(state)]
423            .read()
424            .expect("no worker panics while holding a shard");
425
426        shard
427            .get(state)
428            .map_or_else(|| Arc::new(Snapshot::empty()), Arc::clone)
429    }
430
431    /// The published goal snapshot.
432    fn goal_snapshot(&self) -> Arc<Snapshot<C, N>> {
433        Arc::clone(
434            &self
435                .goal_snapshot
436                .read()
437                .expect("no worker panics while publishing"),
438        )
439    }
440
441    /// Sends a candidate to the goal worker or to its endpoint's owner.
442    fn route(&self, label: Arc<Label<S, C, N>>, is_goal: impl Fn(&S) -> bool) {
443        if is_goal(&label.state) {
444            self.send(&self.goal, label);
445        } else {
446            self.send(&self.update[self.owner(&label.state)], label);
447        }
448    }
449
450    /// Hands an admitted label to the less loaded of two search workers
451    /// chosen by hashes of its state (power of two choices).
452    fn dispatch(&self, label: Arc<Label<S, C, N>>) {
453        let n = self.config.search_workers;
454        let (a, b) = (bucket(&label.state, 1, n), bucket(&label.state, 2, n));
455        let load = |r: usize| self.search[r].load.load(Atomic::Relaxed);
456        let r = if load(a) <= load(b) { a } else { b };
457        self.send(&self.search[r], label);
458    }
459
460    /// Appends `item` to `inbox`, counting it as pending.
461    fn send<T>(&self, inbox: &Inbox<T>, item: T) {
462        self.pending.fetch_add(1, Atomic::SeqCst);
463        inbox.load.fetch_add(1, Atomic::Relaxed);
464        inbox
465            .items
466            .lock()
467            .expect("no worker panics while holding an inbox")
468            .push(item);
469        inbox.ready.notify_one();
470    }
471
472    /// Marks one item of `inbox` as processed, and ends the search when
473    /// nothing is pending any more.
474    fn finish<T>(&self, inbox: &Inbox<T>) {
475        inbox.load.fetch_sub(1, Atomic::Relaxed);
476        if self.pending.fetch_sub(1, Atomic::SeqCst) == 1 {
477            self.done.store(true, Atomic::SeqCst);
478            Self::wake(&self.goal);
479            for inbox in self.search.iter().chain(&self.update) {
480                Self::wake(inbox);
481            }
482        }
483    }
484
485    /// Wakes a worker waiting on `inbox`, holding its lock so that the
486    /// wake-up cannot be missed.
487    fn wake<T>(inbox: &Inbox<T>) {
488        let _guard = inbox
489            .items
490            .lock()
491            .expect("no worker panics while holding an inbox");
492        inbox.ready.notify_all();
493    }
494
495    /// Moves the arrivals of `inbox` into `queue`, waiting while both are
496    /// empty. Returns `false` once the search has ended.
497    fn refill<T>(&self, inbox: &Inbox<T>, mut queue: impl FnMut(T), queued: bool) -> bool {
498        let mut items = inbox
499            .items
500            .lock()
501            .expect("no worker panics while holding an inbox");
502        while items.is_empty() && !queued {
503            if self.done.load(Atomic::SeqCst) {
504                return false;
505            }
506
507            items = inbox
508                .ready
509                .wait(items)
510                .expect("no worker panics while holding an inbox");
511        }
512
513        for item in items.drain(..) {
514            queue(item);
515        }
516
517        true
518    }
519}
520
521/// A deterministic bucket in `0..n` for `state`, salted by `seed`.
522fn bucket<S: Hash>(state: &S, seed: u64, n: usize) -> usize {
523    let mut hasher = DefaultHasher::new();
524    seed.hash(&mut hasher);
525    state.hash(&mut hasher);
526    let n = u64::try_from(n).expect("worker counts fit in u64");
527    usize::try_from(hasher.finish() % n).expect("a bucket is below the worker count")
528}
529
530/// A private best-first queue under one cyclic objective order.
531struct Private<S, C, const N: usize> {
532    /// The queue.
533    heap: BinaryHeap<Reverse<Entry<S, C, N>>>,
534    /// The first objective of the order.
535    first: usize,
536    /// Arrivals so far.
537    seq: usize,
538}
539
540impl<S, C: Cost, const N: usize> Private<S, C, N> {
541    /// An empty queue ordering `f` from objective `first` on, cyclically.
542    fn new(first: usize) -> Self {
543        Self {
544            heap: BinaryHeap::new(),
545            first,
546            seq: 0,
547        }
548    }
549
550    /// Queues a label.
551    fn push(&mut self, label: Arc<Label<S, C, N>>) {
552        let key = core::array::from_fn(|i| label.f[(i + self.first) % N]);
553        self.seq += 1;
554        self.heap.push(Reverse(Entry {
555            key,
556            seq: self.seq,
557            label,
558        }));
559    }
560
561    /// Takes the label with the smallest key.
562    fn pop(&mut self) -> Option<Arc<Label<S, C, N>>> {
563        self.heap.pop().map(|Reverse(entry)| entry.label)
564    }
565}
566
567/// A search worker (Algorithm 2): expands admitted labels and sends the
568/// children that survive snapshot pruning to their owners.
569fn search_worker<G, H, C, P, const N: usize>(
570    shared: &Shared<G::State, C, N>,
571    graph: &G,
572    mut heuristic: H,
573    is_goal: &P,
574    worker: usize,
575) where
576    G: Graph<Weight = [C; N]>,
577    G::State: Hash,
578    H: Heuristic<G::State, [C; N]>,
579    C: Cost,
580    P: Fn(&G::State) -> bool,
581{
582    let inbox = &shared.search[worker];
583    let mut queue = Private::new(worker % N);
584    let mut successors = Vec::new();
585
586    loop {
587        let queued = !queue.heap.is_empty();
588        if !shared.refill(inbox, |label| queue.push(label), queued) {
589            break;
590        }
591
592        let Some(parent) = queue.pop() else { continue };
593        shared.expanded.fetch_add(1, Atomic::Relaxed);
594
595        let goals = shared.goal_snapshot();
596        graph.successors(&parent.state, &mut successors);
597        for (state, weight) in successors.drain(..) {
598            let Some(estimate) = heuristic.estimate(&state) else {
599                continue;
600            };
601
602            let (g, goal) = (add(parent.g, weight), is_goal(&state));
603            let f = add(g, estimate);
604            let endpoint = if goal {
605                Arc::clone(&goals)
606            } else {
607                shared.snapshot(&state)
608            };
609
610            if endpoint.dominates(&g) || goals.dominates(&f) {
611                continue;
612            }
613
614            let child = Arc::new(Label {
615                state,
616                g,
617                f,
618                parent: Some(Arc::clone(&parent)),
619                seen: endpoint.version,
620            });
621            shared.generated.fetch_add(1, Atomic::Relaxed);
622            shared.route(child, is_goal);
623        }
624
625        shared.finish(inbox);
626    }
627}
628
629/// The canonical frontier of one state and its last published snapshot.
630struct Canonical<C, const N: usize> {
631    /// The exact non-dominated costs admitted so far.
632    front: Front<C, N>,
633    /// The last snapshot published for it.
634    snapshot: Arc<Snapshot<C, N>>,
635}
636
637impl<C: Cost, const N: usize> Canonical<C, N> {
638    /// An empty frontier with the version-0 snapshot.
639    fn new() -> Self {
640        Self {
641            front: Front::new(),
642            snapshot: Arc::new(Snapshot::empty()),
643        }
644    }
645
646    /// The admission step of Algorithm 3 (lines 8 to 24): rejects `g` if it
647    /// was checked against an older snapshot and the current one dominates
648    /// it, else inserts it and returns the next snapshot to publish.
649    fn admit(&mut self, g: [C; N], seen: u64, config: &SipConfig) -> Option<Arc<Snapshot<C, N>>> {
650        if seen != self.snapshot.version && self.snapshot.dominates(&g) {
651            return None;
652        }
653
654        if !self.front.insert(g) {
655            return None;
656        }
657
658        self.snapshot = Arc::new(self.snapshot.next(&self.front, g, config));
659        Some(Arc::clone(&self.snapshot))
660    }
661}
662
663/// An update worker (Algorithm 3) for the non-goal states it owns.
664fn update_worker<S, C, const N: usize>(shared: &Shared<S, C, N>, p: usize)
665where
666    S: Clone + Hash + Eq,
667    C: Cost,
668{
669    let inbox = &shared.update[p];
670    let mut queue = Private::new(0);
671    let mut frontiers: HashMap<S, Canonical<C, N>> = HashMap::new();
672
673    loop {
674        let queued = !queue.heap.is_empty();
675        if !shared.refill(inbox, |label| queue.push(label), queued) {
676            break;
677        }
678
679        let Some(y) = queue.pop() else { continue };
680        let canonical = frontiers
681            .entry(y.state.clone())
682            .or_insert_with(Canonical::new);
683
684        if let Some(snapshot) = canonical.admit(y.g, y.seen, &shared.config) {
685            shared.shards[p]
686                .write()
687                .expect("no worker panics while holding a shard")
688                .insert(y.state.clone(), snapshot);
689            shared.dispatch(y);
690        }
691
692        shared.finish(inbox);
693    }
694}
695
696/// The goal worker: keeps the goal frontier and one representative per
697/// admitted cost, and returns the representatives of the final front in
698/// lexicographic order.
699fn goal_worker<S, C, const N: usize>(shared: &Shared<S, C, N>) -> Vec<Arc<Label<S, C, N>>>
700where
701    S: Clone + Hash + Eq,
702    C: Cost,
703{
704    let inbox = &shared.goal;
705    let mut queue = Private::new(0);
706    let mut frontier = Canonical::new();
707    let mut representatives = BTreeMap::new();
708
709    loop {
710        let queued = !queue.heap.is_empty();
711        if !shared.refill(inbox, |label| queue.push(label), queued) {
712            break;
713        }
714
715        let Some(y) = queue.pop() else { continue };
716
717        if let Some(snapshot) = frontier.admit(y.g, y.seen, &shared.config) {
718            *shared
719                .goal_snapshot
720                .write()
721                .expect("no worker panics while publishing") = snapshot;
722            representatives.insert(y.g, y);
723        }
724
725        shared.finish(inbox);
726    }
727
728    frontier
729        .front
730        .as_slice()
731        .iter()
732        .map(|cost| Arc::clone(&representatives[cost]))
733        .collect()
734}
735
736/// The solution ending in `label`.
737fn rebuild<S: Clone, C: Copy, const N: usize>(label: &Arc<Label<S, C, N>>) -> Solution<S, [C; N]> {
738    let mut path = Vec::new();
739    let mut current = Some(label);
740
741    while let Some(l) = current {
742        path.push(l.state.clone());
743        current = l.parent.as_ref();
744    }
745
746    path.reverse();
747
748    Solution {
749        cost: label.g,
750        path,
751    }
752}