rs_poker 5.0.0

A library to help with any Rust code dealing with poker. This includes card values, suits, hands, hand ranks, 5 card hand strength calculation, 7 card hand strength calulcation, and monte carlo game simulation helpers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};

use crate::core::{CardBitSet, Deck};

use super::{
    Agent, GameState, HoldemSimulation,
    agent::FoldingAgent,
    cfr::{CFRHistorian, CFRState, TraversalSet},
    errors::HoldemSimulationError,
    historian::Historian,
};

// Some builder methods to help with turning a builder struct into a ready
// simulation
fn build_deck(game_state: &GameState) -> Deck {
    let mut d = CardBitSet::default();

    for hand in game_state.hands.iter() {
        let bitset: CardBitSet = (*hand).into();

        d &= !bitset; // remove the cards in the hand from the deck
    }
    for card in game_state.board.iter() {
        d.remove(*card); // remove the cards on the board from the deck
    }

    d.into() // convert the bitset into a deck
}

fn build_agents(num_agents: usize) -> Vec<Box<dyn Agent>> {
    (0..num_agents)
        .map(|_| -> Box<dyn Agent> { Box::<FoldingAgent>::default() })
        .collect()
}

/// # HoldemSimulationBuilder
///
/// `RngHoldemSimulationBuilder` is a builder to allow for complex
/// configurations of a holdem simulation played via agents. A game state is
/// required, other fields are optional.
///
/// `HolemSimulationBuilder` is a type alias
/// for `RngHoldemSimulationBuilder<ThreadRng>` which is the default builder.
///
/// ## Setters
///
/// Each setter will set the optional value to the passed in value. Then return
/// the mutated builder.
///
/// While agents are not required the default is a full ring of folding agents.
/// So likely not that interesting a simulation.
///
/// ## Examples
///
/// ```
/// use rs_poker::arena::{GameStateBuilder, HoldemSimulationBuilder};
///
/// let game_state = GameStateBuilder::new()
///     .num_players_with_stack(5, 100.0)
///     .blinds(2.0, 1.0)
///     .dealer_idx(3)
///     .build()
///     .unwrap();
/// let sim = HoldemSimulationBuilder::default()
///     .game_state(game_state)
///     .build()
///     .unwrap();
/// ```
/// However sometimes you want to use a known but random simulation. In that
/// case you can pass in the rng like this:
///
/// ```
/// use rand::{SeedableRng, rngs::StdRng};
/// use rs_poker::arena::{GameStateBuilder, HoldemSimulationBuilder};
///
/// let game_state = GameStateBuilder::new()
///     .num_players_with_stack(5, 100.0)
///     .blinds(2.0, 1.0)
///     .dealer_idx(3)
///     .build()
///     .unwrap();
/// let sim = HoldemSimulationBuilder::default()
///     .game_state(game_state)
///     .build()
///     .unwrap();
/// ```
pub struct HoldemSimulationBuilder {
    agents: Option<Vec<Box<dyn Agent>>>,
    historians: Vec<Box<dyn Historian>>,
    game_state: Option<GameState>,
    deck: Option<Deck>,
    panic_on_historian_error: bool,
    /// Optional CFR context for automatic historian creation.
    cfr_state: Option<CFRState>,
    cfr_traversal_set: Option<TraversalSet>,
    cfr_allow_node_mutation: bool,
}

/// # Examples
/// ```
/// use rand::{SeedableRng, rngs::StdRng};
/// use rs_poker::arena::{Agent, agent::FoldingAgent};
/// use rs_poker::arena::{GameStateBuilder, HoldemSimulationBuilder};
///
/// let game_state = GameStateBuilder::new()
///     .num_players_with_stack(5, 100.0)
///     .blinds(2.0, 1.0)
///     .dealer_idx(3)
///     .build()
///     .unwrap();
/// let agents: Vec<Box<dyn Agent>> = (0..5)
///     .map(|_| Box::<FoldingAgent>::default() as Box<dyn Agent>)
///     .collect();
/// let sim = HoldemSimulationBuilder::default()
///     .game_state(game_state)
///     .agents(agents)
///     .build();
/// ```
impl HoldemSimulationBuilder {
    /// Set the agents for the simulation created by this builder.
    pub fn agents(mut self, agents: Vec<Box<dyn Agent>>) -> Self {
        self.agents = Some(agents);
        self
    }

