use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cmp::{Ordering, Reverse};
use core::hash::{Hash, Hasher};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering as Atomic};
use std::collections::HashMap;
use std::hash::DefaultHasher;
use std::sync::{Condvar, Mutex, RwLock};
use search_core::{Cost, Heuristic};
use crate::cost::add;
use crate::graph::Graph;
use crate::output::{Output, Solution, Stats};
use crate::pareto::{Front, FrontIndex, IndexedFront};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SipConfig {
pub search_workers: usize,
pub update_workers: usize,
pub index: FrontIndex,
pub index_threshold: usize,
pub delta_min: usize,
pub delta_divisor: usize,
pub block_size: usize,
}
impl SipConfig {
pub const DEFAULT: Self = Self {
search_workers: 2,
update_workers: 2,
index: FrontIndex::Blocks,
index_threshold: 64,
delta_min: 8,
delta_divisor: 8,
block_size: 16,
};
fn delta_capacity(&self, frontier: usize) -> usize {
(frontier / self.delta_divisor).max(self.delta_min)
}
}
impl Default for SipConfig {
fn default() -> Self {
Self::DEFAULT
}
}
pub fn sip_mosp<G, H, C, P, const N: usize>(
graph: &G,
mut heuristic: H,
start: G::State,
is_goal: P,
config: SipConfig,
) -> Output<G::State, [C; N]>
where
G: Graph<Weight = [C; N]> + Sync,
G::State: Hash + Send + Sync,
H: Heuristic<G::State, [C; N]> + Clone + Send,
C: Cost + Send + Sync,
P: Fn(&G::State) -> bool + Sync,
{
assert!(
config.search_workers > 0 && config.update_workers > 0,
"SIP-MOSP needs at least one search and one update worker"
);
assert!(
config.delta_divisor > 0 && config.block_size > 0,
"the delta divisor and the block size must be positive"
);
let Some(h) = heuristic.estimate(&start) else {
return Output {
solutions: Vec::new(),
stats: Stats::default(),
};
};
let shared = Shared::new(config);
let start_label = Arc::new(Label {
state: start,
g: [C::ZERO; N],
f: h,
parent: None,
seen: 0,
});
shared.generated.fetch_add(1, Atomic::Relaxed);
let goal_labels = std::thread::scope(|scope| {
for r in 0..config.search_workers {
let (shared, heuristic, is_goal) = (&shared, heuristic.clone(), &is_goal);
scope.spawn(move || search_worker(shared, graph, heuristic, is_goal, r));
}
for p in 0..config.update_workers {
let shared = &shared;
scope.spawn(move || update_worker(shared, p));
}
let goal = scope.spawn(|| goal_worker(&shared));
shared.route(start_label, &is_goal);
goal.join().expect("the goal worker panicked")
});
let stats = Stats {
expanded: shared.expanded.load(Atomic::Relaxed),
generated: shared.generated.load(Atomic::Relaxed),
};
Output {
solutions: goal_labels
.into_iter()
.map(|label| rebuild(&label))
.collect(),
stats,
}
}
struct Label<S, C, const N: usize> {
state: S,
g: [C; N],
f: [C; N],
parent: Option<Arc<Label<S, C, N>>>,
seen: u64,
}
struct Entry<S, C, const N: usize> {
key: [C; N],
seq: usize,
label: Arc<Label<S, C, N>>,
}
impl<S, C: Ord, const N: usize> PartialEq for Entry<S, C, N> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<S, C: Ord, const N: usize> Eq for Entry<S, C, N> {}
impl<S, C: Ord, const N: usize> PartialOrd for Entry<S, C, N> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<S, C: Ord, const N: usize> Ord for Entry<S, C, N> {
fn cmp(&self, other: &Self) -> Ordering {
(&self.key, self.seq).cmp(&(&other.key, other.seq))
}
}
struct Snapshot<C, const N: usize> {
base: Arc<IndexedFront<C, N>>,
delta: Vec<[C; N]>,
delta_min: Option<[C; N]>,
version: u64,
}
impl<C: Cost, const N: usize> Snapshot<C, N> {
fn empty() -> Self {
Self {
base: Arc::new(IndexedFront::new(Vec::new(), FrontIndex::None)),
delta: Vec::new(),
delta_min: None,
version: 0,
}
}
fn dominates(&self, q: &[C; N]) -> bool {
let below = |p: &[C; N]| p.iter().zip(q).all(|(a, b)| a <= b);
if self.delta_min.as_ref().is_some_and(below) && self.delta.iter().any(below) {
return true;
}
self.base.weakly_dominates(q)
}
fn next(&self, front: &Front<C, N>, g: [C; N], config: &SipConfig) -> Self {
let version = self.version + 1;
let rebuild = |index| Self {
base: Arc::new(IndexedFront::with_block_size(
front.as_slice().to_vec(),
index,
config.block_size,
)),
delta: Vec::new(),
delta_min: None,
version,
};
if front.len() < config.index_threshold {
return rebuild(FrontIndex::None);
}
let unindexed = self.base.len() < config.index_threshold;
if unindexed || self.delta.len() + 1 >= config.delta_capacity(front.len()) {
return rebuild(config.index);
}
let mut delta = self.delta.clone();
delta.push(g);
let delta_min = Some(match self.delta_min {
Some(m) => core::array::from_fn(|i| m[i].min(g[i])),
None => g,
});
Self {
base: Arc::clone(&self.base),
delta,
delta_min,
version,
}
}
}
struct Inbox<T> {
items: Mutex<Vec<T>>,
ready: Condvar,
load: AtomicUsize,
}
impl<T> Inbox<T> {
fn new() -> Self {
Self {
items: Mutex::new(Vec::new()),
ready: Condvar::new(),
load: AtomicUsize::new(0),
}
}
}
type Shard<S, C, const N: usize> = RwLock<HashMap<S, Arc<Snapshot<C, N>>>>;
struct Shared<S, C, const N: usize> {
config: SipConfig,
search: Vec<Inbox<Arc<Label<S, C, N>>>>,
update: Vec<Inbox<Arc<Label<S, C, N>>>>,
goal: Inbox<Arc<Label<S, C, N>>>,
shards: Vec<Shard<S, C, N>>,
goal_snapshot: RwLock<Arc<Snapshot<C, N>>>,
pending: AtomicUsize,
done: AtomicBool,
expanded: AtomicUsize,
generated: AtomicUsize,
}
impl<S: Clone + Hash + Eq, C: Cost, const N: usize> Shared<S, C, N> {
fn new(config: SipConfig) -> Self {
Self {
config,
search: (0..config.search_workers).map(|_| Inbox::new()).collect(),
update: (0..config.update_workers).map(|_| Inbox::new()).collect(),
goal: Inbox::new(),
shards: (0..config.update_workers)
.map(|_| RwLock::new(HashMap::new()))
.collect(),
goal_snapshot: RwLock::new(Arc::new(Snapshot::empty())),
pending: AtomicUsize::new(0),
done: AtomicBool::new(false),
expanded: AtomicUsize::new(0),
generated: AtomicUsize::new(0),
}
}
fn owner(&self, state: &S) -> usize {
bucket(state, 0, self.config.update_workers)
}
fn snapshot(&self, state: &S) -> Arc<Snapshot<C, N>> {
let shard = self.shards[self.owner(state)]
.read()
.expect("no worker panics while holding a shard");
shard
.get(state)
.map_or_else(|| Arc::new(Snapshot::empty()), Arc::clone)
}
fn goal_snapshot(&self) -> Arc<Snapshot<C, N>> {
Arc::clone(
&self
.goal_snapshot
.read()
.expect("no worker panics while publishing"),
)
}
fn route(&self, label: Arc<Label<S, C, N>>, is_goal: impl Fn(&S) -> bool) {
if is_goal(&label.state) {
self.send(&self.goal, label);
} else {
self.send(&self.update[self.owner(&label.state)], label);
}
}
fn dispatch(&self, label: Arc<Label<S, C, N>>) {
let n = self.config.search_workers;
let (a, b) = (bucket(&label.state, 1, n), bucket(&label.state, 2, n));
let load = |r: usize| self.search[r].load.load(Atomic::Relaxed);
let r = if load(a) <= load(b) { a } else { b };
self.send(&self.search[r], label);
}
fn send<T>(&self, inbox: &Inbox<T>, item: T) {
self.pending.fetch_add(1, Atomic::SeqCst);
inbox.load.fetch_add(1, Atomic::Relaxed);
inbox
.items
.lock()
.expect("no worker panics while holding an inbox")
.push(item);
inbox.ready.notify_one();
}
fn finish<T>(&self, inbox: &Inbox<T>) {
inbox.load.fetch_sub(1, Atomic::Relaxed);
if self.pending.fetch_sub(1, Atomic::SeqCst) == 1 {
self.done.store(true, Atomic::SeqCst);
Self::wake(&self.goal);
for inbox in self.search.iter().chain(&self.update) {
Self::wake(inbox);
}
}
}
fn wake<T>(inbox: &Inbox<T>) {
let _guard = inbox
.items
.lock()
.expect("no worker panics while holding an inbox");
inbox.ready.notify_all();
}
fn refill<T>(&self, inbox: &Inbox<T>, mut queue: impl FnMut(T), queued: bool) -> bool {
let mut items = inbox
.items
.lock()
.expect("no worker panics while holding an inbox");
while items.is_empty() && !queued {
if self.done.load(Atomic::SeqCst) {
return false;
}
items = inbox
.ready
.wait(items)
.expect("no worker panics while holding an inbox");
}
for item in items.drain(..) {
queue(item);
}
true
}
}
fn bucket<S: Hash>(state: &S, seed: u64, n: usize) -> usize {
let mut hasher = DefaultHasher::new();
seed.hash(&mut hasher);
state.hash(&mut hasher);
let n = u64::try_from(n).expect("worker counts fit in u64");
usize::try_from(hasher.finish() % n).expect("a bucket is below the worker count")
}
struct Private<S, C, const N: usize> {
heap: BinaryHeap<Reverse<Entry<S, C, N>>>,
first: usize,
seq: usize,
}
impl<S, C: Cost, const N: usize> Private<S, C, N> {
fn new(first: usize) -> Self {
Self {
heap: BinaryHeap::new(),
first,
seq: 0,
}
}
fn push(&mut self, label: Arc<Label<S, C, N>>) {
let key = core::array::from_fn(|i| label.f[(i + self.first) % N]);
self.seq += 1;
self.heap.push(Reverse(Entry {
key,
seq: self.seq,
label,
}));
}
fn pop(&mut self) -> Option<Arc<Label<S, C, N>>> {
self.heap.pop().map(|Reverse(entry)| entry.label)
}
}
fn search_worker<G, H, C, P, const N: usize>(
shared: &Shared<G::State, C, N>,
graph: &G,
mut heuristic: H,
is_goal: &P,
worker: usize,
) where
G: Graph<Weight = [C; N]>,
G::State: Hash,
H: Heuristic<G::State, [C; N]>,
C: Cost,
P: Fn(&G::State) -> bool,
{
let inbox = &shared.search[worker];
let mut queue = Private::new(worker % N);
let mut successors = Vec::new();
loop {
let queued = !queue.heap.is_empty();
if !shared.refill(inbox, |label| queue.push(label), queued) {
break;
}
let Some(parent) = queue.pop() else { continue };
shared.expanded.fetch_add(1, Atomic::Relaxed);
let goals = shared.goal_snapshot();
graph.successors(&parent.state, &mut successors);
for (state, weight) in successors.drain(..) {
let Some(estimate) = heuristic.estimate(&state) else {
continue;
};
let (g, goal) = (add(parent.g, weight), is_goal(&state));
let f = add(g, estimate);
let endpoint = if goal {
Arc::clone(&goals)
} else {
shared.snapshot(&state)
};
if endpoint.dominates(&g) || goals.dominates(&f) {
continue;
}
let child = Arc::new(Label {
state,
g,
f,
parent: Some(Arc::clone(&parent)),
seen: endpoint.version,
});
shared.generated.fetch_add(1, Atomic::Relaxed);
shared.route(child, is_goal);
}
shared.finish(inbox);
}
}
struct Canonical<C, const N: usize> {
front: Front<C, N>,
snapshot: Arc<Snapshot<C, N>>,
}
impl<C: Cost, const N: usize> Canonical<C, N> {
fn new() -> Self {
Self {
front: Front::new(),
snapshot: Arc::new(Snapshot::empty()),
}
}
fn admit(&mut self, g: [C; N], seen: u64, config: &SipConfig) -> Option<Arc<Snapshot<C, N>>> {
if seen != self.snapshot.version && self.snapshot.dominates(&g) {
return None;
}
if !self.front.insert(g) {
return None;
}
self.snapshot = Arc::new(self.snapshot.next(&self.front, g, config));
Some(Arc::clone(&self.snapshot))
}
}
fn update_worker<S, C, const N: usize>(shared: &Shared<S, C, N>, p: usize)
where
S: Clone + Hash + Eq,
C: Cost,
{
let inbox = &shared.update[p];
let mut queue = Private::new(0);
let mut frontiers: HashMap<S, Canonical<C, N>> = HashMap::new();
loop {
let queued = !queue.heap.is_empty();
if !shared.refill(inbox, |label| queue.push(label), queued) {
break;
}
let Some(y) = queue.pop() else { continue };
let canonical = frontiers
.entry(y.state.clone())
.or_insert_with(Canonical::new);
if let Some(snapshot) = canonical.admit(y.g, y.seen, &shared.config) {
shared.shards[p]
.write()
.expect("no worker panics while holding a shard")
.insert(y.state.clone(), snapshot);
shared.dispatch(y);
}
shared.finish(inbox);
}
}
fn goal_worker<S, C, const N: usize>(shared: &Shared<S, C, N>) -> Vec<Arc<Label<S, C, N>>>
where
S: Clone + Hash + Eq,
C: Cost,
{
let inbox = &shared.goal;
let mut queue = Private::new(0);
let mut frontier = Canonical::new();
let mut representatives = BTreeMap::new();
loop {
let queued = !queue.heap.is_empty();
if !shared.refill(inbox, |label| queue.push(label), queued) {
break;
}
let Some(y) = queue.pop() else { continue };
if let Some(snapshot) = frontier.admit(y.g, y.seen, &shared.config) {
*shared
.goal_snapshot
.write()
.expect("no worker panics while publishing") = snapshot;
representatives.insert(y.g, y);
}
shared.finish(inbox);
}
frontier
.front
.as_slice()
.iter()
.map(|cost| Arc::clone(&representatives[cost]))
.collect()
}
fn rebuild<S: Clone, C: Copy, const N: usize>(label: &Arc<Label<S, C, N>>) -> Solution<S, [C; N]> {
let mut path = Vec::new();
let mut current = Some(label);
while let Some(l) = current {
path.push(l.state.clone());
current = l.parent.as_ref();
}
path.reverse();
Solution {
cost: label.g,
path,
}
}