Skip to main content

native_solver/solver/
tree.rs

1//! Betting tree spanning one or more streets, heads-up. OOP (out of
2//! position) acts first on every street. Once a betting round ends without
3//! a fold, a `Chance` node deals the next community card (unless the board
4//! is already complete) before a fresh betting round starts; on the river
5//! it resolves straight to showdown. Bet/raise sizes are configured as
6//! fractions of the pot and clipped to the smaller of the two stacks (no
7//! side pots — both players start each street with equal remaining stacks,
8//! so this is exact, not an approximation). Chip amounts are exact integers
9//! ([`Chips`]), so an all-in leaves exactly zero behind at any input scale.
10
11use super::chips::Chips;
12use crate::card::{mask_has, mask_of, Card, CardSet};
13
14/// Setup for betting starting from a given (partial or complete) board.
15///
16/// Build one with [`GameConfig::new`] and the `with_*` methods. Without
17/// them the game has no bet sizes, so every street is checked down.
18///
19/// ```
20/// use native_solver::{build_tree, Card, Chips, GameConfig};
21///
22/// let board: Vec<Card> = ["Ks", "Th", "7s", "4d", "2s"]
23///     .iter()
24///     .map(|s| s.parse())
25///     .collect::<Result<_, _>>()?;
26/// let config = GameConfig::new(board, Chips::whole(100), Chips::whole(100))
27///     .with_bet_sizes([0.5, 1.0])
28///     .with_max_raises(1);
29/// assert_eq!(build_tree(&config)?.num_decision_nodes, 8);
30/// # Ok::<(), Box<dyn std::error::Error>>(())
31/// ```
32#[derive(Debug, Clone, PartialEq)]
33pub struct GameConfig {
34    pub(crate) board: Vec<Card>,
35    pub(crate) pot: Chips,
36    pub(crate) effective_stack: Chips,
37    pub(crate) bet_sizes: Vec<f64>,
38    pub(crate) max_raises: u32,
39    pub(crate) suit_isomorphism: bool,
40}
41
42impl GameConfig {
43    /// A game on `board` with `pot` in the middle and `effective_stack` behind.
44    ///
45    /// `board` is the flop, turn, or river (3, 4, or 5 cards). The game starts with
46    /// no bet sizes, no raises, and no suit-isomorphism reduction.
47    pub fn new(board: Vec<Card>, pot: Chips, effective_stack: Chips) -> GameConfig {
48        GameConfig {
49            board,
50            pot,
51            effective_stack,
52            bet_sizes: Vec::new(),
53            max_raises: 0,
54            suit_isomorphism: false,
55        }
56    }
57
58    /// Sets the bet and raise sizes, as fractions of the pot, for every street.
59    ///
60    /// Each amount is rounded half-to-even to a whole [`Chips`] unit, clipped to
61    /// the available stack, and deduplicated. No all-in size is added: include a
62    /// large enough fraction for one.
63    pub fn with_bet_sizes(mut self, bet_sizes: impl Into<Vec<f64>>) -> GameConfig {
64        self.bet_sizes = bet_sizes.into();
65        self
66    }
67
68    /// Sets the maximum number of raises per street (the count resets each
69    /// street).
70    pub fn with_max_raises(mut self, max_raises: u32) -> GameConfig {
71        self.max_raises = max_raises;
72        self
73    }
74
75    /// Groups strategically identical chance cards to shrink the tree.
76    ///
77    /// Cards of the same rank whose suits are both absent from the board are
78    /// interchangeable, so the tree recurses once per such class and the trainer
79    /// derives the other members' values by relabeling suits. Results match the
80    /// unreduced tree (see [the conventions](crate::conventions)). Off by
81    /// default.
82    pub fn with_suit_isomorphism(mut self, suit_isomorphism: bool) -> GameConfig {
83        self.suit_isomorphism = suit_isomorphism;
84        self
85    }
86
87    /// The board the first street starts on.
88    pub fn board(&self) -> &[Card] {
89        &self.board
90    }
91
92    /// Chips already in the pot at the start of the first street.
93    pub fn pot(&self) -> Chips {
94        self.pot
95    }
96
97    /// Each player's remaining stack at the start of the first street.
98    pub fn effective_stack(&self) -> Chips {
99        self.effective_stack
100    }
101
102    /// Bet and raise sizes, as fractions of the pot.
103    pub fn bet_sizes(&self) -> &[f64] {
104        &self.bet_sizes
105    }
106
107    /// Maximum number of raises per street.
108    pub fn max_raises(&self) -> u32 {
109        self.max_raises
110    }
111
112    /// Whether chance nodes are grouped by suit isomorphism.
113    pub fn suit_isomorphism(&self) -> bool {
114        self.suit_isomorphism
115    }
116}
117
118/// A seat in the heads-up hand.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Player {
121    /// Out of position: acts first on every street. Index 0.
122    Oop,
123    /// In position: acts last on every street. Index 1.
124    Ip,
125}
126
127impl Player {
128    /// Both players in index order, so `Player::ALL[i].index() == i`.
129    pub const ALL: [Player; 2] = [Player::Oop, Player::Ip];
130
131    /// The opponent.
132    pub fn other(self) -> Player {
133        match self {
134            Player::Oop => Player::Ip,
135            Player::Ip => Player::Oop,
136        }
137    }
138
139    /// `0` for OOP and `1` for IP: the index into every `[_; 2]` per-player array.
140    pub fn index(self) -> usize {
141        match self {
142            Player::Oop => 0,
143            Player::Ip => 1,
144        }
145    }
146}
147
148/// A betting action at a decision node.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub enum Action {
151    /// Pass with no bet to call.
152    Check,
153    /// Open the betting with this many chips.
154    Bet(Chips),
155    /// Match the outstanding bet.
156    Call,
157    /// Give up the pot.
158    Fold,
159    /// Call and add this many chips on top (not the raise-to total).
160    Raise(Chips),
161}
162
163/// How a hand ends, with the payoffs the solver uses.
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub enum Terminal {
166    /// A player folded and `winner` takes the pot.
167    ///
168    /// `invested` is each player's total contribution to the pot at this point
169    /// (including the pre-street `pot`, split evenly as each player's
170    /// baseline), in input chips. Built trees derive these from exact
171    /// [`Chips`]; they stay `f64` because they are the payoffs the solver
172    /// kernels consume.
173    Fold {
174        /// The player who did not fold.
175        winner: Player,
176        /// `[OOP, IP]` total contribution, in input chips.
177        invested: [f64; 2],
178    },
179    /// Both players reach showdown on a complete board; the better hand wins
180    /// the opponent's `invested` and a tie splits the pot.
181    Showdown {
182        /// `[OOP, IP]` total contribution, in input chips.
183        invested: [f64; 2],
184    },
185}
186
187/// A node of the betting tree.
188#[derive(Debug, Clone, PartialEq)]
189pub enum Node {
190    /// A player chooses one of `actions`.
191    Decision {
192        /// Dense id in `0..Tree::num_decision_nodes`, assigned in depth-first
193        /// preorder.
194        /// Strategies and evaluations are keyed by it.
195        id: usize,
196        /// The player to act.
197        player: Player,
198        /// The legal actions, in a fixed order.
199        actions: Vec<Action>,
200        /// One subtree per action, in the same order as `actions`.
201        children: Vec<Node>,
202    },
203    /// Deals the next community card.
204    ///
205    /// Cards are grouped into suit-isomorphism classes (see
206    /// [`GameConfig::suit_isomorphism`]): each entry is one class's member
207    /// cards plus the subtree built from its representative (`members[0]`).
208    /// With isomorphism disabled every class is a singleton, so this is
209    /// equivalent to one child per undealt card (52 minus however many board
210    /// cards have been dealt so far along this path).
211    Chance {
212        /// `(class members, subtree)` per suit-isomorphism class.
213        children: Vec<(Vec<Card>, Node)>,
214    },
215    /// The hand is over.
216    Terminal(Terminal),
217}
218
219/// Why a board was rejected.
220#[derive(Debug, Clone, PartialEq, Eq)]
221#[non_exhaustive]
222pub enum BoardError {
223    /// The board must have 3 (flop), 4 (turn), or 5 (river) cards.
224    WrongSize {
225        /// The number of cards supplied.
226        len: usize,
227    },
228    /// The same card appears more than once.
229    DuplicateCard {
230        /// The repeated card.
231        card: Card,
232    },
233}
234
235impl std::fmt::Display for BoardError {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        match self {
238            Self::WrongSize { len } => write!(f, "board has {len} cards; expected 3, 4, or 5"),
239            Self::DuplicateCard { card } => {
240                write!(f, "board card {card} appears more than once")
241            }
242        }
243    }
244}
245
246impl std::error::Error for BoardError {}
247
248/// Checks that `board` is a legal flop, turn, or river.
249pub(crate) fn validate_board(board: &[Card]) -> Result<(), BoardError> {
250    if !(3..=5).contains(&board.len()) {
251        return Err(BoardError::WrongSize { len: board.len() });
252    }
253    let mut seen = CardSet::EMPTY;
254    for &card in board {
255        if !seen.insert(card) {
256            return Err(BoardError::DuplicateCard { card });
257        }
258    }
259    Ok(())
260}
261
262/// Why a betting tree was not built.
263#[derive(Debug, Clone, PartialEq, Eq)]
264#[non_exhaustive]
265pub enum TreeError {
266    /// [`GameConfig::board`] is not a legal flop, turn, or river.
267    Board(BoardError),
268    /// [`GameConfig::pot`] is zero or negative.
269    NonPositivePot,
270    /// [`GameConfig::effective_stack`] is negative.
271    NegativeStack,
272    /// A bet size is zero, negative, or not finite.
273    InvalidBetSize {
274        /// Position of the size in [`GameConfig::bet_sizes`].
275        index: usize,
276    },
277    /// The tree would need more decision nodes than the supplied budget.
278    TooManyDecisionNodes {
279        /// The decision-node budget that was exceeded.
280        limit: usize,
281    },
282}
283
284impl std::fmt::Display for TreeError {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        match self {
287            Self::Board(error) => write!(f, "invalid board: {error}"),
288            Self::NonPositivePot => write!(f, "pot must be positive"),
289            Self::NegativeStack => write!(f, "effective stack must not be negative"),
290            Self::InvalidBetSize { index } => write!(
291                f,
292                "bet size at index {index} must be a positive, finite pot fraction"
293            ),
294            Self::TooManyDecisionNodes { limit } => write!(
295                f,
296                "game tree exceeds {limit} decision nodes; reduce bet sizes, raises, or start on a later street"
297            ),
298        }
299    }
300}
301
302impl std::error::Error for TreeError {
303    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
304        match self {
305            Self::Board(error) => Some(error),
306            _ => None,
307        }
308    }
309}
310
311impl From<BoardError> for TreeError {
312    fn from(error: BoardError) -> Self {
313        Self::Board(error)
314    }
315}
316
317/// Rejects a configuration that does not describe a legal game.
318fn validate_config(cfg: &GameConfig) -> Result<(), TreeError> {
319    validate_board(&cfg.board)?;
320    if cfg.pot <= Chips::ZERO {
321        return Err(TreeError::NonPositivePot);
322    }
323    if cfg.effective_stack < Chips::ZERO {
324        return Err(TreeError::NegativeStack);
325    }
326    if let Some(index) = cfg
327        .bet_sizes
328        .iter()
329        .position(|&size| !size.is_finite() || size <= 0.0)
330    {
331        return Err(TreeError::InvalidBetSize { index });
332    }
333    Ok(())
334}
335
336/// A betting tree and the board it starts from.
337#[derive(Debug, Clone, PartialEq)]
338pub struct Tree {
339    /// The board the first street starts on: 3, 4, or 5 cards.
340    pub board: Vec<Card>,
341    /// The first node: OOP's first decision, unless no stack is left to bet.
342    pub root: Node,
343    /// The number of decision nodes; their ids are `0..num_decision_nodes`.
344    pub num_decision_nodes: usize,
345}
346
347/// Builds the full betting tree for `cfg`.
348///
349/// The tree can grow very large; use [`build_tree_bounded`] for untrusted
350/// input.
351///
352/// # Examples
353///
354/// ```
355/// use native_solver::{build_tree, Card, Chips, GameConfig, Node};
356///
357/// let board = ["Ks", "Th", "7s", "4d"]
358///     .iter()
359///     .map(|card| card.parse())
360///     .collect::<Result<Vec<Card>, _>>()?;
361/// let config = GameConfig::new(board, Chips::whole(100), Chips::whole(200)).with_bet_sizes([0.5]);
362/// let tree = build_tree(&config)?;
363///
364/// // OOP acts first, and decision ids run from 0.
365/// assert!(matches!(tree.root, Node::Decision { id: 0, .. }));
366/// assert!(tree.num_decision_nodes > 0);
367/// # Ok::<(), Box<dyn std::error::Error>>(())
368/// ```
369///
370/// # Errors
371/// Returns an error if the board is not a legal flop, turn, or river, the
372/// pot is not positive, the stack is negative, or a bet size is not a
373/// positive finite number.
374pub fn build_tree(cfg: &GameConfig) -> Result<Tree, TreeError> {
375    build_tree_bounded(cfg, usize::MAX)
376}
377
378/// Builds the betting tree, stopping once it would exceed `max_decision_nodes`.
379///
380/// Callers must also bound input size and recursion depth (notably
381/// `max_raises`). Successful trees have the same node ids and actions as
382/// [`build_tree`].
383///
384/// # Errors
385/// Returns the same configuration errors as [`build_tree`], or
386/// [`TreeError::TooManyDecisionNodes`] when the budget is exceeded.
387pub fn build_tree_bounded(cfg: &GameConfig, max_decision_nodes: usize) -> Result<Tree, TreeError> {
388    validate_config(cfg)?;
389    let mut budget = BuildBudget {
390        next_id: 0,
391        max_decision_nodes,
392    };
393    let stack = [cfg.effective_stack, cfg.effective_stack];
394    let root = build(
395        cfg,
396        &cfg.board,
397        Player::Oop,
398        [Chips::ZERO; 2],
399        stack,
400        None,
401        false,
402        0,
403        &mut budget,
404    )?;
405    Ok(Tree {
406        board: cfg.board.clone(),
407        root,
408        num_decision_nodes: budget.next_id,
409    })
410}
411
412struct BuildBudget {
413    next_id: usize,
414    max_decision_nodes: usize,
415}
416
417impl BuildBudget {
418    fn allocate_id(&mut self) -> Result<usize, TreeError> {
419        if self.next_id >= self.max_decision_nodes {
420            return Err(TreeError::TooManyDecisionNodes {
421                limit: self.max_decision_nodes,
422            });
423        }
424        let id = self.next_id;
425        self.next_id += 1;
426        Ok(id)
427    }
428}
429
430/// Suits that appear nowhere in `board` — any permutation among them maps
431/// the board to itself, so cards of the same rank in different free suits
432/// are strategically interchangeable at this point in the tree.
433fn free_suits(board: &[Card]) -> [bool; 4] {
434    let mut used = [false; 4];
435    for &c in board {
436        used[c.suit() as usize] = true;
437    }
438    [!used[0], !used[1], !used[2], !used[3]]
439}
440
441/// Groups the undealt cards into suit-isomorphism classes: cards of the
442/// same rank whose suits are both free are one class (any one of them can
443/// be trained and the rest derived by relabeling — see `cfr.rs`); a card
444/// in a suit already pinned by the board is always its own singleton
445/// class. With `suit_isomorphism` off, every class is a singleton
446/// (equivalent to one child per undealt card).
447/// Not tied to [`GameConfig`] (only needs the flag, not the rest of the
448/// setup) so `cfr.rs` can also call it directly for its own internal
449/// purposes — see `cfr::avg_score`, which always groups this way
450/// regardless of whether the *tree* was built with isomorphism, since
451/// grouping same-rank free-suit cards is always a valid equivalence.
452pub(crate) fn deal_classes(suit_isomorphism: bool, board: &[Card]) -> Vec<Vec<Card>> {
453    let used = mask_of(board);
454    let free = if suit_isomorphism {
455        free_suits(board)
456    } else {
457        [false; 4]
458    };
459
460    let mut classes: Vec<Vec<Card>> = Vec::new();
461    let mut free_rank_class: [Option<usize>; 13] = [None; 13];
462    for c in Card::all() {
463        if mask_has(used, c) {
464            continue;
465        }
466        if free[c.suit() as usize] {
467            let r = c.rank() as usize;
468            match free_rank_class[r] {
469                Some(idx) => classes[idx].push(c),
470                None => {
471                    free_rank_class[r] = Some(classes.len());
472                    classes.push(vec![c]);
473                }
474            }
475        } else {
476            classes.push(vec![c]);
477        }
478    }
479    classes
480}
481
482/// Ends the current betting round: showdown if the board is already
483/// complete (5 cards), otherwise a `Chance` node dealing the next card
484/// into a fresh betting round (OOP acts first again, raise count resets).
485fn end_of_street(
486    cfg: &GameConfig,
487    board: &[Card],
488    added: [Chips; 2],
489    stack: [Chips; 2],
490    budget: &mut BuildBudget,
491) -> Result<Node, TreeError> {
492    if board.len() >= 5 {
493        return Ok(Node::Terminal(Terminal::Showdown {
494            invested: invested(cfg, added),
495        }));
496    }
497    let mut children = Vec::new();
498    for members in deal_classes(cfg.suit_isomorphism, board) {
499        let rep = members[0];
500        let mut next_board = board.to_vec();
501        next_board.push(rep);
502        let child = build(
503            cfg,
504            &next_board,
505            Player::Oop,
506            added,
507            stack,
508            None,
509            false,
510            0,
511            budget,
512        )?;
513        children.push((members, child));
514    }
515    Ok(Node::Chance { children })
516}
517
518/// Terminal payoffs: half the starting pot each plus everything added since.
519/// The half may be a half-unit, so it is applied only after leaving [`Chips`].
520fn invested(cfg: &GameConfig, added: [Chips; 2]) -> [f64; 2] {
521    let baseline = cfg.pot.to_f64() / 2.0;
522    [baseline + added[0].to_f64(), baseline + added[1].to_f64()]
523}
524
525/// `added` is each player's contribution beyond their half of `cfg.pot`.
526#[allow(clippy::too_many_arguments)]
527fn build(
528    cfg: &GameConfig,
529    board: &[Card],
530    player: Player,
531    added: [Chips; 2],
532    stack: [Chips; 2],
533    facing: Option<Chips>,
534    prev_checked: bool,
535    raises_so_far: u32,
536    budget: &mut BuildBudget,
537) -> Result<Node, TreeError> {
538    // Once an all-in is called, neither player has a betting decision left.
539    // Keep every remaining public-card chance (and its terminal contribution),
540    // but do not allocate two single-action check nodes on each later street.
541    // In particular this must precede allocate_id: forced checks must not use
542    // the admission budget or leave holes in the trainer's decision IDs.
543    if facing.is_none() && stack == [Chips::ZERO; 2] {
544        return end_of_street(cfg, board, added, stack, budget);
545    }
546    let id = budget.allocate_id()?;
547
548    let mut actions = Vec::new();
549    let mut children = Vec::new();
550
551    if let Some(to_call) = facing {
552        actions.push(Action::Fold);
553        children.push(Node::Terminal(Terminal::Fold {
554            winner: player.other(),
555            invested: invested(cfg, added),
556        }));
557
558        let mut call_added = added;
559        call_added[player.index()] += to_call;
560        let mut call_stack = stack;
561        call_stack[player.index()] -= to_call;
562        actions.push(Action::Call);
563        children.push(end_of_street(cfg, board, call_added, call_stack, budget)?);
564
565        if raises_so_far < cfg.max_raises && stack[player.index()] > to_call {
566            let opponent = player.other();
567            let pot_after_call = cfg.pot + added[0] + added[1] + to_call;
568            let own_room = stack[player.index()] - to_call;
569            let opponent_room = stack[opponent.index()];
570            let raise_extras =
571                sized_amounts(&cfg.bet_sizes, pot_after_call, own_room.min(opponent_room));
572
573            for extra in raise_extras {
574                let mut new_added = added;
575                new_added[player.index()] += to_call + extra;
576                let mut new_stack = stack;
577                new_stack[player.index()] -= to_call + extra;
578                actions.push(Action::Raise(extra));
579                children.push(build(
580                    cfg,
581                    board,
582                    opponent,
583                    new_added,
584                    new_stack,
585                    Some(extra),
586                    false,
587                    raises_so_far + 1,
588                    budget,
589                )?);
590            }
591        }
592    } else {
593        let check_child = if prev_checked {
594            end_of_street(cfg, board, added, stack, budget)?
595        } else {
596            build(
597                cfg,
598                board,
599                player.other(),
600                added,
601                stack,
602                None,
603                true,
604                raises_so_far,
605                budget,
606            )?
607        };
608        actions.push(Action::Check);
609        children.push(check_child);
610
611        if stack[player.index()] > Chips::ZERO {
612            let opponent = player.other();
613            let pot_now = cfg.pot + added[0] + added[1];
614            let room = stack[player.index()].min(stack[opponent.index()]);
615            let bet_amounts = sized_amounts(&cfg.bet_sizes, pot_now, room);
616
617            for amt in bet_amounts {
618                let mut new_added = added;
619                new_added[player.index()] += amt;
620                let mut new_stack = stack;
621                new_stack[player.index()] -= amt;
622                actions.push(Action::Bet(amt));
623                children.push(build(
624                    cfg,
625                    board,
626                    opponent,
627                    new_added,
628                    new_stack,
629                    Some(amt),
630                    false,
631                    raises_so_far,
632                    budget,
633                )?);
634            }
635        }
636    }
637
638    Ok(Node::Decision {
639        id,
640        player,
641        actions,
642        children,
643    })
644}
645
646/// Pot-fraction amounts clipped to `room`, ascending, without duplicates or
647/// non-positive amounts.
648fn sized_amounts(fractions: &[f64], pot: Chips, room: Chips) -> Vec<Chips> {
649    let mut amounts: Vec<Chips> = fractions
650        .iter()
651        .map(|&frac| pot.fraction(frac).min(room))
652        .filter(|&amt| amt > Chips::ZERO)
653        .collect();
654    amounts.sort_unstable();
655    amounts.dedup();
656    amounts
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use crate::card::Card;
663
664    fn river_board() -> Vec<Card> {
665        ["2h", "7c", "9d", "Jc", "4s"]
666            .iter()
667            .map(|s| s.parse::<Card>().unwrap())
668            .collect()
669    }
670
671    fn turn_board() -> Vec<Card> {
672        ["2h", "7c", "9d", "Jc"]
673            .iter()
674            .map(|s| s.parse::<Card>().unwrap())
675            .collect()
676    }
677
678    /// Public history as `(player, actions)` per decision plus terminal
679    /// investments, with amounts divided by `scale` (which must divide them).
680    fn shape(node: &Node, scale: i64, out: &mut Vec<String>) {
681        let unscale = |amount: Chips| {
682            assert_eq!(
683                amount.0 % scale,
684                0,
685                "{amount:?} is not a multiple of {scale}"
686            );
687            Chips(amount.0 / scale)
688        };
689        match node {
690            Node::Decision {
691                player,
692                actions,
693                children,
694                ..
695            } => {
696                let actions: Vec<Action> = actions
697                    .iter()
698                    .map(|action| match *action {
699                        Action::Bet(amount) => Action::Bet(unscale(amount)),
700                        Action::Raise(amount) => Action::Raise(unscale(amount)),
701                        other => other,
702                    })
703                    .collect();
704                out.push(format!("{player:?} {actions:?}"));
705                children.iter().for_each(|child| shape(child, scale, out));
706            }
707            Node::Chance { children } => children
708                .iter()
709                .for_each(|(_, child)| shape(child, scale, out)),
710            Node::Terminal(Terminal::Fold { invested, .. } | Terminal::Showdown { invested }) => {
711                out.push(format!("{:?}", invested.map(|chips| chips / scale as f64)));
712            }
713        }
714    }
715
716    /// Replays every path's stacks; asserts amounts are positive, stacks never
717    /// go negative, and nobody acts again once an all-in has been called.
718    fn check_stacks(node: &Node, stack: [Chips; 2], facing: Option<Chips>, all_in: bool) {
719        match node {
720            Node::Decision {
721                player,
722                actions,
723                children,
724                ..
725            } => {
726                assert!(!all_in, "decision after a called all-in");
727                let p = player.index();
728                for (action, child) in actions.iter().zip(children) {
729                    let mut next = stack;
730                    let (paid, next_facing) = match *action {
731                        Action::Check | Action::Fold => (Chips::ZERO, None),
732                        Action::Call => (facing.unwrap(), None),
733                        Action::Bet(amount) => (amount, Some(amount)),
734                        Action::Raise(extra) => (facing.unwrap() + extra, Some(extra)),
735                    };
736                    if let Action::Bet(amount) | Action::Raise(amount) = *action {
737                        assert!(amount > Chips::ZERO);
738                    }
739                    next[p] -= paid;
740                    assert!(next[p] >= Chips::ZERO, "stack went negative");
741                    let called_all_in = matches!(action, Action::Call) && next == [Chips::ZERO; 2];
742                    check_stacks(child, next, next_facing, called_all_in);
743                }
744            }
745            Node::Chance { children } => children
746                .iter()
747                .for_each(|(_, child)| check_stacks(child, stack, None, all_in)),
748            Node::Terminal(_) => {}
749        }
750    }
751
752    fn config(
753        board: Vec<Card>,
754        pot: Chips,
755        stack: Chips,
756        bet_sizes: Vec<f64>,
757        max_raises: u32,
758    ) -> GameConfig {
759        GameConfig {
760            board,
761            pot,
762            effective_stack: stack,
763            bet_sizes,
764            max_raises,
765            suit_isomorphism: true,
766        }
767    }
768
769    fn scaled(cfg: &GameConfig, scale: i64) -> GameConfig {
770        GameConfig {
771            pot: Chips(cfg.pot.0 * scale),
772            effective_stack: Chips(cfg.effective_stack.0 * scale),
773            ..cfg.clone()
774        }
775    }
776
777    #[test]
778    fn all_in_leaves_no_residual_stack_at_any_scale() {
779        // With f64 chips, pot 5.5 / stack 9 left an 8.88e-16 stack after an
780        // all-in and built `Raise(8.88e-16)`; scaling by 10 hid it.
781        for (pot, stack) in [(5500, 9000), (1500, 3900)] {
782            for board in [river_board(), turn_board()] {
783                let cfg = config(board, Chips(pot), Chips(stack), vec![0.33, 0.75, 1.5], 3);
784                let base = build_tree(&cfg).unwrap().num_decision_nodes;
785                for scale in [1, 10, 100] {
786                    let tree = build_tree(&scaled(&cfg, scale)).unwrap();
787                    assert_eq!(
788                        tree.num_decision_nodes, base,
789                        "pot {pot} stack {stack} x{scale}"
790                    );
791                    check_stacks(
792                        &tree.root,
793                        [cfg.effective_stack; 2].map(|s| Chips(s.0 * scale)),
794                        None,
795                        false,
796                    );
797                }
798            }
799        }
800        let river = config(
801            river_board(),
802            Chips(5500),
803            Chips(9000),
804            vec![0.33, 0.75, 1.5],
805            3,
806        );
807        assert_eq!(build_tree(&river).unwrap().num_decision_nodes, 26);
808    }
809
810    #[test]
811    fn tree_shape_is_scale_invariant_when_sizes_need_no_rounding() {
812        // Whole-chip pots and stacks with half-pot multiples stay integral in
813        // 0.001 units for three halvings (bet + two raises on one street), so
814        // every scaled tree must be the base tree with amounts multiplied.
815        let mut seed = 0x2545_f491_4f6c_dd1du64;
816        let mut next = |bound: u64| {
817            seed ^= seed << 13;
818            seed ^= seed >> 7;
819            seed ^= seed << 17;
820            seed % bound
821        };
822        for _ in 0..200 {
823            let pot = Chips::whole(1 + next(40) as i64);
824            let stack = Chips::whole(1 + next(120) as i64);
825            let sizes: Vec<f64> = (0..1 + next(3))
826                .map(|_| [0.5, 1.0, 1.5, 2.0][next(4) as usize])
827                .collect();
828            let cfg = config(river_board(), pot, stack, sizes, next(3) as u32);
829            let mut base = Vec::new();
830            shape(&build_tree(&cfg).unwrap().root, 1, &mut base);
831            for scale in [10, 100] {
832                let mut other = Vec::new();
833                shape(
834                    &build_tree(&scaled(&cfg, scale)).unwrap().root,
835                    scale,
836                    &mut other,
837                );
838                assert_eq!(base, other, "{cfg:?} x{scale}");
839            }
840        }
841    }
842
843    #[test]
844    fn arbitrary_thousandth_amounts_keep_stacks_exact() {
845        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
846        let mut next = |bound: u64| {
847            seed ^= seed << 13;
848            seed ^= seed >> 7;
849            seed ^= seed << 17;
850            seed % bound
851        };
852        for _ in 0..300 {
853            let pot = Chips(1 + next(20_000) as i64);
854            let stack = Chips(1 + next(60_000) as i64);
855            let sizes: Vec<f64> = (0..1 + next(4))
856                .map(|_| (1 + next(300)) as f64 / 100.0)
857                .collect();
858            let cfg = config(river_board(), pot, stack, sizes, next(4) as u32);
859            check_stacks(&build_tree(&cfg).unwrap().root, [stack; 2], None, false);
860        }
861    }
862
863    #[test]
864    fn bounded_tree_preserves_ids_actions_and_exact_boundary() {
865        let cfg = GameConfig {
866            board: turn_board(),
867            pot: Chips::whole(100),
868            effective_stack: Chips::whole(200),
869            bet_sizes: vec![0.5, 1.0],
870            max_raises: 1,
871            suit_isomorphism: true,
872        };
873        let original = build_tree(&cfg).unwrap();
874        let bounded = build_tree_bounded(&cfg, original.num_decision_nodes).unwrap();
875        assert_eq!(
876            format!("{:?}", original.root),
877            format!("{:?}", bounded.root)
878        );
879        assert_eq!(original.num_decision_nodes, bounded.num_decision_nodes);
880        assert!(build_tree_bounded(&cfg, original.num_decision_nodes - 1).is_err());
881        assert!(build_tree_bounded(&cfg, 0).is_err());
882    }
883
884    #[test]
885    fn bounded_tree_aborts_large_flop_construction() {
886        let cfg = GameConfig {
887            board: turn_board()[..3].to_vec(),
888            pot: Chips::whole(100),
889            effective_stack: Chips::whole(100000),
890            bet_sizes: vec![0.25, 0.5, 1.0, 2.0],
891            max_raises: 4,
892            suit_isomorphism: false,
893        };
894        let error = build_tree_bounded(&cfg, 100).expect_err("must exceed construction budget");
895        assert_eq!(error, TreeError::TooManyDecisionNodes { limit: 100 });
896        assert!(error.to_string().contains("100 decision nodes"));
897    }
898
899    #[test]
900    fn check_check_ends_in_showdown_on_the_river() {
901        let cfg = GameConfig {
902            board: river_board(),
903            pot: Chips::whole(100),
904            effective_stack: Chips::whole(200),
905            bet_sizes: vec![1.0],
906            max_raises: 0,
907            suit_isomorphism: false,
908        };
909        let tree = build_tree(&cfg).unwrap();
910        let Node::Decision {
911            actions, children, ..
912        } = &tree.root
913        else {
914            panic!("expected decision")
915        };
916        assert_eq!(actions.len(), 2);
917        let Node::Decision {
918            player: ip_player,
919            actions: ip_actions,
920            children: ip_children,
921            ..
922        } = &children[0]
923        else {
924            panic!("expected IP decision after check")
925        };
926        assert_eq!(*ip_player, Player::Ip);
927        assert_eq!(ip_actions.len(), 2);
928        assert!(matches!(
929            ip_children[0],
930            Node::Terminal(Terminal::Showdown { .. })
931        ));
932    }
933
934    #[test]
935    fn bet_size_is_pot_fraction_and_call_ends_in_showdown_on_the_river() {
936        let cfg = GameConfig {
937            board: river_board(),
938            pot: Chips::whole(100),
939            effective_stack: Chips::whole(200),
940            bet_sizes: vec![1.0],
941            max_raises: 0,
942            suit_isomorphism: false,
943        };
944        let tree = build_tree(&cfg).unwrap();
945        let Node::Decision {
946            actions, children, ..
947        } = &tree.root
948        else {
949            panic!("expected decision")
950        };
951        let Action::Bet(amount) = actions[1] else {
952            panic!("expected a bet action")
953        };
954        assert_eq!(amount, Chips::whole(100));
955
956        let Node::Decision {
957            actions: ip_actions,
958            children: ip_children,
959            ..
960        } = &children[1]
961        else {
962            panic!("expected IP decision facing the bet")
963        };
964        assert_eq!(ip_actions.len(), 2);
965        assert!(matches!(
966            ip_children[0],
967            Node::Terminal(Terminal::Fold { .. })
968        ));
969        assert!(matches!(
970            ip_children[1],
971            Node::Terminal(Terminal::Showdown { .. })
972        ));
973    }
974
975    #[test]
976    fn raises_are_capped_by_max_raises_per_street() {
977        let cfg = GameConfig {
978            board: river_board(),
979            pot: Chips::whole(100),
980            effective_stack: Chips::whole(1000),
981            bet_sizes: vec![1.0],
982            max_raises: 1,
983            suit_isomorphism: false,
984        };
985        let tree = build_tree(&cfg).unwrap();
986        let Node::Decision { children, .. } = &tree.root else {
987            panic!("expected decision")
988        };
989        let Node::Decision {
990            actions,
991            children: ip_children,
992            ..
993        } = &children[1]
994        else {
995            panic!("expected IP decision facing the bet")
996        };
997        assert_eq!(actions.len(), 3);
998        let Node::Decision {
999            actions: oop_actions,
1000            ..
1001        } = &ip_children[2]
1002        else {
1003            panic!("expected OOP decision facing the raise")
1004        };
1005        assert_eq!(oop_actions.len(), 2);
1006    }
1007
1008    #[test]
1009    fn check_check_on_the_turn_deals_a_chance_node_with_48_river_cards() {
1010        let cfg = GameConfig {
1011            board: turn_board(),
1012            pot: Chips::whole(100),
1013            effective_stack: Chips::whole(200),
1014            bet_sizes: vec![1.0],
1015            max_raises: 0,
1016            suit_isomorphism: false,
1017        };
1018        let tree = build_tree(&cfg).unwrap();
1019        let Node::Decision { children, .. } = &tree.root else {
1020            panic!("expected decision")
1021        };
1022        let Node::Decision {
1023            children: ip_children,
1024            ..
1025        } = &children[0]
1026        else {
1027            panic!("expected IP decision after check")
1028        };
1029        // Check-check on the turn (4-card board) should deal the river, not show down directly.
1030        let Node::Chance {
1031            children: river_deals,
1032        } = &ip_children[0]
1033        else {
1034            panic!("expected a chance node dealing the river")
1035        };
1036        // With isomorphism disabled, every class is a singleton: one per undealt card.
1037        assert_eq!(river_deals.len(), 48); // 52 - 4 board cards
1038        for (members, _) in river_deals {
1039            assert_eq!(members.len(), 1);
1040        }
1041
1042        // Every river deal leads into a fresh betting round (OOP decision), not straight to showdown.
1043        for (_, node) in river_deals {
1044            assert!(matches!(
1045                node,
1046                Node::Decision {
1047                    player: Player::Oop,
1048                    ..
1049                }
1050            ));
1051        }
1052    }
1053
1054    #[test]
1055    fn river_deals_never_repeat_an_existing_board_card() {
1056        let cfg = GameConfig {
1057            board: turn_board(),
1058            pot: Chips::whole(100),
1059            effective_stack: Chips::whole(200),
1060            bet_sizes: vec![1.0],
1061            max_raises: 0,
1062            suit_isomorphism: false,
1063        };
1064        let tree = build_tree(&cfg).unwrap();
1065        let Node::Decision { children, .. } = &tree.root else {
1066            panic!("expected decision")
1067        };
1068        let Node::Decision {
1069            children: ip_children,
1070            ..
1071        } = &children[0]
1072        else {
1073            panic!("expected IP decision after check")
1074        };
1075        let Node::Chance {
1076            children: river_deals,
1077        } = &ip_children[0]
1078        else {
1079            panic!("expected a chance node dealing the river")
1080        };
1081        let board_set = mask_of(&turn_board());
1082        for (members, _) in river_deals {
1083            for &card in members {
1084                assert!(!mask_has(board_set, card));
1085            }
1086        }
1087    }
1088
1089    #[test]
1090    fn suit_isomorphism_groups_free_suit_cards_of_the_same_rank() {
1091        // Board uses only clubs and diamonds -> hearts and spades are free.
1092        let board: Vec<Card> = ["2c", "7d", "9c"]
1093            .iter()
1094            .map(|s| s.parse::<Card>().unwrap())
1095            .collect();
1096        let cfg = GameConfig {
1097            board: board.clone(),
1098            pot: Chips::whole(100),
1099            effective_stack: Chips::whole(200),
1100            bet_sizes: vec![1.0],
1101            max_raises: 0,
1102            suit_isomorphism: true,
1103        };
1104        let tree = build_tree(&cfg).unwrap();
1105        let Node::Decision { children, .. } = &tree.root else {
1106            panic!("expected decision")
1107        };
1108        let Node::Decision {
1109            children: ip_children,
1110            ..
1111        } = &children[0]
1112        else {
1113            panic!("expected IP decision after check")
1114        };
1115        let Node::Chance { children: deals } = &ip_children[0] else {
1116            panic!("expected a chance node dealing the turn")
1117        };
1118
1119        // 49 undealt cards; hearts and spades are free. Rather than
1120        // hand-derive the exact class breakdown, check the structural
1121        // invariants directly: every class shares one rank, only free-suit
1122        // (h/s) cards are ever grouped into a class of size > 1, and every
1123        // undealt card appears in exactly one class.
1124        let used = mask_of(&board);
1125        let mut seen = std::collections::HashSet::new();
1126        let mut total_members = 0;
1127        for (members, _) in deals {
1128            assert!(!members.is_empty());
1129            let ranks: std::collections::HashSet<u8> = members.iter().map(|&c| c.rank()).collect();
1130            assert_eq!(
1131                ranks.len(),
1132                1,
1133                "every class member must share the same rank"
1134            );
1135            if members.len() > 1 {
1136                for &c in members {
1137                    let s = c.suit();
1138                    assert!(
1139                        s == 2 || s == 3,
1140                        "grouped members must use a free suit (h=2, s=3)"
1141                    );
1142                }
1143            }
1144            for &c in members {
1145                assert!(
1146                    !mask_has(used, c),
1147                    "class must not include an already-used card"
1148                );
1149                assert!(
1150                    seen.insert(c),
1151                    "each undealt card must appear in exactly one class"
1152                );
1153            }
1154            total_members += members.len();
1155        }
1156        assert_eq!(total_members, 52 - board.len());
1157        // At least one class should actually group 2 free-suit cards together
1158        // (that's the whole point of isomorphism reduction).
1159        assert!(deals.iter().any(|(members, _)| members.len() == 2));
1160        // No class can exceed the number of free suits (2 here).
1161        assert!(deals.iter().all(|(members, _)| members.len() <= 2));
1162    }
1163}