Skip to main content

game_tree_search/
alpha_beta.rs

1//! Alpha-beta pruning: minimax that skips moves which cannot change the decision.
2
3use alloc::vec::Vec;
4
5use core::mem;
6
7use search_core::Budget;
8
9use crate::incremental::{Borrowed, Place};
10use crate::minimax::improves;
11use crate::table::{Entry, Memory};
12use crate::{Algorithm, Bound, Game, Score, ScoredMove, SearchResult, Searcher, Side, Stats};
13
14/// Searches `position` up to `depth` plies with fail-soft alpha-beta pruning.
15///
16/// Returns the [`minimax()`](crate::minimax()) score while visiting far fewer positions,
17/// most so when [`Game::order_moves`] puts good moves first. Like minimax, the side to move
18/// comes from [`Game::side_to_move`], so one side may move several times in a row.
19///
20/// With the default [`Game::satisfices`], the root score is the minimax value and its bound
21/// is [`Bound::Exact`]; the best root move is exact too, while the other
22/// [`SearchResult::root_moves`] are often only bounded. A game that overrides
23/// [`Game::satisfices`] trades that exactness for speed, as documented there.
24///
25/// Allocates its working buffers on every call; [`Searcher::search`] reuses them across
26/// searches.
27///
28/// # Examples
29///
30/// ```
31/// # use game_tree_search::{Game, Side};
32/// # struct Nim;
33/// # impl Game for Nim {
34/// #     type Position = (u32, Side);
35/// #     type Move = u32;
36/// #     type Score = i32;
37/// #     fn side_to_move(&self, &(_, side): &Self::Position) -> Side { side }
38/// #     fn moves(&self, &(stones, _): &Self::Position, moves: &mut Vec<u32>) {
39/// #         moves.extend((1..=2).filter(|&take| take <= stones));
40/// #     }
41/// #     fn play(&self, &(stones, side): &Self::Position, take: &u32) -> Self::Position {
42/// #         (stones - take, if side == Side::Max { Side::Min } else { Side::Max })
43/// #     }
44/// #     fn evaluate(&self, &(stones, side): &Self::Position) -> i32 {
45/// #         match (stones, side) { (0, Side::Max) => -1, (0, Side::Min) => 1, _ => 0 }
46/// #     }
47/// # }
48/// use game_tree_search::{Bound, alpha_beta, minimax};
49///
50/// let root = (10, Side::Max);
51/// let pruned = alpha_beta(&Nim, &root, 10);
52/// let full = minimax(&Nim, &root, 10);
53/// assert_eq!((pruned.score, pruned.bound), (full.score, Bound::Exact));
54/// assert!(pruned.stats.nodes < full.stats.nodes);
55/// ```
56#[must_use]
57pub fn alpha_beta<G: Game>(
58    game: &G,
59    position: &G::Position,
60    depth: u32,
61) -> SearchResult<G::Move, G::Score> {
62    Searcher::new().search(game, position, depth)
63}
64
65impl<G: Game, T: Memory<G>> Searcher<G, T> {
66    /// Searches `position` up to `depth` plies with this searcher's [`Algorithm`], reusing its
67    /// buffers and table.
68    ///
69    /// Returns what [`alpha_beta()`](crate::alpha_beta()), [`pvs()`](crate::pvs()) or
70    /// [`mtdf()`](crate::mtdf()) return. Once the buffers have grown to the search depth, a
71    /// search allocates only the [`SearchResult`] it returns.
72    #[must_use]
73    pub fn search(
74        &mut self,
75        game: &G,
76        position: &G::Position,
77        depth: u32,
78    ) -> SearchResult<G::Move, G::Score> {
79        self.search_from(game, &mut Borrowed(position), depth)
80    }
81
82    /// [`Searcher::search`] from the root `here`.
83    pub(crate) fn search_from(
84        &mut self,
85        game: &G,
86        here: &mut impl Place<G>,
87        depth: u32,
88    ) -> SearchResult<G::Move, G::Score> {
89        self.stats = Stats::ZERO;
90        self.hint.clear();
91        self.guess = None;
92        let mut unlimited = |_: &Stats| false;
93        let mut run = Run {
94            game,
95            budget: &mut unlimited,
96        };
97
98        let node = self.iterate(&mut run, here, depth, Window::FULL);
99        self.result(&node, depth)
100    }
101
102    /// One search of `position` to `depth` with the searcher's algorithm within `window`,
103    /// trying the hint's moves first; MTD(f) ignores `window` and picks its own.
104    ///
105    /// Adds to the searcher's counters instead of resetting them. If the budget stopped the
106    /// search, the searcher's abort flag is set and the node must be discarded.
107    pub(crate) fn iterate<B: Budget<Stats>, H: Place<G>>(
108        &mut self,
109        run: &mut Run<'_, G, B>,
110        here: &mut H,
111        depth: u32,
112        window: Window<G::Score>,
113    ) -> Node<G::Score> {
114        self.aborted = false;
115        if self.algorithm == Algorithm::Mtdf {
116            return self.mtdf(run, here, depth);
117        }
118
119        self.root(run, here, depth, window)
120    }
121
122    /// One search of the root `position` to `depth` within `window`, leaving its line and
123    /// root moves in the searcher's buffers.
124    pub(crate) fn root<B: Budget<Stats>, H: Place<G>>(
125        &mut self,
126        run: &mut Run<'_, G, B>,
127        here: &mut H,
128        depth: u32,
129        window: Window<G::Score>,
130    ) -> Node<G::Score> {
131        let mut root_moves = mem::take(&mut self.root_moves);
132        root_moves.clear();
133        let frame = Frame {
134            ply: 0,
135            depth,
136            window,
137            on_hint: true,
138        };
139        let node = self.visit(run, here, frame, Some(&mut root_moves));
140        self.root_moves = root_moves;
141
142        node
143    }
144
145    /// The result of the last root search, which returned `node` at `depth`.
146    pub(crate) fn result(
147        &self,
148        node: &Node<G::Score>,
149        depth: u32,
150    ) -> SearchResult<G::Move, G::Score> {
151        SearchResult {
152            score: node.score,
153            bound: node.bound,
154            pv: self.line(0).to_vec(),
155            root_moves: self.root_moves.clone(),
156            unexamined: node.skipped,
157            depth,
158            proven: node.proven,
159            stats: self.stats,
160        }
161    }
162
163    /// Searches the position at `frame`, recording every child in `root_moves` (given only at
164    /// the root).
165    ///
166    /// Leaves the position's principal variation in the line buffer of its ply. Once the
167    /// budget is exhausted, it sets the searcher's abort flag and returns at once.
168    fn visit<B: Budget<Stats>, H: Place<G>>(
169        &mut self,
170        run: &mut Run<'_, G, B>,
171        here: &mut H,
172        frame: Frame<G::Score>,
173        root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
174    ) -> Node<G::Score> {
175        let game = run.game;
176        if run.budget.exhausted(&self.stats) {
177            self.aborted = true;
178            return Node::horizon(game.evaluate(here.position()));
179        }
180
181        self.stats
182            .visit(u32::try_from(frame.ply).expect("a ply never exceeds the u32 search depth"));
183        let mut moves = self.enter(frame.ply);
184        if frame.depth == 0 {
185            return self.quiesce(run, here, frame, moves, root_moves);
186        }
187
188        game.moves(here.position(), &mut moves);
189        if moves.is_empty() {
190            self.leave(frame.ply, moves);
191            return Node::leaf(game.evaluate(here.position()));
192        }
193
194        self.order(game, here.position(), &mut moves);
195
196        let key = self.table.key(game, here.position());
197        let stored = self.table.recall(&key);
198        if let Some(node) = stored.as_ref().and_then(|entry| answer(entry, frame)) {
199            self.stats.table_hits += 1;
200            self.leave(frame.ply, moves);
201            return node;
202        }
203
204        if let Some(best) = stored.and_then(|entry| entry.best) {
205            promote(&mut moves, &best);
206        }
207
208        let hint = self.promote_hint(&mut moves, frame);
209        let expansion = Expansion {
210            moves,
211            hint,
212            stand: None,
213        };
214        let node = self.expand(run, here, frame, expansion, root_moves);
215        if !self.aborted {
216            let entry = self.entry(&node, frame);
217            self.table.remember(key, entry);
218        }
219
220        node
221    }
222
223    /// The table entry for the position at `frame`, just searched to `node`.
224    fn entry(&self, node: &Node<G::Score>, frame: Frame<G::Score>) -> Entry<G::Move, G::Score> {
225        Entry {
226            depth: frame.depth,
227            score: node.score,
228            bound: node.bound,
229            best: self.line(frame.ply).first().map(|step| step.mv.clone()),
230            proven: node.proven,
231            reach: node.reach,
232        }
233    }
234
235    /// Quiescence at the horizon position at `frame`: its evaluation, unless one of its
236    /// [`Game::noisy_moves`] beats it, searched the same way below. `moves` is the ply's empty
237    /// move list; `root_moves`, given only at a depth-0 root, records the noisy moves tried.
238    fn quiesce<B: Budget<Stats>, H: Place<G>>(
239        &mut self,
240        run: &mut Run<'_, G, B>,
241        here: &mut H,
242        frame: Frame<G::Score>,
243        mut moves: Vec<G::Move>,
244        root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
245    ) -> Node<G::Score> {
246        let game = run.game;
247        self.stats.horizon += 1;
248        let stand = Node::horizon(game.evaluate(here.position()));
249        game.noisy_moves(here.position(), &mut moves);
250        if moves.is_empty() {
251            self.leave(frame.ply, moves);
252            return stand;
253        }
254
255        self.order(game, here.position(), &mut moves);
256        let hint = self.promote_hint(&mut moves, frame);
257        let expansion = Expansion {
258            moves,
259            hint,
260            stand: Some(stand),
261        };
262        self.expand(run, here, frame, expansion, root_moves)
263    }
264
265    /// Puts `moves`, not empty, in the game's order, then keeps the first move and rotates the
266    /// rest by the searcher's skew, so a Lazy SMP helper searches the alternatives in its own
267    /// order while still trying the game's best guess first.
268    fn order(&self, game: &G, position: &G::Position, moves: &mut [G::Move]) {
269        game.order_moves(position, moves);
270        if let Some((_, rest)) = moves.split_first_mut().filter(|(_, rest)| !rest.is_empty()) {
271            let skew = self.skew % rest.len();
272            rest.rotate_left(skew);
273        }
274    }
275
276    /// Moves the hint's move for this ply to the front of `moves`, if the line to the
277    /// position follows the hint and the move is legal here; returns it.
278    fn promote_hint(&self, moves: &mut [G::Move], frame: Frame<G::Score>) -> Option<G::Move> {
279        let hint = self.hint.get(frame.ply).filter(|_| frame.on_hint)?;
280
281        promote(moves, hint).then(|| hint.clone())
282    }
283
284    /// Searches the `moves` of the position at `frame`, `hint` among them, until one of them
285    /// stops the search there; in quiescence, `stand` is the score to beat.
286    fn expand<B: Budget<Stats>, H: Place<G>>(
287        &mut self,
288        run: &mut Run<'_, G, B>,
289        here: &mut H,
290        frame: Frame<G::Score>,
291        expansion: Expansion<G::Move, G::Score>,
292        mut root_moves: Option<&mut Vec<ScoredMove<G::Move, G::Score>>>,
293    ) -> Node<G::Score> {
294        let Expansion {
295            mut moves,
296            hint,
297            stand,
298        } = expansion;
299        let game = run.game;
300        let side = game.side_to_move(here.position());
301        let total = moves.len();
302        let mut window = frame.window;
303        if let Some(stand) = stand {
304            window.tighten(side, stand.score);
305        }
306
307        let mut best = stand;
308        let (mut widened, mut proven, mut searched, mut reach) = (false, stand.is_none(), 0, 0);
309        for mv in moves.drain(..) {
310            if best.is_some_and(|best| stops(game, side, best.score, &window)) {
311                break;
312            }
313
314            searched += 1;
315            let child_frame = frame.child(window, hint.as_ref() == Some(&mv));
316            let later = best.is_some();
317            let child = here.descend(game, &mv, |child| {
318                self.child(run, child, child_frame, (side, later))
319            });
320            if self.aborted {
321                break;
322            }
323
324            let step = ScoredMove {
325                mv,
326                score: child.score,
327                bound: child.bound,
328            };
329            if let Some(root_moves) = root_moves.as_deref_mut() {
330                root_moves.push(step.clone());
331            }
332
333            widened |= child.bound.widens(side);
334            proven &= child.proven;
335            reach = reach.max(child.reach + 1);
336            window.tighten(side, child.score);
337            if best.is_none_or(|best| improves(side, child.score, best.score)) {
338                best = Some(child);
339                self.adopt(frame.ply, step);
340            }
341        }
342
343        self.leave(frame.ply, moves);
344        let Some(best) = best else {
345            return Node::horizon(game.evaluate(here.position()));
346        };
347
348        let node = Node {
349            proven,
350            reach,
351            ..best
352        };
353        self.finish(side, node, total - searched, widened)
354    }
355
356    /// Searches the child at `frame`, a move of `side`'s.
357    ///
358    /// With [`Algorithm::Pvs`], a child after the first (`later`) is scouted first with a
359    /// null window at the edge of `frame`'s window, which only tells whether it beats that
360    /// edge; only a child that does is searched again with the full window. The first child
361    /// is searched with the full window right away, as it is expected to be the best.
362    #[inline]
363    fn child<B: Budget<Stats>, H: Place<G>>(
364        &mut self,
365        run: &mut Run<'_, G, B>,
366        here: &mut H,
367        frame: Frame<G::Score>,
368        (side, later): (Side, bool),
369    ) -> Node<G::Score> {
370        let scout = frame
371            .window
372            .null(side)
373            .filter(|_| later && self.algorithm == Algorithm::Pvs);
374        if let Some(window) = scout {
375            let node = self.visit(run, here, Frame { window, ..frame }, None);
376            if self.aborted || !frame.window.needs_research(&node) {
377                return node;
378            }
379
380            self.stats.researches += 1;
381        }
382
383        self.visit(run, here, frame, None)
384    }
385
386    /// The position's result from its best child, the moves `skipped` and whether a searched
387    /// child `widened` the value.
388    fn finish(
389        &mut self,
390        side: Side,
391        best: Node<G::Score>,
392        skipped: usize,
393        widened: bool,
394    ) -> Node<G::Score> {
395        let cut = skipped > 0;
396        if cut && !self.aborted {
397            self.stats.cuts += 1;
398        }
399
400        Node {
401            bound: Bound::combine(side, cut, best.bound, widened),
402            skipped,
403            ..best
404        }
405    }
406}
407
408/// Moves `mv` to the front of `moves`, keeping the others in order; whether it was there.
409fn promote<M: PartialEq>(moves: &mut [M], mv: &M) -> bool {
410    let Some(index) = moves.iter().position(|candidate| candidate == mv) else {
411        return false;
412    };
413
414    moves[..=index].rotate_right(1);
415    true
416}
417
418/// The node `entry` answers at `frame` without a search; `None` if the position must be
419/// searched.
420///
421/// An exact entry answers, and so does a bound already outside `frame`'s window. A bound
422/// never narrows the window: a search inside a narrowed window could return only a bound
423/// where the full search is exact. The root is always searched, so it can report every move
424/// it tries.
425fn answer<M, S: Ord + Copy>(entry: &Entry<M, S>, frame: Frame<S>) -> Option<Node<S>> {
426    if frame.ply == 0 || !entry.serves(frame.depth) {
427        return None;
428    }
429
430    let answers = match entry.bound {
431        Bound::Exact => true,
432        Bound::Lower => frame.window.closes(Side::Max, entry.score),
433        Bound::Upper => frame.window.closes(Side::Min, entry.score),
434        Bound::Approximate => false,
435    };
436
437    answers.then(|| Node::stored(entry))
438}
439
440/// Whether `side`, holding `score`, skips its remaining moves: a window cutoff, or the game
441/// is satisfied.
442fn stops<G: Game>(game: &G, side: Side, score: G::Score, window: &Window<G::Score>) -> bool {
443    window.closes(side, score) || game.satisfices(side, score)
444}
445
446/// The moves a position searches: all of them, or in quiescence the noisy ones.
447struct Expansion<M, S> {
448    /// The moves to search, in the order to search them.
449    moves: Vec<M>,
450    /// The hint's move among them, if the line follows the hint.
451    hint: Option<M>,
452    /// In quiescence, the position's own evaluation, kept unless a move beats it.
453    stand: Option<Node<S>>,
454}
455
456/// What one search run works with besides the searcher: the game and the budget.
457pub(crate) struct Run<'a, G, B> {
458    /// The game searched.
459    pub(crate) game: &'a G,
460    /// Stops the run early; asked before every position visited.
461    pub(crate) budget: &'a mut B,
462}
463
464/// Where a position sits in the search: its ply, the plies left, its window and whether the
465/// line to it follows the searcher's hint.
466#[derive(Debug, Clone, Copy)]
467struct Frame<S> {
468    /// Moves played from the root to the position.
469    ply: usize,
470    /// Plies left to search below the position.
471    depth: u32,
472    /// The scores still worth telling apart.
473    window: Window<S>,
474    /// Whether every move to the position is the hint's move at its ply.
475    on_hint: bool,
476}
477
478impl<S> Frame<S> {
479    /// The frame of a child within `window`, reached by the hint's move if `hinted`.
480    const fn child(&self, window: Window<S>, hinted: bool) -> Self {
481        Self {
482            ply: self.ply + 1,
483            depth: self.depth.saturating_sub(1),
484            window,
485            on_hint: self.on_hint && hinted,
486        }
487    }
488}
489
490/// The scores still worth telling apart at a position, from [`Side::Max`]'s point of view.
491///
492/// With the default [`Game::satisfices`], a search within a window returns the exact score
493/// if it lies strictly inside, and only a bound otherwise; a game that satisfices can get a
494/// bound either way. `None` is unbounded on that side. Used to give deepening an aspiration
495/// window, see [`Deepening::window`](crate::Deepening::window).
496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
497pub struct Window<S> {
498    /// The score [`Side::Max`] is already sure of elsewhere: scores at or below it need not
499    /// be told apart.
500    pub alpha: Option<S>,
501    /// The score [`Side::Min`] is already sure of elsewhere: scores at or above it need not
502    /// be told apart.
503    pub beta: Option<S>,
504}
505
506impl<S> Window<S> {
507    /// The window that tells every score apart.
508    pub const FULL: Self = Self {
509        alpha: None,
510        beta: None,
511    };
512}
513
514impl<S: Ord + Copy> Window<S> {
515    /// Whether the window is unbounded on both sides.
516    pub(crate) const fn is_full(&self) -> bool {
517        self.alpha.is_none() && self.beta.is_none()
518    }
519
520    /// Whether `side`, holding `score`, can no longer affect the decision above.
521    fn closes(&self, side: Side, score: S) -> bool {
522        match side {
523            Side::Max => self.beta.is_some_and(|beta| score >= beta),
524            Side::Min => self.alpha.is_some_and(|alpha| score <= alpha),
525        }
526    }
527
528    /// The null window at the edge `side` has to beat: just above alpha for [`Side::Max`],
529    /// just below beta for [`Side::Min`]; `None` if that edge is open or at the end of the
530    /// score range.
531    fn null(&self, side: Side) -> Option<Self>
532    where
533        S: Score,
534    {
535        let (alpha, beta) = match side {
536            Side::Max => {
537                let alpha = self.alpha?;
538                (alpha, alpha.next_up())
539            }
540            Side::Min => {
541                let beta = self.beta?;
542                (beta.next_down(), beta)
543            }
544        };
545
546        (alpha < beta).then_some(Self {
547            alpha: Some(alpha),
548            beta: Some(beta),
549        })
550    }
551
552    /// Whether a scout result `node` needs a search with this full window: it is not exact,
553    /// and its score lies strictly inside the window, so the true value may too.
554    fn needs_research(&self, node: &Node<S>) -> bool {
555        let above = self.alpha.is_none_or(|alpha| node.score > alpha);
556        let below = self.beta.is_none_or(|beta| node.score < beta);
557
558        node.bound != Bound::Exact && above && below
559    }
560
561    /// Narrows the window once `side` has found a move worth `score`.
562    fn tighten(&mut self, side: Side, score: S) {
563        match side {
564            Side::Max => self.alpha = Some(self.alpha.map_or(score, |alpha| alpha.max(score))),
565            Side::Min => self.beta = Some(self.beta.map_or(score, |beta| beta.min(score))),
566        }
567    }
568}
569
570/// What a search learned about one position; its principal variation sits in the
571/// searcher's line buffer for its ply.
572#[derive(Debug, Clone, Copy)]
573pub(crate) struct Node<S> {
574    /// The score, from [`Side::Max`]'s point of view.
575    pub(crate) score: S,
576    /// How [`Node::score`] relates to the position's minimax value.
577    pub(crate) bound: Bound,
578    /// The moves of the position left unsearched.
579    skipped: usize,
580    /// Whether no line below the position ran into the depth limit.
581    proven: bool,
582    /// The fewest plies left at which a search of the position runs into no depth limit.
583    reach: u32,
584}
585
586impl<S> Node<S> {
587    /// A position where the game ends, scored by [`Game::evaluate`].
588    const fn leaf(score: S) -> Self {
589        Self {
590            score,
591            bound: Bound::Exact,
592            skipped: 0,
593            proven: true,
594            reach: 1,
595        }
596    }
597
598    /// A position where the depth runs out, scored by [`Game::evaluate`].
599    const fn horizon(score: S) -> Self {
600        Self {
601            score,
602            bound: Bound::Exact,
603            skipped: 0,
604            proven: false,
605            reach: 0,
606        }
607    }
608
609    /// A position answered by a transposition table entry.
610    fn stored<M>(entry: &Entry<M, S>) -> Self
611    where
612        S: Copy,
613    {
614        Self {
615            score: entry.score,
616            bound: entry.bound,
617            skipped: 0,
618            proven: entry.proven,
619            reach: entry.reach,
620        }
621    }
622}
623
624/// Unit tests for the searcher's hint handling.
625#[cfg(test)]
626mod tests {
627    use alloc::vec;
628    use alloc::vec::Vec;
629
630    use super::{Frame, Run, Window, answer};
631    use crate::incremental::Borrowed;
632    use crate::table::Entry;
633    use crate::{Bound, Game, Searcher, Side, Stats};
634
635    /// A game whose root offers moves `1` and `2`, each ending the game.
636    struct TwoMoves;
637
638    impl Game for TwoMoves {
639        /// `true` at the root, `false` once a move was played.
640        type Position = bool;
641        /// The move played.
642        type Move = u8;
643        /// Always `0`.
644        type Score = i32;
645
646        fn side_to_move(&self, _: &bool) -> Side {
647            Side::Max
648        }
649
650        fn moves(&self, &root: &bool, moves: &mut Vec<u8>) {
651            if root {
652                moves.extend([1, 2]);
653            }
654        }
655
656        fn play(&self, _: &bool, _: &u8) -> bool {
657            false
658        }
659
660        fn evaluate(&self, _: &bool) -> i32 {
661            0
662        }
663    }
664
665    /// Searches the root of [`TwoMoves`] to depth 2 with `hint` as the previous line.
666    fn search_with_hint(hint: Vec<u8>) -> Option<u8> {
667        let mut searcher = Searcher::<TwoMoves>::new();
668        searcher.hint = hint;
669        let mut unlimited = |_: &Stats| false;
670        let mut run = Run {
671            game: &TwoMoves,
672            budget: &mut unlimited,
673        };
674
675        let node = searcher.iterate(&mut run, &mut Borrowed(&true), 2, Window::FULL);
676        searcher.result(&node, 2).best().copied()
677    }
678
679    /// Approximate entries, entries from another depth and bounds inside the window answer
680    /// nothing; bounds beyond the window answer.
681    #[test]
682    fn unusable_entries_answer_nothing() {
683        let entry = |bound, depth| Entry::<u8, i32> {
684            depth,
685            score: 3,
686            bound,
687            best: None,
688            proven: false,
689            reach: 0,
690        };
691        let frame = Frame {
692            ply: 1,
693            depth: 2,
694            window: Window {
695                alpha: Some(0),
696                beta: Some(5),
697            },
698            on_hint: false,
699        };
700
701        assert!(answer(&entry(Bound::Approximate, 2), frame).is_none());
702        assert!(answer(&entry(Bound::Exact, 3), frame).is_none());
703        assert!(answer(&entry(Bound::Lower, 2), frame).is_none());
704        assert!(answer(&entry(Bound::Upper, 2), frame).is_none());
705        let beyond = Frame {
706            window: Window {
707                alpha: Some(3),
708                beta: Some(3),
709            },
710            ..frame
711        };
712        assert!(answer(&entry(Bound::Lower, 2), beyond).is_some());
713        assert!(answer(&entry(Bound::Upper, 2), beyond).is_some());
714    }
715
716    /// Principal variation search scouts a later child with a null window, and re-searches
717    /// it when the scout beats the edge, but searches the first child with the full window
718    /// right away.
719    #[test]
720    fn pvs_scouts_only_later_children() {
721        let mut searcher = Searcher::<TwoMoves>::new().with_algorithm(crate::Algorithm::Pvs);
722        let mut unlimited = |_: &Stats| false;
723        let mut run = Run {
724            game: &TwoMoves,
725            budget: &mut unlimited,
726        };
727        let frame = Frame {
728            ply: 1,
729            depth: 1,
730            window: Window {
731                alpha: Some(-1),
732                beta: Some(1),
733            },
734            on_hint: false,
735        };
736
737        let first = searcher.child(&mut run, &mut Borrowed(&true), frame, (Side::Max, false));
738        assert_eq!(
739            (first.score, first.bound, searcher.stats.researches),
740            (0, Bound::Exact, 0)
741        );
742
743        let later = searcher.child(&mut run, &mut Borrowed(&true), frame, (Side::Max, true));
744        assert_eq!(
745            (later.score, later.bound, searcher.stats.researches),
746            (0, Bound::Exact, 1)
747        );
748    }
749
750    /// A searcher that budgets its first iteration stops at once on a spent budget, as a
751    /// Lazy SMP helper must when the main thread is done.
752    #[test]
753    fn a_budgeted_first_iteration_stops_at_once() {
754        let mut searcher = Searcher::<TwoMoves>::new();
755        searcher.budget_first = true;
756        let result = searcher.deepen(&TwoMoves, &true, 5, |_: &Stats| true);
757        assert_eq!((result.stats.nodes, result.pv.len()), (0, 0));
758    }
759
760    /// A legal hint is searched first and wins the tie; an illegal one is ignored.
761    #[test]
762    fn only_legal_hints_are_tried_first() {
763        assert_eq!(search_with_hint(vec![2]), Some(2));
764        assert_eq!(search_with_hint(vec![9]), Some(1));
765        assert_eq!(search_with_hint(Vec::new()), Some(1));
766    }
767}