use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::thread;
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::open_list::OpenList;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, SearchSpace};
pub(crate) const BUDGET_INTERVAL: u64 = 64;
pub fn hda_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
threads: usize,
budget: impl Budget<Stats> + Send,
) -> GraphResult<G>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send,
G::Action: Clone + Send,
G::Cost: Send,
T: Goal<G::State> + Sync + ?Sized,
H: Heuristic<G::State, G::Cost> + Clone + Send,
{
hda_star_multi(graph, [start], goal, heuristic, threads, budget)
}
pub fn hda_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
threads: usize,
budget: impl Budget<Stats> + Send,
) -> GraphResult<G>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send,
G::Action: Clone + Send,
G::Cost: Send,
T: Goal<G::State> + Sync + ?Sized,
H: Heuristic<G::State, G::Cost> + Clone + Send,
{
let (space, start_goal) = SearchSpace::<G::State, G::Action, G::Cost>::seed(starts, goal);
if let Some(found) = start_goal {
return finish(Outcome::Found(space.solution(found)), Stats::default());
}
if space.len() == 0 {
return finish(Outcome::Unsolvable, Stats::default());
}
let threads = threads.max(1);
let owners = DefaultHashBuilder::default();
let mut partitions: Vec<GraphPartition<G, H>> = (1..threads)
.map(|index| Partition::new(index, heuristic.clone()))
.collect();
partitions.insert(0, Partition::new(0, heuristic));
for start in 0..space.len() {
let state = space.state(start).clone();
let owner = owner_of(&owners, threads, &state);
partitions[owner].record(state, G::Cost::ZERO, None);
}
let (senders, receivers): (Vec<_>, Vec<_>) = (0..threads).map(|_| mpsc::channel()).unzip();
let shared = Shared {
graph,
goal,
owners,
senders,
work: AtomicUsize::new(threads),
stopped: AtomicBool::new(false),
limit_reached: AtomicBool::new(false),
incumbent: Mutex::new(None),
improvements: AtomicUsize::new(0),
budget: Mutex::new((Stats::default(), budget)),
};
let partitions = run_workers(&shared, partitions, receivers);
let totals = partitions
.iter()
.fold(Stats::default(), |total, partition| {
total.plus(partition.stats)
});
let outcome = if shared.limit_reached.load(Ordering::SeqCst) {
Outcome::LimitReached
} else {
match *lock(&shared.incumbent) {
Some(incumbent) => Outcome::Found(path(&partitions, incumbent.at)),
None => Outcome::Unsolvable,
}
};
finish(outcome, totals)
}
fn run_workers<G, T, H, B>(
shared: &Shared<'_, G, T, B>,
partitions: Vec<GraphPartition<G, H>>,
receivers: Vec<Receiver<GraphMessage<G>>>,
) -> Vec<GraphPartition<G, H>>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send,
G::Action: Clone + Send,
G::Cost: Send,
T: Goal<G::State> + Sync + ?Sized,
H: Heuristic<G::State, G::Cost> + Send,
B: Budget<Stats> + Send,
{
thread::scope(|scope| {
let handles: Vec<_> = partitions
.into_iter()
.zip(receivers)
.map(|(partition, inbox)| {
scope.spawn(move || {
let guard = StopOnPanic(shared);
let mut worker = Worker {
shared,
inbox,
partition,
buffer: Vec::new(),
bound: None,
improvements: 0,
};
worker.run();
drop(guard);
worker.partition
})
})
.collect();
handles
.into_iter()
.map(|handle| {
handle
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
})
.collect()
})
}
fn finish<S, A, C>(outcome: Outcome<S, A, C>, stats: Stats) -> SearchResult<S, A, C> {
SearchResult { outcome, stats }
}
fn owner_of<S: Hash>(owners: &DefaultHashBuilder, threads: usize, state: &S) -> usize {
#[expect(
clippy::cast_possible_truncation,
reason = "the remainder is below `threads`, a `usize`"
)]
let owner = (owners.hash_one(state) % threads as u64) as usize;
owner
}
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
fn path<S: Clone, A: Clone, C: Cost, H>(
partitions: &[Partition<S, A, C, H>],
goal: Link,
) -> Solution<S, A, C> {
let mut states = Vec::new();
let mut actions = Vec::new();
let mut cost = C::ZERO;
let mut current = goal;
loop {
let node = &partitions[current.thread].nodes[current.node];
states.push(node.state.clone());
let Some((parent, action, edge_cost)) = &node.parent else {
break;
};
actions.push(action.clone());
cost = cost + *edge_cost;
current = *parent;
}
states.reverse();
actions.reverse();
Solution {
states,
actions,
cost,
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Link {
thread: usize,
node: NodeId,
}
type GraphPartition<G, H> =
Partition<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost, H>;
type GraphMessage<G> =
Message<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;
type Parent<A, C> = (Link, A, C);
#[derive(Clone, Copy)]
struct Incumbent<C> {
cost: C,
at: Link,
}
enum Message<S, A, C> {
State(S, C, Parent<A, C>),
Stop,
}
struct Shared<'a, G: Successors, T: ?Sized, B> {
graph: &'a G,
goal: &'a T,
owners: DefaultHashBuilder,
senders: Vec<Sender<GraphMessage<G>>>,
work: AtomicUsize,
stopped: AtomicBool,
limit_reached: AtomicBool,
incumbent: Mutex<Option<Incumbent<G::Cost>>>,
improvements: AtomicUsize,
budget: Mutex<(Stats, B)>,
}
impl<G: Successors, T: ?Sized, B> Shared<'_, G, T, B> {
fn stop(&self) {
self.stopped.store(true, Ordering::SeqCst);
for sender in &self.senders {
let _ = sender.send(Message::Stop);
}
}
fn bound(&self) -> Option<G::Cost> {
lock(&self.incumbent).map(|incumbent| incumbent.cost)
}
}
struct StopOnPanic<'s, 'a, G: Successors, T: ?Sized, B>(&'s Shared<'a, G, T, B>);
impl<G: Successors, T: ?Sized, B> Drop for StopOnPanic<'_, '_, G, T, B> {
fn drop(&mut self) {
if thread::panicking() {
self.0.stop();
}
}
}
struct Node<S, A, C> {
state: S,
g: C,
h: Option<C>,
closed: bool,
parent: Option<Parent<A, C>>,
}
struct Partition<S, A, C, H> {
index: usize,
heuristic: H,
nodes: Vec<Node<S, A, C>>,
table: HashTable<NodeId>,
hasher: DefaultHashBuilder,
open: OpenList<C>,
stats: Stats,
unreported: Stats,
}
impl<S: Hash + Eq, A, C: Cost, H: Heuristic<S, C>> Partition<S, A, C, H> {
fn new(index: usize, heuristic: H) -> Self {
Self {
index,
heuristic,
nodes: Vec::new(),
table: HashTable::new(),
hasher: DefaultHashBuilder::default(),
open: OpenList::new(),
stats: Stats::default(),
unreported: Stats::default(),
}
}
fn record(&mut self, state: S, g: C, parent: Option<Parent<A, C>>) {
let hash = self.hasher.hash_one(&state);
let nodes = &self.nodes;
let Some(&id) = self.table.find(hash, |&id| nodes[id].state == state) else {
self.insert(hash, state, g, parent);
return;
};
let node = &mut self.nodes[id];
if g.cmp(&node.g).is_ge() {
return;
}
node.g = g;
node.parent = parent;
if let Some(h) = node.h {
if node.closed {
self.stats.reopened += 1;
self.unreported.reopened += 1;
}
self.open.push(id, g.saturating_add(h), g);
}
}
fn insert(&mut self, hash: u64, state: S, g: C, parent: Option<Parent<A, C>>) {
let id = self.nodes.len();
let h = self.heuristic.estimate(&state);
let (nodes, hasher) = (&self.nodes, &self.hasher);
self.table
.insert_unique(hash, id, |&other| hasher.hash_one(&nodes[other].state));
self.nodes.push(Node {
state,
g,
h,
closed: false,
parent,
});
if let Some(h) = h {
self.open.push(id, g.saturating_add(h), g);
}
}
fn pop_below(&mut self, bound: Option<C>) -> Option<NodeId> {
let nodes = &self.nodes;
let (_, f) = self.open.peek_where(|id, g| g.cmp(&nodes[id].g).is_eq())?;
if bound.is_some_and(|bound| f.cmp(&bound).is_ge()) {
return None;
}
self.open
.pop_where(|id, g| g.cmp(&nodes[id].g).is_eq())
.map(|(id, _)| id)
}
}
struct Worker<'s, 'a, G: Successors, T: ?Sized, H, B> {
shared: &'s Shared<'a, G, T, B>,
inbox: Receiver<GraphMessage<G>>,
partition: GraphPartition<G, H>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
bound: Option<G::Cost>,
improvements: usize,
}
impl<G, T, H, B> Worker<'_, '_, G, T, H, B>
where
G: Successors,
G::State: Hash + Eq,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
B: Budget<Stats>,
{
fn run(&mut self) {
loop {
if !self.receive_pending() || self.shared.stopped.load(Ordering::SeqCst) {
return;
}
let improvements = self.shared.improvements.load(Ordering::SeqCst);
if improvements != self.improvements {
self.improvements = improvements;
self.bound = self.shared.bound();
}
match self.partition.pop_below(self.bound) {
Some(id) => self.visit(id),
None => {
if !self.idle() {
return;
}
}
}
}
}
fn receive_pending(&mut self) -> bool {
let mut received = 0;
while let Ok(message) = self.inbox.try_recv() {
if !self.receive(message) {
return false;
}
received += 1;
}
if received > 0 {
self.shared.work.fetch_sub(received, Ordering::SeqCst);
}
true
}
fn receive(&mut self, message: GraphMessage<G>) -> bool {
let Message::State(state, g, parent) = message else {
return false;
};
self.partition.record(state, g, Some(parent));
true
}
fn idle(&mut self) -> bool {
if self.shared.work.fetch_sub(1, Ordering::SeqCst) == 1 {
self.shared.stop();
return false;
}
match self.inbox.recv() {
Ok(message) => self.receive(message),
Err(_) => false,
}
}
fn visit(&mut self, id: NodeId) {
let node = &self.partition.nodes[id];
if self.shared.goal.is_goal(&node.state) {
let at = Link {
thread: self.partition.index,
node: id,
};
let mut incumbent = lock(&self.shared.incumbent);
if incumbent.is_none_or(|incumbent| node.g.cmp(&incumbent.cost).is_lt()) {
*incumbent = Some(Incumbent { cost: node.g, at });
self.shared.improvements.fetch_add(1, Ordering::SeqCst);
}
return;
}
if self.budget_exhausted() {
self.shared.limit_reached.store(true, Ordering::SeqCst);
self.shared.stop();
return;
}
self.expand(id);
}
fn budget_exhausted(&mut self) -> bool {
if self.partition.stats.expanded % BUDGET_INTERVAL != 0 {
return false;
}
let mut budget = lock(&self.shared.budget);
let (total, budget) = &mut *budget;
*total = total.plus(core::mem::take(&mut self.partition.unreported));
budget.exhausted(total)
}
fn expand(&mut self, id: NodeId) {
let partition = &mut self.partition;
partition.nodes[id].closed = true;
let g = partition.nodes[id].g;
let generated = collect_successors(
self.shared.graph,
&partition.nodes[id].state,
&mut self.buffer,
);
for stats in [&mut partition.stats, &mut partition.unreported] {
stats.expanded += 1;
stats.generated += generated;
}
let threads = self.shared.senders.len();
let from = Link {
thread: partition.index,
node: id,
};
let counted = self.buffer.len();
if threads > 1 && counted > 0 {
self.shared.work.fetch_add(counted, Ordering::SeqCst);
}
let mut kept = 0;
for (action, state, cost) in self.buffer.drain(..) {
let parent = (from, action, cost);
let owner = owner_of(&self.shared.owners, threads, &state);
if owner == partition.index {
partition.record(state, g + cost, Some(parent));
kept += 1;
continue;
}
if self.shared.senders[owner]
.send(Message::State(state, g + cost, parent))
.is_err()
{
return;
}
}
if threads > 1 && kept > 0 {
self.shared.work.fetch_sub(kept, Ordering::SeqCst);
}
}
}