    /// Set the game state for ths simulation created by this bu
    pub fn game_state(mut self, game_state: GameState) -> Self {
        self.game_state = Some(game_state);
        self
    }

    /// Set the deck. If not set a deck will be
    /// created from the game state and shuffled.
    pub fn deck(mut self, deck: Deck) -> Self {
        self.deck = Some(deck);
        self
    }

    /// Set the historians for the simulation created by this builder.
    pub fn historians(mut self, historians: Vec<Box<dyn Historian>>) -> Self {
        self.historians = historians;
        self
    }

    /// Should the simulation panic if a historian errors.
    /// Default is false and allows the simulation to continue if a historian
    /// errors. It will be removed from the simulation and recorded in the logs.
    pub fn panic_on_historian_error(mut self, panic_on_historian_error: bool) -> Self {
        self.panic_on_historian_error = panic_on_historian_error;
        self
    }

    /// Provide CFR context for this simulation.
    ///
    /// When set, the builder will automatically create a `CFRHistorian` and
    /// add it to the simulation's historians. All players share a single
    /// CFR tree (CFRState). CFRState is cheap to clone (just Arc bumps).
    ///
    /// # Arguments
    /// * `cfr_state` - The single shared CFR state for all players
    /// * `traversal_set` - The traversal set tracking each player's position
    /// * `allow_node_mutation` - Whether to allow mutating node types on mismatch
    pub fn cfr_context(
        mut self,
        cfr_state: CFRState,
        traversal_set: TraversalSet,
        allow_node_mutation: bool,
    ) -> Self {
        self.cfr_state = Some(cfr_state);
        self.cfr_traversal_set = Some(traversal_set);
        self.cfr_allow_node_mutation = allow_node_mutation;
        self
    }

    /// Given the fields already specified build any that are not specified and
    /// create a new HoldemSimulation.
    ///
    /// Seeds a default RNG (`StdRng`) from OS entropy and stores it on the
    /// simulation. For hot paths where many simulations are created (e.g., CFR
    /// sub-simulations), prefer `build_with_rng` to supply a seeded sub-RNG.
    ///
    /// @returns HoldemSimulationError if no game_state was given.
    pub fn build(self) -> Result<HoldemSimulation, HoldemSimulationError> {
        self.build_with_rng(StdRng::from_rng(&mut rand::rng()))
    }

    /// Build the simulation, moving the provided RNG into the simulation.
    ///
    /// The simulation owns its RNG so that `run()` can be `async` without
    /// borrowing an external `&mut R` across await points. The RNG is also used
    /// for the simulation ID.
    pub fn build_with_rng<R: Rng + Send + 'static>(
        self,
        mut rng: R,
    ) -> Result<HoldemSimulation, HoldemSimulationError> {
        let game_state = self
            .game_state
            .ok_or(HoldemSimulationError::NeedGameState)?;

        let agents = self
            .agents
            .unwrap_or_else(|| build_agents(game_state.hands.len()));

        // Collect historians from explicit registration plus any provided by
        // agents. CFR agents self-provide a `HandLogHistorian` ONLY at depth 0
        // and only when their estimator needs the game log; sub-agents and the
        // default estimator return `None`, so this is a no-op for ordinary CFR
        // sims. The CFRHistorian (tree traversal) is added separately below.
        let agent_historians = agents.iter().filter_map(|a| a.historian());
        let mut historians: Vec<_> = self
            .historians
            .into_iter()
            .chain(agent_historians)
            .collect();

        // If CFR context was provided, create and add a CFRHistorian.
        if let (Some(cfr_state), Some(traversal_set)) = (self.cfr_state, self.cfr_traversal_set) {
            let cfr_historian =
                CFRHistorian::new(&cfr_state, traversal_set, self.cfr_allow_node_mutation);
            historians.push(Box::new(cfr_historian));
        }

        let deck = self.deck.unwrap_or_else(|| build_deck(&game_state));

        let id = rng.random::<u128>();

        Ok(HoldemSimulation {
            agents,
            game_state,
            deck,
            id,
            historians,
            panic_on_historian_error: self.panic_on_historian_error,
            rng: Box::new(rng),
        })
    }
}

