1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct SipConfig {
57 pub search_workers: usize,
59 pub update_workers: usize,
62 pub index: FrontIndex,
65 pub index_threshold: usize,
68 pub delta_min: usize,
72 pub delta_divisor: usize,
74 pub block_size: usize,
76}
77
78impl SipConfig {
79 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 fn delta_capacity(&self, frontier: usize) -> usize {
93 (frontier / self.delta_divisor).max(self.delta_min)
94 }
95}
96
97impl Default for SipConfig {
98 fn default() -> Self {
100 Self::DEFAULT
101 }
102}
103
104pub 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
223struct Label<S, C, const N: usize> {
225 state: S,
227 g: [C; N],
229 f: [C; N],
231 parent: Option<Arc<Label<S, C, N>>>,
233 seen: u64,
236}
237
238struct Entry<S, C, const N: usize> {
240 key: [C; N],
242 seq: usize,
244 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
268struct Snapshot<C, const N: usize> {
271 base: Arc<IndexedFront<C, N>>,
273 delta: Vec<[C; N]>,
275 delta_min: Option<[C; N]>,
277 version: u64,
279}
280
281impl<C: Cost, const N: usize> Snapshot<C, N> {
282 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 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 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
346struct Inbox<T> {
348 items: Mutex<Vec<T>>,
350 ready: Condvar,
352 load: AtomicUsize,
355}
356
357impl<T> Inbox<T> {
358 fn new() -> Self {
360 Self {
361 items: Mutex::new(Vec::new()),
362 ready: Condvar::new(),
363 load: AtomicUsize::new(0),
364 }
365 }
366}
367
368type Shard<S, C, const N: usize> = RwLock<HashMap<S, Arc<Snapshot<C, N>>>>;
370
371struct Shared<S, C, const N: usize> {
373 config: SipConfig,
375 search: Vec<Inbox<Arc<Label<S, C, N>>>>,
377 update: Vec<Inbox<Arc<Label<S, C, N>>>>,
379 goal: Inbox<Arc<Label<S, C, N>>>,
381 shards: Vec<Shard<S, C, N>>,
383 goal_snapshot: RwLock<Arc<Snapshot<C, N>>>,
385 pending: AtomicUsize,
388 done: AtomicBool,
390 expanded: AtomicUsize,
392 generated: AtomicUsize,
394}
395
396impl<S: Clone + Hash + Eq, C: Cost, const N: usize> Shared<S, C, N> {
397 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 fn owner(&self, state: &S) -> usize {
417 bucket(state, 0, self.config.update_workers)
418 }
419
420 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 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 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 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 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 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 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 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
521fn 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
530struct Private<S, C, const N: usize> {
532 heap: BinaryHeap<Reverse<Entry<S, C, N>>>,
534 first: usize,
536 seq: usize,
538}
539
540impl<S, C: Cost, const N: usize> Private<S, C, N> {
541 fn new(first: usize) -> Self {
543 Self {
544 heap: BinaryHeap::new(),
545 first,
546 seq: 0,
547 }
548 }
549
550 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 fn pop(&mut self) -> Option<Arc<Label<S, C, N>>> {
563 self.heap.pop().map(|Reverse(entry)| entry.label)
564 }
565}
566
567fn 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
629struct Canonical<C, const N: usize> {
631 front: Front<C, N>,
633 snapshot: Arc<Snapshot<C, N>>,
635}
636
637impl<C: Cost, const N: usize> Canonical<C, N> {
638 fn new() -> Self {
640 Self {
641 front: Front::new(),
642 snapshot: Arc::new(Snapshot::empty()),
643 }
644 }
645
646 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
663fn 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
696fn 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
736fn 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}