Skip to main content

decoupled_search/
search.rs

1//! Uniform-cost, A* and greedy best-first decoupled search with dominance
2//! pruning.
3//!
4//! All three share one driver and differ in the open-list key: `g`,
5//! `g + h` or `h`. Uniform-cost search and A* stop once the popped key
6//! reaches the best solution cost found so far; greedy search stops at the
7//! first solution. [`Config`] selects the dominance criterion (see
8//! [`Pruning`]) and whether leaves keep prices ([`Leaves`]).
9//!
10//! ```mermaid
11//! graph LR
12//!     pop[pop lowest key] --> stop{done?}
13//!     stop -- yes --> done[reconstruct best]
14//!     stop -- no --> expand[global successors]
15//!     expand --> prune{dominated or dead end?}
16//!     prune -- no --> store[store, record goal cost, push]
17//!     store --> pop
18//!     prune -- yes --> pop
19//! ```
20
21mod dominance;
22mod reconstruct;
23mod stubborn;
24
25use alloc::collections::{BTreeMap, BinaryHeap};
26use alloc::vec;
27use alloc::vec::Vec;
28use core::cmp::Reverse;
29
30use sas_plus::{Task, Value};
31
32use crate::decoupled::{DecoupledState, DecoupledTask, Price};
33use crate::{DecoupledHeuristic, Error, Factoring, Plan};
34pub(crate) use dominance::simulation;
35use dominance::{Bounds, Dominance};
36use stubborn::StubbornSets;
37
38/// How the open list is ordered.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub(crate) enum Order {
41    /// By `g + h`, cost-optimal for admissible `h` (`h = 0` without a
42    /// heuristic, which is uniform-cost search).
43    Cost,
44    /// By `h` alone, stopping at the first solution.
45    Greedy,
46    /// Anytime decoupled A*: by `g` plus a root heuristic (remaining global
47    /// cost only), pruning by `g + h` against the best solution, stopping
48    /// once the popped key plus the least possible goal price reaches it.
49    Anytime,
50}
51
52/// The dominance criterion that prunes generated decoupled states.
53///
54/// A stored state `t` *dominates* a generated state `n` with the same
55/// center if every completion of `n` can be turned into a completion of `t`
56/// with the same remaining global actions and no higher total cost; `n` is
57/// then pruned. The criteria are those of Torralba, Gnad, Dubbert and
58/// Hoffmann (IJCAI 2016), generalised to this crate's global actions, which
59/// may read and write leaves under any partition, and to partial leaf
60/// goals. [`Pruning::Frontier`] subsumes [`Pruning::Basic`],
61/// [`Pruning::EffectivePrices`] subsumes [`Pruning::Frontier`],
62/// [`Pruning::Simulation`] subsumes [`Pruning::Basic`], and
63/// [`Pruning::EffectiveSimulation`] subsumes all; effective prices and
64/// simulation are incomparable (as in the paper). Stronger criteria prune
65/// more but cost more: simulation is computed once per search and leaf.
66///
67/// # Anchored leaf states
68///
69/// The paper has one goal leaf state, and only leaf actions move a leaf.
70/// Here, a leaf state is *anchored* if it satisfies the leaf goal or the
71/// leaf preconditions of some global action's part on the leaf (every state
72/// is, if some part has no leaf precondition). An unanchored state can only
73/// be left by leaf actions; a completion's leaf path ends in a goal leaf
74/// state and meets every global action that touches the leaf in an
75/// anchored state.
76///
77/// # The per-leaf property
78///
79/// Each criterion yields, per leaf `L`, a slack `δ_L` such that:
80///
81/// > (★) for every center path `π` from `n` and every `π`-compliant leaf
82/// > path `ρ` that a completion of `n` takes from a reached leaf state `x`,
83/// > `t` has a `π`-compliant leaf path that ends in a goal leaf state and
84/// > satisfies the same global preconditions, at total leaf cost at most
85/// > `price_n(x) + δ_L + cost(ρ)`.
86///
87/// All criteria but the frontier one give a *bound* `D_t(x)` with "`t` can
88/// do what `ρ` does from `x` at leaf cost at most `D_t(x) + cost(ρ)`"; then
89/// `δ_L = max_x (D_t(x) - price_n(x))` over the reached states `x` of `n`
90/// satisfies (★).
91///
92/// - [`Pruning::Basic`]: `D_t(x) = price_t(x)`. `t` reaches `x` at that
93///   price and follows `ρ`.
94/// - [`Pruning::Simulation`]: `D_t(x) = min_{x ⪯ y} price_t(y)` over the
95///   reached `y` that simulate `x` (see the variant). `t` reaches `y` and
96///   mirrors `ρ`.
97/// - [`Pruning::EffectivePrices`]: `D_t = p`, the point-wise least function
98///   with `p(x) = S(x)` on anchored states and
99///   `p(x) = min(S(x), max_{x -a-> y} p(y) - cost(a))` elsewhere, over leaf
100///   actions regardless of their center preconditions, where
101///   `S = price_t`. Proof: let `ρ` visit `x = s_0, ..., s_m` and take the
102///   first `i` with `p(s_i) = S(s_i)`; it exists because `ρ` ends in a goal
103///   leaf state, which is anchored. Before `i` all states are unanchored,
104///   so every step is a leaf action and `p(s_j) >= p(s_{j+1}) - cost(a_{j+1})`;
105///   summing, `S(s_i) = p(s_i) <= p(x) + cost(s_0 .. s_i)`. `t` reaches `s_i`
106///   at `S(s_i)` and follows the rest of `ρ`. States whose least value is
107///   `-∞` reach no anchored state, so no completion uses them.
108/// - [`Pruning::EffectiveSimulation`]: the same with `S` the simulation
109///   bound; at `s_i`, `t` reaches a simulating `y` and mirrors the rest.
110/// - [`Pruning::Frontier`]: `δ_L = max_x (price_t(x) - price_n(x))` over the
111///   reached states `x` on the frontier of `n`: anchored, or left by some
112///   leaf action `x -a-> y` with `price_n(x) + cost(a) < price_n(y)`. Proof:
113///   if `ρ` starts outside the frontier, every leaf action out of a
114///   non-frontier state `s_j` reaches `s_{j+1}` with
115///   `price_n(s_{j+1}) <= price_n(s_j) + cost(a_{j+1})`, so the first
116///   frontier state `s_k` of `ρ` (it exists, the goal state is anchored)
117///   has `price_n(s_k) <= price_n(x) + cost(s_0 .. s_k)`; `t` reaches `s_k`
118///   at `price_t(s_k) <= price_n(s_k) + δ_L` and follows the rest of `ρ`.
119///
120/// # The `g` budget
121///
122/// Leaf prices exclude `g`. A completion of `n` through leaf states `x_L`
123/// costs `g(n) + Σ_L (price_n(x_L) + cost(ρ_L)) + c`, with `c` the cost of
124/// the remaining global actions, and by (★) `t` has one costing at most
125/// `g(t) + Σ_L (price_n(x_L) + δ_L + cost(ρ_L)) + c`. So `t` dominates `n`
126/// for cost-optimal search if `g(t) + Σ_L δ_L <= g(n)`, which
127/// [`Config::fold_g`] uses; without it, the classic condition `g(t) <= g(n)`
128/// and `δ_L <= 0` for every leaf. Comparing `g + price` per leaf state
129/// instead is unsound with two or more leaves, because `g` is paid once but
130/// would be credited per leaf: with `g(t) = 0` and both leaves at price 10,
131/// `g(n) = 10` and both at 0, every leaf ties at 10, yet completing both
132/// costs 20 from `t` and 10 from `n`. Greedy search only needs
133/// reachability: `t` dominates `n` if every `δ_L` is finite.
134///
135/// # Optimality
136///
137/// Say a stored node *covers* cost `C` via global actions `π` if `π` leads
138/// it to a goal state with total cost at most `C`. While uniform-cost search
139/// or A* with an admissible heuristic has not recorded the optimal cost
140/// `C*`, take a node covering `C*` with the shortest `π`. If `π` is empty,
141/// the node is a goal and its cost was recorded when it was stored. If the
142/// node were closed, its successor along `π[0]` was either stored (covering
143/// via a shorter path), pruned by a stored node covering via the same
144/// shorter `π[1..]` (dominance keeps the remaining global actions, so the
145/// paper's condition on the number of center actions is not needed), or a
146/// dead end of the heuristic, which is impossible for a state with a
147/// completion. So it is open with `f <= C*`, and the search cannot stop
148/// before recording `C*`. Termination follows from Dickson's lemma for the
149/// basic criterion, which every other one subsumes.
150///
151/// Leaves whose transitions depend on the center (center-conditioned
152/// effects, derived variables attached to them) or that have more than
153/// [`Config::max_analysis_states`] states use the basic bound.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155#[non_exhaustive]
156pub enum Pruning {
157    /// Same center and no higher price for any leaf state (Gnad and
158    /// Hoffmann's criterion).
159    Basic,
160    /// Prices compared only on the frontier of the generated state: leaf
161    /// states that are goals, satisfy a global precondition, or could still
162    /// lower another state's price.
163    Frontier,
164    /// Prices of the stored state replaced by effective prices, which credit
165    /// a leaf state with the cheapest way to get to where it leads.
166    EffectivePrices,
167    /// A leaf state may take the price of any reached leaf state that
168    /// simulates it.
169    ///
170    /// The leaf simulation `⪯` (Definition 5 of the paper, with global
171    /// actions added) is the coarsest relation on leaf states where
172    /// `x ⪯ y` implies: if `x` satisfies the leaf goal, so does `y`; for
173    /// every global action's part `P` on the leaf, if `x` satisfies `P`'s
174    /// leaf preconditions, so does `y`, and `P(x) ⪯ P(y)`; and for every
175    /// leaf action `x -a-> x'`, either `x' ⪯ y` (the leaf stays at `y`) or
176    /// some leaf action `b` with `cost(b) <= cost(a)` and center
177    /// preconditions contained in `a`'s leads `y -b-> y'` with `x' ⪯ y'`.
178    /// By induction on a compliant leaf path from `x`, `y` has one that
179    /// complies with the same center path (each `b` is applicable wherever
180    /// `a` was, each global action's leaf preconditions hold), ends in a
181    /// goal leaf state whenever the original does, and costs no more.
182    Simulation,
183    /// Effective prices over simulation bounds; the strongest criterion.
184    EffectiveSimulation,
185    /// [`Pruning::EffectivePrices`] until the search has spent about as
186    /// much as computing the leaf simulations would cost, then
187    /// [`Pruning::EffectiveSimulation`] (the default).
188    ///
189    /// Computing a leaf simulation takes time quadratic in the leaf size,
190    /// which dominates searches on small tasks. The switch follows the
191    /// ski-rental rule: the work unit is one leaf state of a generated
192    /// decoupled state (leaf closure touches every leaf state of every
193    /// successor), and the simulation's estimated cost is the sum of
194    /// `size^2 * (1 + leaf actions)` over the analysed leaves. A search that
195    /// ends earlier never pays for simulation; otherwise it pays at most
196    /// about twice the better of the two choices. Both criteria are sound,
197    /// so mixing them in one search is too; bounds cached under effective
198    /// prices are recomputed after the switch. With
199    /// [`Config::reduce_leaves`], the simulation is needed up front, and
200    /// this is [`Pruning::EffectiveSimulation`] from the start.
201    #[default]
202    Adaptive,
203}
204
205/// What a decoupled state keeps per leaf state.
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207#[non_exhaustive]
208pub enum Leaves {
209    /// The price of every reached leaf state: the cheapest cost of leaf
210    /// actions that reaches it along the current center path. Needed for
211    /// cost-optimal search.
212    #[default]
213    Priced,
214    /// Only which leaf states are reached (all at price 0); leaf action
215    /// costs enter the plan, not the search. Smaller states and more
216    /// pruning, for greedy search only.
217    Reachability,
218}
219
220/// Options for decoupled search.
221///
222/// # Examples
223///
224/// ```
225/// use decoupled_search::{Config, Factoring, Pruning};
226/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
227///
228/// let op = |pre: Vec<Fact>, eff: Fact| Operator {
229///     name: "op".into(),
230///     pre,
231///     eff: vec![Effect::new(eff)],
232///     cost: 1,
233/// };
234/// let task = Task {
235///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
236///     operators: vec![
237///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
238///         op(vec![Fact::new(0, 1)], Fact::new(0, 0)),
239///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
240///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
241///     ],
242///     initial: State(vec![0, 0]),
243///     goal: vec![Fact::new(1, 1)],
244///     axioms: vec![],
245/// };
246///
247/// let config = Config {
248///     pruning: Pruning::Basic,
249///     ..Config::default()
250/// };
251/// let outcome = config.search(&task, &Factoring::fork(&task))?;
252/// assert_eq!(outcome.plan.map(|p| p.cost), Some(3));
253/// assert!(outcome.statistics.expanded >= 1);
254/// # Ok::<(), decoupled_search::Error>(())
255/// ```
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
257#[expect(
258    clippy::struct_excessive_bools,
259    reason = "independent on/off options; struct-literal construction is public API"
260)]
261pub struct Config {
262    /// The dominance criterion. Default: [`Pruning::Adaptive`].
263    pub pruning: Pruning,
264    /// Whether a stored state may dominate one reached more cheaply, when
265    /// its cheaper prices pay for the difference in `g` (one budget shared
266    /// by all leaves). Without it, the stored state needs no higher `g`.
267    /// Default: `true`.
268    pub fold_g: bool,
269    /// Prices or reachability only. Default: [`Leaves::Priced`].
270    pub leaves: Leaves,
271    /// The largest leaf (in leaf states) that frontier, effective-price and
272    /// simulation analyses run on; larger leaves use the basic comparison.
273    /// Simulation takes time quadratic in the leaf size per refinement
274    /// round, effective prices keep one bound per leaf state in every
275    /// stored state. Default: 256.
276    pub max_analysis_states: usize,
277    /// Whether to shrink the leaf state spaces by leaf simulation before
278    /// searching: the superfluous-transition rule of Torralba, Gnad,
279    /// Dubbert and Hoffmann (IJCAI 2016, Section 6 of the extended
280    /// technical report), with a removal order that makes it sound.
281    /// Default: `false`.
282    ///
283    /// On every analysed leaf (see [`Config::max_analysis_states`]), the
284    /// leaf simulation `⪯` of [`Pruning::Simulation`] is computed once.
285    /// Say that `x -b-> y'` *replaces* `x -a-> x'` if `cost(b) <= cost(a)`,
286    /// `b`'s center preconditions are contained in `a`'s, and `x' ⪯ y'`. A
287    /// leaf transition `x -a-> x'` is removed if
288    ///
289    /// 1. `x' ⪯ x`: staying at `x` is as good, or
290    /// 2. another leaf action `b` applicable in `x` replaces it, and either
291    ///    `a` does not replace `b` in turn or `b` has the smaller index.
292    ///
293    /// The report states rule 2 without the last condition and without a
294    /// removal order; read as one simultaneous step, it would remove both
295    /// of two transitions that replace each other (for example two copies
296    /// of one action), which is unsound. Removing one transition at a time,
297    /// each justified by one still present, removes exactly what the rules
298    /// above remove, up to which of two mutually replacing transitions
299    /// stays. The report also drops leaf states that become unreachable and
300    /// leaf actions without transitions; here leaf closure skips removed
301    /// transitions, so those states are never reached and stored
302    /// ([`Statistics::reduced_leaf_transitions`] and
303    /// [`Statistics::unreachable_leaf_states`] report the effect).
304    /// [`Config::reduced_task`] drops the operators left without a useful
305    /// transition, for building heuristics.
306    ///
307    /// *Soundness* (the report gives no proof). "Replaces" is reflexive and
308    /// transitive on the transitions leaving `x`; ordering by it, and by
309    /// index between transitions that replace each other, is a strict
310    /// partial order on a finite set, and rule 2 removes only transitions
311    /// below a greater one. Take any compliant leaf path `ρ` of the full
312    /// leaf system, and its first removed step `s_i -a-> s_{i+1}`.
313    /// Following rule 2 upwards ends in a maximal transition `s_i -c-> z`,
314    /// which rule 2 keeps, with `s_{i+1} ⪯ z` by transitivity; if rule 1
315    /// removes it, staying at `s_i` (`z ⪯ s_i`) is as good. `c` is
316    /// applicable wherever `a` was (weaker center preconditions) and no
317    /// dearer. By the simulation, the rest of `ρ` is mirrored from `z` (or
318    /// `s_i`) at no higher cost, in no more steps, meeting the same global
319    /// preconditions and ending in a goal leaf state. Repeating at the next
320    /// removed step terminates: each round either fixes one more step or
321    /// (staying) shortens the path. So every completion of the full system
322    /// has one of the reduced system at no higher cost, which preserves
323    /// optimality and solvability, and every reduced completion is a real
324    /// one. The dominance analyses still use the full transitions, which
325    /// only makes frontier and effective-price bounds more conservative,
326    /// and mirrored paths in the simulation bound are converted the same
327    /// way.
328    pub reduce_leaves: bool,
329    /// Whether to apply, in every expanded state, only the global actions
330    /// of a decoupled strong stubborn set (Gnad, Hoffmann and Wehrle, JAIR
331    /// 2019, Definitions 4 to 8, general star topologies, with the paper's
332    /// approximations). Default: `false`.
333    ///
334    /// The set is the closure of: in a non-goal state, the achievers of an
335    /// open part of the goal (a leaf fact no reached leaf state has, else a
336    /// leaf's goal part no single reached leaf state has, else a center
337    /// fact); in a goal state, the actions that could still lower some
338    /// leaf's goal price (none: the state is not expanded); for an
339    /// unreached action in the set, the achievers of an open part of its
340    /// precondition; for a reached one, every action that interferes with
341    /// it and has a consistent precondition, and every action leaving a
342    /// reached leaf state towards its leaf preconditions. The paper proves
343    /// that this keeps a strongly optimal decoupled plan, so uniform-cost
344    /// search, A* and anytime A* stay optimal and every search stays
345    /// complete. [`Statistics::stubborn_pruned`] counts what it removes.
346    ///
347    /// Where the paper's guarantee stops:
348    ///
349    /// - Tasks with conditional effects or axioms are searched with full
350    ///   expansion; the construction is not defined for them.
351    /// - The paper covers duplicate detection, not dominance pruning. For
352    ///   [`Pruning::Basic`], [`Pruning::Frontier`] and
353    ///   [`Pruning::EffectivePrices`] with [`Config::fold_g`] off, a
354    ///   dominating state can follow the pruned one's center path at no
355    ///   higher cost, which is the property the proof needs (an argument of
356    ///   this crate, not a proof). The other criteria, `fold_g`, and
357    ///   [`Config::reduce_leaves`] rest on the randomized cross-checks
358    ///   against Dijkstra only.
359    pub stubborn_sets: bool,
360    /// Whether to keep the pricing function of every leaf with at least
361    /// [`Config::symbolic_min_states`] states as binary decision diagrams,
362    /// one per price, instead of a price per enumerated leaf state (Gnad,
363    /// Torralba and Hoffmann 2017); smaller leaves stay enumerated. Needs
364    /// the `symbolic-leaves` feature. Default: `false`.
365    ///
366    /// The decoupled state space is the same as with explicit leaves, so
367    /// costs, plans and the number of expanded states agree; leaves larger
368    /// than [`crate::MAX_LEAF_STATES`] become searchable when their reached
369    /// sets have small diagrams. Supports every search and heuristic and
370    /// both [`Leaves`] modes, with [`Pruning::Basic`] (with or without
371    /// [`Config::fold_g`]) only; other criteria, [`Config::reduce_leaves`],
372    /// [`Config::stubborn_sets`], conditional effects and axioms are
373    /// rejected with [`Error::SymbolicUnsupported`].
374    pub symbolic_leaves: bool,
375    /// The fewest leaf states for which [`Config::symbolic_leaves`] uses
376    /// diagrams; 0 makes every leaf symbolic. Default: 1024, about where
377    /// diagrams start to pay off on the crate's benchmark.
378    pub symbolic_min_states: usize,
379    /// Whether to expand sets of center states at once: a search node is a
380    /// set of center states, kept as a BDD, that share one pricing function
381    /// and one `g`. Needs the `symbolic-leaves` feature; leaves follow
382    /// [`Config::symbolic_leaves`] and [`Config::symbolic_min_states`].
383    /// Default: `false`.
384    ///
385    /// This is the crate's own formulation, not a published one;
386    /// `docs/design.md` argues why it is sound, and the randomized
387    /// cross-checks against Dijkstra test it. Each member is an ordinary
388    /// decoupled state, so cost-optimal searches stay optimal; the nodes
389    /// differ from the explicit search's, so the counters do too. Supports uniform-cost search, A* and GBFS with
390    /// [`Pruning::Basic`] and [`Config::fold_g`] off, under the same
391    /// restrictions as [`Config::symbolic_leaves`]; anytime A* and `fold_g`
392    /// are rejected with [`Error::SymbolicUnsupported`]. Heuristics see a
393    /// center fact as reached when some member has it.
394    pub symbolic_center: bool,
395}
396
397impl Default for Config {
398    fn default() -> Self {
399        Self {
400            pruning: Pruning::default(),
401            fold_g: true,
402            leaves: Leaves::default(),
403            max_analysis_states: 256,
404            reduce_leaves: false,
405            stubborn_sets: false,
406            symbolic_leaves: false,
407            symbolic_min_states: 1024,
408            symbolic_center: false,
409        }
410    }
411}
412
413/// Counters of one search run.
414#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
415#[non_exhaustive]
416pub struct Statistics {
417    /// Decoupled states expanded (popped and not past the stopping key).
418    pub expanded: u64,
419    /// Successors generated, the initial state included.
420    pub generated: u64,
421    /// Generated states pruned because a stored state dominates them.
422    pub dominated: u64,
423    /// Generated states pruned because the heuristic declared them dead
424    /// ends.
425    pub dead_ends: u64,
426    /// States stored (and pushed on the open list).
427    pub stored: u64,
428    /// Leaf simulations computed (one per analysed leaf, if any criterion or
429    /// [`Config::reduce_leaves`] needed them).
430    pub simulated_leaves: u64,
431    /// Leaf transitions removed by [`Config::reduce_leaves`].
432    pub reduced_leaf_transitions: u64,
433    /// Generated states pruned by anytime A* ([`Config::anytime_astar`])
434    /// because `g` plus the fork heuristic reaches the best solution cost.
435    pub bound_pruned: u64,
436    /// Leaf states that [`Config::reduce_leaves`] made unreachable from the
437    /// initial leaf states (under every center).
438    pub unreachable_leaf_states: u64,
439    /// Applicable global actions that [`Config::stubborn_sets`] left out,
440    /// summed over the expanded states.
441    pub stubborn_pruned: u64,
442}
443
444/// The result of a search run: the plan, if any, and counters.
445#[derive(Clone, Debug, PartialEq, Eq)]
446#[non_exhaustive]
447pub struct Outcome {
448    /// The plan; `None` if the task is unsolvable.
449    pub plan: Option<Plan>,
450    /// What the search did.
451    pub statistics: Statistics,
452}
453
454/// A generated decoupled state.
455#[derive(Debug)]
456struct Node {
457    /// The decoupled state.
458    state: DecoupledState,
459    /// Cost of the global actions from the initial state.
460    g: Price,
461    /// Predecessor node and the index of the global action that led here;
462    /// `None` for the initial node.
463    parent: Option<(usize, usize)>,
464    /// The node's dominance bounds, computed on its first comparison.
465    bounds: Option<Bounds>,
466}
467
468/// Search bookkeeping: all nodes, the open list, the dominance store and the
469/// best solution found so far.
470struct Search<'t> {
471    /// The task being searched.
472    task: &'t DecoupledTask,
473    /// The heuristic; `None` means `h = 0` without computing fact prices.
474    /// Under [`Order::Anytime`], the fork heuristic that prunes against the
475    /// best solution.
476    heuristic: Option<&'t dyn DecoupledHeuristic>,
477    /// The root heuristic of [`Order::Anytime`], evaluated with every
478    /// reached fact at price 0; `None` otherwise.
479    root: Option<&'t dyn DecoupledHeuristic>,
480    /// A lower bound on the goal price of every decoupled goal state (see
481    /// [`min_goal_price`]); 0 unless [`Order::Anytime`].
482    min_goal_price: Price,
483    /// The open-list order.
484    order: Order,
485    /// The dominance criterion.
486    dominance: Dominance,
487    /// Every node that survived pruning, indexed by node id.
488    nodes: Vec<Node>,
489    /// Node ids ordered by their key (`g + h` or `h`).
490    open: BinaryHeap<Reverse<(Price, usize)>>,
491    /// Node ids per center state, for dominance checks.
492    by_center: BTreeMap<Vec<Value>, Vec<usize>>,
493    /// Cheapest solution cost so far and the node it ends in.
494    best: Option<(Price, usize)>,
495    /// Counters.
496    statistics: Statistics,
497    /// The most expansions to make; `None` for no limit.
498    limit: Option<u64>,
499    /// What a sample search measures.
500    probe: Probe,
501    /// The stubborn set construction; `None` for full expansion.
502    stubborn: Option<StubbornSets>,
503}
504
505/// Finds a cheapest plan for `task` by uniform-cost decoupled search over
506/// `factoring`, with the default [`Config`].
507///
508/// Returns `Ok(None)` if the task is unsolvable. A generated state is pruned
509/// when a stored state with the same center dominates it (see [`Pruning`]).
510///
511/// # Errors
512///
513/// - [`Error::InvalidTask`] if `task` does not validate.
514/// - [`Error::CenterEffectReadsLeaf`], [`Error::EffectConditionAcrossLeaves`]
515///   or [`Error::AxiomAcrossLeaves`] for conditional effects and axioms that
516///   decoupled search cannot express under `factoring`.
517/// - [`Error::DerivedInLeaf`] if `factoring` puts a derived variable in a
518///   leaf.
519/// - [`Error::FactoringMismatch`] or [`Error::LeafTooLarge`] if `factoring`
520///   was built for a different task.
521///
522/// # Examples
523///
524/// ```
525/// use decoupled_search::{Factoring, search};
526/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
527///
528/// // A truck (variable 0) and a package (variable 1) that rides along.
529/// let op = |name: &str, pre: Vec<Fact>, eff: Fact| Operator {
530///     name: name.into(),
531///     pre,
532///     eff: vec![Effect::new(eff)],
533///     cost: 1,
534/// };
535/// let task = Task {
536///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
537///     operators: vec![
538///         op("drive", vec![Fact::new(0, 0)], Fact::new(0, 1)),
539///         op("load", vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
540///         op("unload", vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
541///     ],
542///     initial: State(vec![0, 0]),
543///     goal: vec![Fact::new(1, 1)],
544///     axioms: vec![],
545/// };
546///
547/// let factoring = Factoring::fork(&task);
548/// assert_eq!(factoring.leaves(), &[vec![1]]);
549///
550/// let plan = search(&task, &factoring)?.expect("solvable");
551/// assert_eq!(plan.cost, 3);
552/// assert_eq!(plan.validate(&task), Ok(()));
553/// # Ok::<(), decoupled_search::Error>(())
554/// ```
555pub fn search(task: &Task, factoring: &Factoring) -> Result<Option<Plan>, Error> {
556    Config::default()
557        .search(task, factoring)
558        .map(|outcome| outcome.plan)
559}
560
561/// Finds a cheapest plan for `task` by decoupled A* over `factoring`, guided
562/// by `heuristic`, with the default [`Config`].
563///
564/// The plan is cost-optimal if `heuristic` is admissible in the sense of
565/// [`DecoupledHeuristic::estimate`], as [`crate::HMax`] is. Pruning is the
566/// same as in [`search()`]; states the heuristic declares dead ends are
567/// pruned too. Returns `Ok(None)` if the task is unsolvable.
568///
569/// # Errors
570///
571/// As [`search()`].
572///
573/// # Examples
574///
575/// See [`crate::HMax`].
576pub fn astar(
577    task: &Task,
578    factoring: &Factoring,
579    heuristic: &(impl DecoupledHeuristic + ?Sized),
580) -> Result<Option<Plan>, Error> {
581    Config::default()
582        .astar(task, factoring, heuristic)
583        .map(|outcome| outcome.plan)
584}
585
586/// Finds some plan for `task` by decoupled greedy best-first search over
587/// `factoring`, ordered by `heuristic` alone, with the default [`Config`],
588/// and returns the first one found. The plan is valid but not necessarily
589/// cheapest.
590///
591/// Dominance ignores costs here: a stored state dominates a generated one
592/// if it can do everything the generated one can, which preserves
593/// solvability. Returns `Ok(None)` if the task is unsolvable.
594///
595/// # Errors
596///
597/// As [`search()`].
598///
599/// # Examples
600///
601/// See [`crate::HFf`].
602pub fn gbfs(
603    task: &Task,
604    factoring: &Factoring,
605    heuristic: &(impl DecoupledHeuristic + ?Sized),
606) -> Result<Option<Plan>, Error> {
607    Config::default()
608        .gbfs(task, factoring, heuristic)
609        .map(|outcome| outcome.plan)
610}
611
612impl Config {
613    /// Uniform-cost decoupled search with this configuration; see
614    /// [`search()`].
615    ///
616    /// # Errors
617    ///
618    /// As [`search()`], and [`Error::ReachabilityNotOptimal`] with
619    /// [`Leaves::Reachability`].
620    pub fn search(&self, task: &Task, factoring: &Factoring) -> Result<Outcome, Error> {
621        self.run(task, factoring, (None, None), Order::Cost)
622    }
623
624    /// Decoupled A* with this configuration; see [`astar`].
625    ///
626    /// # Errors
627    ///
628    /// As [`Config::search`].
629    pub fn astar(
630        &self,
631        task: &Task,
632        factoring: &Factoring,
633        heuristic: &(impl DecoupledHeuristic + ?Sized),
634    ) -> Result<Outcome, Error> {
635        self.run(task, factoring, (Some(&heuristic), None), Order::Cost)
636    }
637
638    /// Decoupled greedy best-first search with this configuration; see
639    /// [`gbfs`]. With [`Leaves::Reachability`], states keep no prices.
640    ///
641    /// # Errors
642    ///
643    /// As [`search()`].
644    ///
645    /// # Examples
646    ///
647    /// ```
648    /// use decoupled_search::{Config, Factoring, HFf, Leaves};
649    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
650    ///
651    /// let op = |pre: Vec<Fact>, eff: Fact, cost| Operator {
652    ///     name: "op".into(),
653    ///     pre,
654    ///     eff: vec![Effect::new(eff)],
655    ///     cost,
656    /// };
657    /// let task = Task {
658    ///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
659    ///     operators: vec![
660    ///         op(vec![Fact::new(0, 0)], Fact::new(0, 1), 4),
661    ///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2), 2),
662    ///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1), 3),
663    ///     ],
664    ///     initial: State(vec![0, 0]),
665    ///     goal: vec![Fact::new(1, 1)],
666    ///     axioms: vec![],
667    /// };
668    ///
669    /// let config = Config { leaves: Leaves::Reachability, ..Config::default() };
670    /// let outcome = config.gbfs(&task, &Factoring::fork(&task), &HFf::new(&task))?;
671    /// let plan = outcome.plan.expect("solvable");
672    /// assert_eq!(plan.cost, 9, "costs are summed from the plan's operators");
673    /// assert_eq!(plan.validate(&task), Ok(()));
674    /// # Ok::<(), decoupled_search::Error>(())
675    /// ```
676    pub fn gbfs(
677        &self,
678        task: &Task,
679        factoring: &Factoring,
680        heuristic: &(impl DecoupledHeuristic + ?Sized),
681    ) -> Result<Outcome, Error> {
682        self.run(task, factoring, (Some(&heuristic), None), Order::Greedy)
683    }
684
685    /// Anytime decoupled A* (Gnad and Hoffmann's Anytime Fork-Root A*,
686    /// ICAPS 2015, generalised to star factorings): A* ordered by `g` plus
687    /// the `root` heuristic, which estimates only the cost of the remaining
688    /// global actions, with `fork` (an estimate of the whole remaining cost,
689    /// as for [`Config::astar`]) used to prune nodes that cannot beat the
690    /// best solution found so far.
691    ///
692    /// The root heuristic sees every reached leaf fact at price 0. Build it
693    /// on [`Factoring::with_free_leaf_actions`], for example
694    /// `HMax::new(&factoring.with_free_leaf_actions(&task)?)`: any
695    /// completion of a member state is then a plan of that task costing
696    /// only its global actions, so `h^max` there is root-admissible.
697    ///
698    /// The search records solutions when they are generated and stops once
699    /// the popped key plus the least goal price any decoupled goal state can
700    /// have (per leaf, the cheapest leaf-action cost from the initial leaf
701    /// state to a goal leaf state, global parts free, ignoring the center)
702    /// reaches the best solution cost, or when the open list is empty. This
703    /// subsumes the paper's early termination (an expanded goal whose goal
704    /// price equals that minimum) and is sound by the same argument as
705    /// [`Config::astar`]: while the optimum `C*` is not recorded, a node
706    /// covering it is open, with key at most `C*` minus its goal price.
707    /// Nodes with `g + fork` at least the best cost are pruned
708    /// ([`Statistics::bound_pruned`]), which cannot cut below `C*`.
709    ///
710    /// The plan is cost-optimal if `root` is root-admissible and `fork` is
711    /// admissible.
712    ///
713    /// # Errors
714    ///
715    /// As [`Config::search`].
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use decoupled_search::{Config, Factoring, HMax};
721    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
722    ///
723    /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
724    ///     name: "op".into(),
725    ///     pre,
726    ///     eff: vec![Effect::new(eff)],
727    ///     cost: 1,
728    /// };
729    /// let task = Task {
730    ///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
731    ///     operators: vec![
732    ///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
733    ///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
734    ///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
735    ///     ],
736    ///     initial: State(vec![0, 0]),
737    ///     goal: vec![Fact::new(1, 1)],
738    ///     axioms: vec![],
739    /// };
740    ///
741    /// let factoring = Factoring::fork(&task);
742    /// let root = HMax::new(&factoring.with_free_leaf_actions(&task)?);
743    /// let outcome = Config::default().anytime_astar(&task, &factoring, &root, &HMax::new(&task))?;
744    /// assert_eq!(outcome.plan.map(|p| p.cost), Some(3));
745    /// # Ok::<(), decoupled_search::Error>(())
746    /// ```
747    pub fn anytime_astar(
748        &self,
749        task: &Task,
750        factoring: &Factoring,
751        root: &(impl DecoupledHeuristic + ?Sized),
752        fork: &(impl DecoupledHeuristic + ?Sized),
753    ) -> Result<Outcome, Error> {
754        self.run(task, factoring, (Some(&fork), Some(&root)), Order::Anytime)
755    }
756
757    /// The search driver shared by all entry points.
758    ///
759    /// # Errors
760    ///
761    /// As [`Config::search`].
762    fn run(
763        &self,
764        task: &Task,
765        factoring: &Factoring,
766        (heuristic, root): (
767            Option<&dyn DecoupledHeuristic>,
768            Option<&dyn DecoupledHeuristic>,
769        ),
770        order: Order,
771    ) -> Result<Outcome, Error> {
772        self.probe(task, factoring, (heuristic, root), order, None)
773            .map(|(outcome, _)| outcome)
774    }
775
776    /// [`Config::run`] that stops after `limit` expansions, if given, and
777    /// also reports what a sample search measures.
778    ///
779    /// # Errors
780    ///
781    /// As [`Config::search`].
782    fn probe(
783        &self,
784        task: &Task,
785        factoring: &Factoring,
786        (heuristic, root): (
787            Option<&dyn DecoupledHeuristic>,
788            Option<&dyn DecoupledHeuristic>,
789        ),
790        order: Order,
791        limit: Option<u64>,
792    ) -> Result<(Outcome, Probe), Error> {
793        if self.symbolic_leaves || self.symbolic_center {
794            #[cfg(feature = "symbolic-leaves")]
795            return crate::symbolic::run(self, task, factoring, (heuristic, root), order)
796                .map(|outcome| (outcome, Probe::default()));
797            #[cfg(not(feature = "symbolic-leaves"))]
798            return Err(Error::SymbolicUnsupported {
799                option: "symbolic leaves or center without the symbolic-leaves feature",
800            });
801        }
802
803        let mut decoupled = DecoupledTask::new(task, factoring)?;
804        if self.leaves == Leaves::Reachability {
805            if order != Order::Greedy {
806                return Err(Error::ReachabilityNotOptimal);
807            }
808
809            decoupled = decoupled.into_reachability_only();
810        }
811
812        let dominance = Dominance::new(&decoupled, self, order == Order::Greedy);
813        let mut statistics = Statistics::default();
814        if self.reduce_leaves {
815            reduce_leaves(&mut decoupled, &dominance, &mut statistics);
816        }
817
818        let min_goal_price = if order == Order::Anytime {
819            min_goal_price(&decoupled)
820        } else {
821            0
822        };
823        let stubborn = self
824            .stubborn_sets
825            .then(|| StubbornSets::new(task, &decoupled))
826            .flatten();
827        let mut search = Search {
828            task: &decoupled,
829            heuristic,
830            root,
831            min_goal_price,
832            order,
833            dominance,
834            nodes: Vec::new(),
835            open: BinaryHeap::new(),
836            by_center: BTreeMap::new(),
837            best: None,
838            statistics,
839            limit,
840            probe: Probe::default(),
841            stubborn,
842        };
843        search.run();
844        search.statistics.simulated_leaves = search.dominance.simulated_leaves();
845
846        let plan = search.best.map(|(cost, id)| {
847            let plan = reconstruct::plan(&decoupled, &search.path(id), cost);
848            with_true_cost(task, plan, decoupled.is_reachability_only())
849        });
850
851        let outcome = Outcome {
852            plan,
853            statistics: search.statistics,
854        };
855        Ok((outcome, search.probe))
856    }
857}
858
859/// What a sample search measures (see [`sample`]).
860#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
861pub(crate) struct Probe {
862    /// Whether the search stopped at its expansion limit rather than by
863    /// finishing.
864    pub(crate) cut_off: bool,
865    /// Work units spent: per generated decoupled state, one plus the number
866    /// of leaf states its leaf closures range over.
867    pub(crate) work: u64,
868    /// The heuristic value of the initial state; `None` if it was pruned.
869    pub(crate) initial_h: Option<Price>,
870    /// The least heuristic value of any stored state.
871    pub(crate) best_h: Option<Price>,
872}
873
874/// A sample search for factoring selection: decoupled A* with `h^max`
875/// (cost-optimal) or greedy best-first search with `h^FF` (not), each with
876/// the default [`Config`], stopped after `expansions` expansions. Returns
877/// the probe and the number of expansions.
878///
879/// # Errors
880///
881/// As [`Config::search`].
882pub(crate) fn sample(
883    task: &Task,
884    factoring: &Factoring,
885    optimal: bool,
886    expansions: u64,
887) -> Result<(Probe, u64), Error> {
888    let config = Config::default();
889    let (outcome, probe) = if optimal {
890        let h = crate::HMax::new(task);
891        config.probe(
892            task,
893            factoring,
894            (Some(&h), None),
895            Order::Cost,
896            Some(expansions),
897        )?
898    } else {
899        let h = crate::HFf::new(task);
900        config.probe(
901            task,
902            factoring,
903            (Some(&h), None),
904            Order::Greedy,
905            Some(expansions),
906        )?
907    };
908
909    Ok((probe, outcome.statistics.expanded))
910}
911
912impl Config {
913    /// `task` without the operators that [`Config::reduce_leaves`] makes
914    /// useless under `factoring`, for building heuristics (the last step of
915    /// the leaf reduction in Torralba, Gnad, Dubbert and Hoffmann's
916    /// technical report).
917    ///
918    /// An operator is removed if it is a leaf action of an analysed leaf
919    /// (see [`Config::max_analysis_states`]) and none of its kept leaf
920    /// transitions starts in a leaf state that the reduced leaf can still
921    /// reach (over kept leaf actions and global parts, under any center).
922    /// Variables, goal and the remaining operators are unchanged, so fact
923    /// prices of the search fit heuristics built on the result.
924    ///
925    /// *Soundness.* Only use heuristics built on the result in searches
926    /// with `reduce_leaves: true`, the same `factoring` and the same
927    /// `max_analysis_states`. There, every reached leaf state is reachable
928    /// in the reduced leaf, and by the soundness argument on
929    /// [`Config::reduce_leaves`] every decoupled state has a cheapest
930    /// completion that uses only kept transitions from such states, hence
931    /// only operators of the result. A heuristic admissible on the result
932    /// is therefore admissible for the search, and fewer operators can only
933    /// raise its estimates. Without leaf reduction in the search the
934    /// estimates may exceed the true cost.
935    ///
936    /// The result is the same for both [`Leaves`] modes: the simulation
937    /// and the removed transitions do not depend on it.
938    ///
939    /// # Errors
940    ///
941    /// As [`Config::search`], except that [`Config::leaves`] is ignored.
942    ///
943    /// # Examples
944    ///
945    /// ```
946    /// use decoupled_search::{Config, Factoring, HMax, Pruning};
947    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
948    ///
949    /// // A truck over three locations and a package (3: in the truck) that
950    /// // must go from location 0 to location 1.
951    /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
952    ///     name: "op".into(),
953    ///     pre,
954    ///     eff: vec![Effect::new(eff)],
955    ///     cost: 1,
956    /// };
957    /// let mut operators = Vec::new();
958    /// for x in 0..3 {
959    ///     for y in (0..3).filter(|&y| y != x) {
960    ///         operators.push(op(vec![Fact::new(0, x)], Fact::new(0, y)));
961    ///     }
962    ///     operators.push(op(vec![Fact::new(0, x), Fact::new(1, x)], Fact::new(1, 3)));
963    ///     operators.push(op(vec![Fact::new(0, x), Fact::new(1, 3)], Fact::new(1, x)));
964    /// }
965    /// let task = Task {
966    ///     variables: vec![Variable::new("truck", 3), Variable::new("pkg", 4)],
967    ///     operators,
968    ///     initial: State(vec![0, 0]),
969    ///     goal: vec![Fact::new(1, 1)],
970    ///     axioms: vec![],
971    /// };
972    ///
973    /// let config = Config { reduce_leaves: true, ..Config::default() };
974    /// let factoring = Factoring::fork(&task);
975    /// let reduced = config.reduced_task(&task, &factoring)?;
976    /// // Only loading at 0 and unloading at 1 remain of the package's six.
977    /// assert_eq!(reduced.operators.len(), task.operators.len() - 4);
978    ///
979    /// let outcome = config.astar(&task, &factoring, &HMax::new(&reduced))?;
980    /// assert_eq!(outcome.plan.map(|p| p.cost), Some(3));
981    /// # Ok::<(), decoupled_search::Error>(())
982    /// ```
983    pub fn reduced_task(&self, task: &Task, factoring: &Factoring) -> Result<Task, Error> {
984        let mut decoupled = DecoupledTask::new(task, factoring)?;
985        let config = Config {
986            reduce_leaves: true,
987            ..*self
988        };
989        let dominance = Dominance::new(&decoupled, &config, false);
990        reduce_leaves(&mut decoupled, &dominance, &mut Statistics::default());
991
992        let mut removed = vec![false; task.operators.len()];
993        for (index, leaf) in decoupled.leaves.iter().enumerate() {
994            if dominance.simulators(index).is_none() {
995                continue;
996            }
997
998            let parts: Vec<_> = decoupled
999                .globals
1000                .iter()
1001                .filter_map(|g| g.parts[index].as_ref())
1002                .collect();
1003            let live = simulation::live_actions(leaf, &parts);
1004            for (action, live) in leaf.actions.iter().zip(live) {
1005                removed[action.op] |= !live;
1006            }
1007        }
1008
1009        let mut reduced = task.clone();
1010        let mut keep = removed.iter().map(|&r| !r);
1011        reduced.operators.retain(|_| keep.next().unwrap_or(true));
1012        Ok(reduced)
1013    }
1014}
1015
1016/// A lower bound on the goal price of every decoupled goal state of `task`:
1017/// per leaf, the cheapest leaf-action cost from the initial leaf state to a
1018/// goal leaf state, global parts free, ignoring the center (0 for leaves
1019/// whose transitions read the center); [`Price::MAX`] if some leaf can
1020/// never reach its goal.
1021fn min_goal_price(task: &DecoupledTask) -> Price {
1022    task.leaves
1023        .iter()
1024        .enumerate()
1025        .map(|(index, leaf)| {
1026            let parts: Vec<_> = task
1027                .globals
1028                .iter()
1029                .filter_map(|g| g.parts[index].as_ref())
1030                .collect();
1031            if leaf.reads_center(parts.iter().copied()) {
1032                return 0;
1033            }
1034
1035            simulation::cheapest_goal(leaf, &parts).unwrap_or(Price::MAX)
1036        })
1037        .fold(0, Price::saturating_add)
1038}
1039
1040/// Removes the redundant leaf transitions of every leaf with a simulation
1041/// (see [`Config::reduce_leaves`]) and counts the effect.
1042fn reduce_leaves(task: &mut DecoupledTask, dominance: &Dominance, statistics: &mut Statistics) {
1043    let widen = |n: usize| u64::try_from(n).unwrap_or(u64::MAX);
1044    for leaf in 0..task.leaves.len() {
1045        let Some(rel) = dominance.simulators(leaf) else {
1046            continue;
1047        };
1048
1049        let parts: Vec<_> = task
1050            .globals
1051            .iter()
1052            .filter_map(|g| g.parts[leaf].as_ref())
1053            .collect();
1054        let (disabled, lost) = simulation::redundant_transitions(&task.leaves[leaf], &parts, rel);
1055        statistics.reduced_leaf_transitions += widen(disabled.iter().filter(|&&d| d).count());
1056        statistics.unreachable_leaf_states += widen(lost);
1057        task.leaves[leaf].disabled = disabled;
1058    }
1059}
1060
1061/// `plan` with its cost summed from its operators. Without leaf costs in
1062/// the search this is the only correct cost; otherwise it equals the search
1063/// cost, which a debug assertion checks.
1064pub(crate) fn with_true_cost(task: &Task, mut plan: Plan, reachability_only: bool) -> Plan {
1065    let summed = plan
1066        .ops
1067        .iter()
1068        .map(|&op| u64::from(task.operators[op].cost))
1069        .sum();
1070    debug_assert!(
1071        reachability_only || summed == plan.cost,
1072        "search cost {} differs from plan cost {summed}",
1073        plan.cost
1074    );
1075    plan.cost = summed;
1076    plan
1077}
1078
1079impl Search<'_> {
1080    /// Inserts the initial state and expands nodes until the open list is
1081    /// empty or [`Search::is_done`].
1082    fn run(&mut self) {
1083        self.insert(self.task.initial(), 0, None);
1084
1085        while let Some(Reverse((key, id))) = self.open.pop() {
1086            if self.is_done(key) {
1087                break;
1088            }
1089
1090            if self
1091                .limit
1092                .is_some_and(|limit| self.statistics.expanded >= limit)
1093            {
1094                self.probe.cut_off = true;
1095                break;
1096            }
1097
1098            self.statistics.expanded += 1;
1099            let node = &self.nodes[id];
1100            let g = node.g;
1101            let successors = match self.stubborn.as_mut() {
1102                None => self.task.successors(&node.state),
1103                Some(stubborn) => {
1104                    let (allowed, pruned) = stubborn.allowed(self.task, &node.state);
1105                    self.statistics.stubborn_pruned += pruned;
1106                    (0..allowed.len())
1107                        .filter(|&i| allowed[i])
1108                        .filter_map(|i| self.task.successor(i, &node.state).map(|s| (i, s)))
1109                        .collect()
1110                }
1111            };
1112            for (action, state) in successors {
1113                let g = g.saturating_add(self.task.globals[action].cost);
1114                self.insert(state, g, Some((id, action)));
1115            }
1116        }
1117    }
1118
1119    /// Whether the search can stop before expanding a node with open-list
1120    /// key `key`: greedy search once any solution is known, otherwise once
1121    /// `key` reaches the best solution cost (keys are lower bounds).
1122    fn is_done(&self, key: Price) -> bool {
1123        match self.order {
1124            Order::Cost => self.best.is_some_and(|(cost, _)| key >= cost),
1125            Order::Anytime => self
1126                .best
1127                .is_some_and(|(cost, _)| key.saturating_add(self.min_goal_price) >= cost),
1128            Order::Greedy => self.best.is_some(),
1129        }
1130    }
1131
1132    /// The heuristic estimate of `state`; 0 without a heuristic, `None` for
1133    /// a dead end.
1134    fn estimate(&self, state: &DecoupledState) -> Option<Price> {
1135        self.heuristic
1136            .map_or(Some(0), |h| h.estimate(&self.task.fact_prices(state)))
1137    }
1138
1139    /// The open-list key of `state` reached at `g` with heuristic value `h`;
1140    /// `None` if the root heuristic of [`Order::Anytime`] declares it a dead
1141    /// end.
1142    fn key(&self, state: &DecoupledState, g: Price, h: Price) -> Option<Price> {
1143        match self.order {
1144            Order::Cost => Some(g.saturating_add(h)),
1145            Order::Greedy => Some(h),
1146            Order::Anytime => {
1147                let root = self.root.map_or(Some(0), |r| {
1148                    r.estimate(&self.task.fact_prices(state).reached_for_free())
1149                })?;
1150                Some(g.saturating_add(root))
1151            }
1152        }
1153    }
1154
1155    /// Adds `state` reached at cost `g` unless a stored node dominates it or
1156    /// the heuristic declares it a dead end, and records it as the best
1157    /// solution if it is one.
1158    fn insert(&mut self, state: DecoupledState, g: Price, parent: Option<(usize, usize)>) {
1159        self.statistics.generated += 1;
1160        let work = self.task.leaves.iter().map(|l| l.size).sum::<usize>() + 1;
1161        let work = u64::try_from(work).unwrap_or(u64::MAX);
1162        self.probe.work = self.probe.work.saturating_add(work);
1163        if self.dominance.record_work(self.task, work) {
1164            for node in &mut self.nodes {
1165                node.bounds = None;
1166            }
1167        }
1168
1169        if self.is_dominated(&state, g) {
1170            self.statistics.dominated += 1;
1171            return;
1172        }
1173
1174        let Some(h) = self.estimate(&state) else {
1175            self.statistics.dead_ends += 1;
1176            return;
1177        };
1178
1179        self.probe.initial_h.get_or_insert(h);
1180        let Some(key) = self.key(&state, g, h) else {
1181            self.statistics.dead_ends += 1;
1182            return;
1183        };
1184
1185        if self.order == Order::Anytime
1186            && self
1187                .best
1188                .is_some_and(|(best, _)| g.saturating_add(h) >= best)
1189        {
1190            self.statistics.bound_pruned += 1;
1191            return;
1192        }
1193
1194        let id = self.nodes.len();
1195        if let Some(rest) = self.task.goal_price(&state) {
1196            let cost = g.saturating_add(rest);
1197            if self.best.is_none_or(|(best, _)| cost < best) {
1198                self.best = Some((cost, id));
1199            }
1200        }
1201
1202        self.by_center
1203            .entry(state.center.clone())
1204            .or_default()
1205            .push(id);
1206        self.probe.best_h = Some(self.probe.best_h.map_or(h, |b| b.min(h)));
1207        self.open.push(Reverse((key, id)));
1208        self.nodes.push(Node {
1209            state,
1210            g,
1211            parent,
1212            bounds: None,
1213        });
1214        self.statistics.stored += 1;
1215    }
1216
1217    /// Whether a stored node with the same center dominates `state`
1218    /// reached at `g`, under the configured criterion.
1219    ///
1220    /// shortcut: linear scan per center state; index the store (for
1221    /// example by reached-leaf-state sets) when stores get long.
1222    fn is_dominated(&mut self, state: &DecoupledState, g: Price) -> bool {
1223        let Some(ids) = self.by_center.get(&state.center) else {
1224            return false;
1225        };
1226
1227        let frontier = self.dominance.frontier(self.task, state);
1228        for &id in ids {
1229            let node = &mut self.nodes[id];
1230            let bounds = node
1231                .bounds
1232                .get_or_insert_with(|| self.dominance.bounds(self.task, &node.state));
1233            if self
1234                .dominance
1235                .dominates((&node.state, node.g, bounds), (state, g, &frontier))
1236            {
1237                return true;
1238            }
1239        }
1240
1241        false
1242    }
1243
1244    /// The path from the initial node to node `id`, as
1245    /// `(global action index that led here, state)`, initial node first.
1246    fn path(&self, mut id: usize) -> Vec<(Option<usize>, &DecoupledState)> {
1247        let mut path = Vec::new();
1248        loop {
1249            let node = &self.nodes[id];
1250            path.push((node.parent.map(|(_, a)| a), &node.state));
1251            match node.parent {
1252                Some((parent, _)) => id = parent,
1253                None => break,
1254            }
1255        }
1256
1257        path.reverse();
1258        path
1259    }
1260}