impl Default for HoldemSimulationBuilder {
    fn default() -> Self {
        Self {
            agents: None,
            historians: vec![],
            game_state: None,
            deck: None,
            panic_on_historian_error: true,
            cfr_state: None,
            cfr_traversal_set: None,
            cfr_allow_node_mutation: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use rand::{SeedableRng, rngs::StdRng};

    use crate::{arena::action::AgentAction, arena::game_state::Round, core::Card};

    use super::*;
    use crate::arena::GameStateBuilder;

    /// Test helper to create a game state with standard defaults
    fn test_game_state(
        stacks: Vec<f32>,
        big_blind: f32,
        small_blind: f32,
        ante: f32,
        dealer_idx: usize,
    ) -> GameState {
        GameStateBuilder::new()
            .stacks(stacks)
            .big_blind(big_blind)
            .small_blind(small_blind)
            .ante(ante)
            .dealer_idx(dealer_idx)
            .build()
            .unwrap()
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_single_step_agent() {
        let stacks = vec![100.0; 9];
        let game_state = test_game_state(stacks, 10.0, 5.0, 1.0, 0);
        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .build_with_rng(StdRng::seed_from_u64(420))
            .unwrap();

        assert_eq!(100.0, sim.game_state.stacks[1]);
        assert_eq!(100.0, sim.game_state.stacks[2]);
        // We are starting out.
        sim.run_round().await;
        assert_eq!(100.0, sim.game_state.stacks[1]);
        assert_eq!(100.0, sim.game_state.stacks[2]);

        // Post the ante and check the results.
        sim.run_round().await;
        for i in 0..9 {
            assert_eq!(99.0, sim.game_state.stacks[i]);
        }

        // Deal Pre-Flop
        sim.run_round().await;

        // Post the blinds and check the results.
        sim.run_round().await;
        assert_eq!(6.0, sim.game_state.player_bet[1]);
        assert_eq!(11.0, sim.game_state.player_bet[2]);
    }

    #[tokio::test]
    async fn test_simulation_complex_showdown() {
        let stacks = vec![102.0, 7.0, 12.0, 102.0, 202.0];
        let mut game_state = test_game_state(stacks, 10.0, 5.0, 2.0, 0);
        let mut deck = CardBitSet::default();

        // Start
        game_state.advance_round();

        // Ante
        game_state.do_bet(2.0, true).unwrap(); // ante@idx 1
        game_state.do_bet(2.0, true).unwrap(); // ante@idx 2
        game_state.do_bet(2.0, true).unwrap(); // ante@idx 3
        game_state.do_bet(2.0, true).unwrap(); // ante@idx 4
        game_state.do_bet(2.0, true).unwrap(); // ante@idx 0
        game_state.advance_round();

        // Deal Preflop
        deal_hand_card(0, "Ks", &mut deck, &mut game_state);
        deal_hand_card(0, "Kh", &mut deck, &mut game_state);

        deal_hand_card(1, "As", &mut deck, &mut game_state);
        deal_hand_card(1, "Ac", &mut deck, &mut game_state);

        deal_hand_card(2, "Ad", &mut deck, &mut game_state);
        deal_hand_card(2, "Ah", &mut deck, &mut game_state);

        deal_hand_card(3, "6d", &mut deck, &mut game_state);
        deal_hand_card(3, "4d", &mut deck, &mut game_state);

        deal_hand_card(4, "9d", &mut deck, &mut game_state);
        deal_hand_card(4, "9s", &mut deck, &mut game_state);
        game_state.advance_round();

        // Preflop
        game_state.do_bet(5.0, true).unwrap(); // blinds@idx 1
        game_state.do_bet(10.0, true).unwrap(); // blinds@idx 2
        game_state.fold(); // idx 3
        game_state.do_bet(10.0, false).unwrap(); // idx 4
        game_state.do_bet(10.0, false).unwrap(); // idx 0
        game_state.advance_round();

        // Deal Flop
        deal_community_card("6c", &mut deck, &mut game_state);
        deal_community_card("2d", &mut deck, &mut game_state);
        deal_community_card("3d", &mut deck, &mut game_state);
        game_state.advance_round();

        // Flop
        assert_eq!(game_state.num_active_players(), 2);
        game_state.do_bet(90.0, false).unwrap(); // idx 4
        game_state.do_bet(90.0, false).unwrap(); // idx 0
        game_state.advance_round();
        assert_eq!(game_state.num_active_players(), 1);

        // Deal Turn
        deal_community_card("8h", &mut deck, &mut game_state);
        game_state.advance_round();

        // Turn
        game_state.do_bet(0.0, false).unwrap(); // idx 4
        game_state.advance_round();
        assert_eq!(game_state.num_active_players(), 1);

        // Deal River
        deal_community_card("8s", &mut deck, &mut game_state);
        game_state.advance_round();

        // River
        game_state.do_bet(100.0, false).unwrap(); // idx 4
        game_state.advance_round();
        assert_eq!(game_state.num_active_players(), 0);

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .build()
            .unwrap();
        sim.run().await;

        assert_eq!(Round::Complete, sim.game_state.round);

        assert_eq!(180.0, sim.game_state.player_winnings[0]);
        assert_eq!(15.0, sim.game_state.player_winnings[1]);
        assert_eq!(30.0, sim.game_state.player_winnings[2]);
        assert_eq!(0.0, sim.game_state.player_winnings[3]);
        assert_eq!(100.0, sim.game_state.player_winnings[4]);

        assert_eq!(180.0, sim.game_state.stacks[0]);
        assert_eq!(15.0, sim.game_state.stacks[1]);
        assert_eq!(30.0, sim.game_state.stacks[2]);
        assert_eq!(100.0, sim.game_state.stacks[3]);
        assert_eq!(100.0, sim.game_state.stacks[4]);
    }

    fn deal_hand_card(
        idx: usize,
        card_str: &str,
        deck: &mut CardBitSet,
        game_state: &mut GameState,
    ) {
        let card = Card::try_from(card_str).unwrap();
        assert!(deck.contains(card));
        deck.remove(card);
        game_state.hands[idx].insert(card);
    }

    fn deal_community_card(card_str: &str, deck: &mut CardBitSet, game_state: &mut GameState) {
        let card = Card::try_from(card_str).unwrap();
        assert!(deck.contains(card));
        deck.remove(card);
        for h in &mut game_state.hands {
            h.insert(card);
        }

        game_state.board.push(card);
    }

    /// An agent that returns an invalid bet amount to trigger error handling
    #[derive(Clone)]
    struct InvalidBetAgent {
        name: String,
        bet_amount: f32,
    }

    #[async_trait::async_trait]
    impl crate::arena::Agent for InvalidBetAgent {
        async fn act(&mut self, _id: u128, _game_state: &GameState) -> AgentAction {
            AgentAction::Bet(self.bet_amount)
        }

        fn name(&self) -> &str {
            &self.name
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_invalid_bet_triggers_fold() {
        let stacks = vec![100.0; 3];
        let game_state = test_game_state(stacks, 10.0, 5.0, 0.0, 0);

        // Create an agent that bets 1.0 - less than the big blind, which is invalid
        let invalid_agent = InvalidBetAgent {
            name: "InvalidBetAgent".to_string(),
            bet_amount: 1.0, // Too small to call the big blind
        };

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .panic_on_historian_error(false)
            .agents(vec![
                Box::new(invalid_agent.clone()),
                Box::new(invalid_agent.clone()),
                Box::new(invalid_agent.clone()),
            ])
            .build_with_rng(StdRng::seed_from_u64(42))
            .unwrap();

        // Run the simulation - agents with invalid bets should be force-folded
        sim.run().await;

        // Game should complete
        assert_eq!(Round::Complete, sim.game_state.round);
    }

    #[test]
    fn test_num_agents() {
        let stacks = vec![100.0; 5];
        let game_state = test_game_state(stacks, 10.0, 5.0, 0.0, 0);
        let sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .build()
            .unwrap();

        assert_eq!(5, sim.num_agents());
    }

    #[test]
    fn test_max_raises_default_is_three() {
        let stacks = vec![100.0; 2];
        let game_state = test_game_state(stacks, 10.0, 5.0, 0.0, 0);
        let sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .build()
            .unwrap();

        assert_eq!(Some(3), sim.game_state.max_raises_per_round);
    }

    #[test]
    fn test_max_raises_none_allows_unlimited() {
        let game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .max_raises_per_round(None)
            .build()
            .unwrap();
        let sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .build()
            .unwrap();

        assert_eq!(None, sim.game_state.max_raises_per_round);
    }

    /// Agent that always raises by min-raise amount
    #[derive(Clone)]
    struct RaisingAgent {
        name: String,
    }

    #[async_trait::async_trait]
    impl crate::arena::Agent for RaisingAgent {
        async fn act(&mut self, _id: u128, game_state: &GameState) -> AgentAction {
            // Always try to raise by min-raise
            let current_bet = game_state.current_round_bet();
            let min_raise = game_state.current_round_min_raise();
            AgentAction::Bet(current_bet + min_raise)
        }

        fn name(&self) -> &str {
            &self.name
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_max_raises_converts_raise_to_call() {
        use crate::arena::action::Action;
        use crate::arena::historian::VecHistorian;

        let game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 1000.0)
            .blinds(10.0, 5.0)
            .max_raises_per_round(Some(2)) // Only 2 raises allowed
            .build()
            .unwrap();

        let hist = Box::new(VecHistorian::default());
        let records = hist.get_storage();

        let raiser = RaisingAgent {
            name: "Raiser".to_string(),
        };

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .agents(vec![Box::new(raiser.clone()), Box::new(raiser.clone())])
            .historians(vec![hist])
            .build_with_rng(StdRng::seed_from_u64(42))
            .unwrap();

        // Run just the preflop betting round
        // Starting -> Ante -> DealPreflop -> Preflop
        sim.run_round().await; // Starting
        sim.run_round().await; // Ante
        sim.run_round().await; // DealPreflop
        sim.run_round().await; // Preflop (runs betting)

        // Count failed actions (raises converted to calls)
        let failed_actions: Vec<_> = records
            .lock()
            .unwrap()
            .iter()
            .filter(|r| matches!(r.action, Action::FailedAction(_)))
            .cloned()
            .collect();

        // With max_raises=2, after 2 raises, subsequent raise attempts should fail
        assert!(
            !failed_actions.is_empty(),
            "Expected some raises to be converted to calls"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_max_raises_all_in_always_allowed() {
        use crate::arena::action::Action;
        use crate::arena::historian::VecHistorian;

        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 100.0)
            .blinds(10.0, 5.0)
            .max_raises_per_round(Some(3)) // Max 3 raises
            .build()
            .unwrap();

        // Advance to preflop and post blinds
        game_state.advance_round(); // Starting
        game_state.advance_round(); // Ante
        game_state.advance_round(); // DealPreflop
        game_state.advance_round(); // Preflop
        game_state.do_bet(5.0, true).unwrap(); // SB posts
        game_state.do_bet(10.0, true).unwrap(); // BB posts

        // Manually set raise count to max to simulate raises already occurred
        game_state.round_data.total_raise_count = 3;

        // Current state: SB to act, has bet 5, needs to match 10 (BB)
        // SB stack is 95.0, BB stack is 90.0

        let hist = Box::new(VecHistorian::default());
        let records = hist.get_storage();

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .agents(vec![
                Box::<crate::arena::agent::FoldingAgent>::default(),
                Box::<crate::arena::agent::FoldingAgent>::default(),
            ])
            .historians(vec![hist])
            .build()
            .unwrap();

        // SB is to act (idx 0 after blinds in 2-player)
        // Current bet is 10.0, player bet is 5.0, stack is 95.0
        // All-in bet would be 5.0 (current) + 95.0 (stack) = 100.0
        let all_in_bet = sim.game_state.current_round_current_player_bet()
            + sim.game_state.current_player_stack();
        assert!(
            all_in_bet > sim.game_state.current_round_bet(),
            "All-in should be a raise"
        );

        // Manually call run_agent_action with an all-in bet
        sim.run_agent_action(AgentAction::Bet(all_in_bet)).await;

        // The all-in should be recorded as PlayedAction, not FailedAction
        let played: Vec<_> = records
            .lock()
            .unwrap()
            .iter()
            .filter(|r| matches!(r.action, Action::PlayedAction(_)))
            .cloned()
            .collect();

        let failed: Vec<_> = records
            .lock()
            .unwrap()
            .iter()
            .filter(|r| matches!(r.action, Action::FailedAction(_)))
            .cloned()
            .collect();

        assert_eq!(played.len(), 1, "All-in should be recorded as PlayedAction");
        assert!(
            failed.is_empty(),
            "All-in should NOT be recorded as FailedAction"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_max_raises_resets_each_round() {
        let game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 500.0)
            .blinds(10.0, 5.0)
            .max_raises_per_round(Some(2))
            .build()
            .unwrap();

        let raiser = RaisingAgent {
            name: "Raiser".to_string(),
        };

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .agents(vec![Box::new(raiser.clone()), Box::new(raiser.clone())])
            .build_with_rng(StdRng::seed_from_u64(42))
            .unwrap();

        // Run through preflop
        sim.run_round().await; // Starting
        sim.run_round().await; // Ante
        sim.run_round().await; // DealPreflop
        sim.run_round().await; // Preflop betting

        // After preflop, advance to flop
        sim.run_round().await; // DealFlop

        // The raise count should be 0 at the start of flop
        assert_eq!(
            sim.game_state.round_data.total_raise_count, 0,
            "Raise count should reset at the start of each betting round"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_max_raises_records_failed_action() {
        use crate::arena::action::Action;
        use crate::arena::historian::VecHistorian;

        let mut game_state = GameStateBuilder::new()
            .num_players_with_stack(2, 1000.0)
            .blinds(10.0, 5.0)
            .max_raises_per_round(Some(2))
            .build()
            .unwrap();

        // Advance to preflop and post blinds
        game_state.advance_round(); // Starting
        game_state.advance_round(); // Ante
        game_state.advance_round(); // DealPreflop
        game_state.advance_round(); // Preflop
        game_state.do_bet(5.0, true).unwrap(); // SB
        game_state.do_bet(10.0, true).unwrap(); // BB

        // Set raise count to max
        game_state.round_data.total_raise_count = 2;

        let hist = Box::new(VecHistorian::default());
        let records = hist.get_storage();

        let raiser = RaisingAgent {
            name: "Raiser".to_string(),
        };

        let mut sim = HoldemSimulationBuilder::default()
            .game_state(game_state)
            .agents(vec![Box::new(raiser.clone()), Box::new(raiser.clone())])
            .historians(vec![hist])
            .build()
            .unwrap();

        // Directly call run_agent_action with a raise attempt
        // Current bet is 10 (BB), min raise is 10, so a raise to 20 should be capped
        sim.run_agent_action(AgentAction::Bet(20.0)).await;

        // The raise should be recorded as a FailedAction
        let failed_actions: Vec<_> = records
            .lock()
            .unwrap()
            .iter()
            .filter_map(|r| {
                if let Action::FailedAction(payload) = &r.action {
                    Some(payload.clone())
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(
            failed_actions.len(),
            1,
            "Should have exactly one failed action"
        );

        // Verify the original action was a Bet (raise attempt)
        assert!(
            matches!(failed_actions[0].action, AgentAction::Bet(_)),
            "Original action should be a Bet"
        );

        // Verify the result action is a Bet at the call amount (not a raise)
        if let AgentAction::Bet(amount) = failed_actions[0].result.action {
            assert_eq!(
                amount, failed_actions[0].result.starting_bet,
                "Result should be a call at the current bet level"
            );
        } else {
            panic!("Result action should be a Bet");
        }
    }
}