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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
use std::fmt;

use smallvec::SmallVec;
use tracing::{Level, event, instrument};

use crate::arena::action::{FailedActionPayload, PlayedActionPayload};
use crate::arena::game_state::Round;
use crate::core::{Card, Deck, Rank, Rankable};

use super::action::{
    Action, AgentAction, AwardPayload, DealStartingHandPayload, ForcedBetPayload, GameStartPayload,
    PlayerSitPayload,
};

use super::Agent;
use super::GameState;
use super::historian::Historian;

/// # Description
///
/// This code is implementing a version of Texas Hold'em poker. It is a
/// simulation of the game that can be played with computer agents. The game
/// progresses through a number of rounds: Starting,
/// Preflop,
/// Flop,
/// Turn,
/// River, and
/// Showdown.
///
/// The simulation creates a deck of cards, shuffles it, and deals cards to the
/// players. The players then take turns making bets, raising or folding until
/// the round is complete. Then, the game moves to the next round, and the
/// process repeats. At the end of the game, the player with the best hand wins.
///
/// The simulation is designed to be used with agents that can make decisions
/// based on the game state. The `HoldemSimulation` struct keeps track of the
/// game state, the deck, and the actions taken in the game.
///
/// The `run` method can be used to run the entire game
///
/// # Behavior
///
/// - Any agent bet that is an over bet will silently turn into an all in. That
///   is to say if an agent has 100 in their stack and bet `100_000_000` that
///   will be accepted and will be equivilant to bet `100`
/// - Any bet that `GameState` rules as being impossible, those that turn into
///   [`rs-poker::arena::errors::GameStateError`] will instead be turned into
///   fold.
/// - It's expected that you have the same number of agents as you have chip
///   stacks in the game state. If players are not active, you can use the
///   `FoldingAgent` as a stand in and set the active bit to false.
pub struct HoldemSimulation {
    /// A randomly generated ID to represent the simulation.
    pub id: u128,
    pub agents: Vec<Box<dyn Agent>>,
    pub game_state: GameState,
    pub deck: Deck,
    pub historians: Vec<Box<dyn Historian>>,
    pub panic_on_historian_error: bool,
    /// The RNG this simulation deals from. Owned so `run()` can be `async` and
    /// spawned without borrowing an external `&mut R` across await points.
    pub rng: Box<dyn rand::Rng + Send>,
}

impl HoldemSimulation {
    pub fn more_rounds(&self) -> bool {
        !matches!(self.game_state.round, Round::Complete)
    }
    /// Returns the number of poker agents participating in this simulation.
    pub fn num_agents(&self) -> usize {
        self.agents.len()
    }

    /// Run the simulation all the way to completion. This will mutate the
    /// current state.
    ///
    /// The span is attached via `#[instrument]` (not a manual `span.enter()`
    /// guard) so it is correctly entered/exited around every `.await`
    /// suspension point on a multi-thread runtime.
    #[instrument(
        level = "debug",
        skip(self),
        fields(id = self.id, num_players = self.game_state.num_players)
    )]
    pub async fn run(&mut self) {
        while self.more_rounds() {
            self.run_round().await;
        }
    }

    pub async fn run_round(&mut self) {
        match self.game_state.round {
            // Dealing the user hand is dealt with as its own round
            // in order to use the per round active bit set
            // for iterating players
            Round::Starting => self.start().await,
            Round::Ante => self.ante().await,

            Round::DealPreflop => self.deal_preflop().await,
            Round::Preflop => self.preflop().await,

            Round::DealFlop => self.deal_flop().await,
            Round::Flop => self.flop().await,

            Round::DealTurn => self.deal_turn().await,
            Round::Turn => self.turn().await,

            Round::DealRiver => self.deal_river().await,
            Round::River => self.river().await,

            Round::Showdown => self.showdown().await,

            // There's nothing left to do to this.
            Round::Complete => (),
        }
    }

    async fn start(&mut self) {
        // Add an action to record the ante, sb and bb
        // This should allow recreating starting game state
        // together with PlayerSit actions.
        self.record_action(Action::GameStart(GameStartPayload {
            ante: self.game_state.ante,
            small_blind: self.game_state.small_blind,
            big_blind: self.game_state.big_blind,
        }))
        .await;

        while self.game_state.current_round_num_active_players() > 0 {
            let idx = self.game_state.to_act_idx();

            // Add an action that records starting stack for each player
            // Starting with to the left of the dealer
            // and ending with dealer button.
            self.record_action(Action::PlayerSit(PlayerSitPayload {
                player_stack: self.game_state.stacks[idx],
                idx,
                name: Some(self.agents[idx].name().to_string()),
            }))
            .await;

            // set the active bit on the player to false.
            // This allows us to not deal to players that
            // are sitting out, while also going in the same
            // order of dealing
            self.game_state.round_data.needs_action.disable(idx);

            self.game_state.round_data.advance_action();
        }

        // We're done with the non-betting dealing only round
        self.advance_round().await;
    }

    async fn ante(&mut self) {
        let ante = self.game_state.ante;
        if ante > 0.0 {
            // Force the ante from each active player.
            while self.game_state.current_round_num_active_players() > 0 {
                let idx = self.game_state.to_act_idx();

                let actual_ante = self.game_state.do_bet(ante, true).unwrap();
                self.record_action(Action::ForcedBet(ForcedBetPayload {
                    bet: actual_ante,
                    idx,
                    player_stack: self.game_state.stacks[idx],
                    forced_bet_type: super::action::ForcedBetType::Ante,
                }))
                .await;

                self.game_state.round_data.needs_action.disable(idx);
            }
        }
        self.advance_round().await;
    }

    async fn deal_preflop(&mut self) {
        // We deal the cards before advancing the round
        // This allows us to use the round active bitset
        while self.game_state.current_round_num_active_players() > 0 {
            let idx = self.game_state.to_act_idx();

            self.deal_player_cards(2).await;

            // This allows us to not deal to players that
            // are sitting out, while also going in the same
            // order of dealing
            self.game_state.round_data.needs_action.disable(idx);

            self.game_state.round_data.advance_action();
        }
        self.advance_round().await
    }

    async fn preflop(&mut self) {
        // Force the small blind and the big blind.
        if !self.game_state.sb_posted {
            let sb = self.game_state.small_blind;
            let sb_idx = self.game_state.to_act_idx();
            let actual_sb = self.game_state.do_bet(sb, true).unwrap();
            self.game_state.sb_posted = true;

            self.record_action(Action::ForcedBet(ForcedBetPayload {
                bet: actual_sb,
                idx: sb_idx,
                forced_bet_type: super::action::ForcedBetType::SmallBlind,
                player_stack: self.game_state.stacks[sb_idx],
            }))
            .await;
        }

        if !self.game_state.bb_posted {
            let bb = self.game_state.big_blind;
            let bb_idx = self.game_state.to_act_idx();
            let actual_bb = self.game_state.do_bet(bb, true).unwrap();
            self.game_state.bb_posted = true;
            self.record_action(Action::ForcedBet(ForcedBetPayload {
                bet: actual_bb,
                idx: bb_idx,
                forced_bet_type: super::action::ForcedBetType::BigBlind,
                player_stack: self.game_state.stacks[bb_idx],
            }))
            .await;
        }

        self.run_betting_round().await;
        self.advance_round().await;
    }

    async fn deal_flop(&mut self) {
        self.deal_comunity_cards(3).await;
        self.advance_round().await;
    }

    async fn flop(&mut self) {
        self.run_betting_round().await;
        self.advance_round().await;
    }

    async fn deal_turn(&mut self) {
        self.deal_comunity_cards(1).await;
        self.advance_round().await;
    }

    async fn turn(&mut self) {
        self.run_betting_round().await;
        self.advance_round().await;
    }

    async fn deal_river(&mut self) {
        self.deal_comunity_cards(1).await;
        self.advance_round().await;
    }
    async fn river(&mut self) {
        self.run_betting_round().await;
        self.advance_round().await;
    }

    async fn showdown(&mut self) {
        // Rank each player that still has a chance.
        let active = self.game_state.player_active | self.game_state.player_all_in;

        let mut bets = self.game_state.player_bet.clone();

        // Collect (rank, player_idx) pairs sorted by rank descending (best first),
        // then by bet ascending within same rank (smallest bets first for side pots).
        // This replaces the BTreeMap<Rank, Vec<usize>> to avoid heap allocations.
        // Inline up to a full table (PlayerBitSet caps at 16) — no heap alloc.
        let mut ranked_players: SmallVec<[(Rank, usize); 16]> = active
            .ones()
            .map(|idx| (self.game_state.hands[idx].rank(), idx))
            .collect();
        ranked_players.sort_by(|a, b| {
            b.0.cmp(&a.0)
                .then_with(|| bets[a.1].partial_cmp(&bets[b.1]).unwrap())
        });

        // There can be bets that players made but didn't take to showdown they should
        // be added to the main pot. Keep them here and then split them up
        // between the winners of the first rank pot. resetting the ammount to
        // zero.
        let mut folded_pot = bets
            .iter()
            .enumerate()
            .filter(|(idx, _)| !active.get(*idx))
            .map(|(_, bet)| *bet)
            .sum::<f32>();
        bets = bets
            .iter()
            .enumerate()
            .map(|(idx, v)| if active.get(idx) { *v } else { 0.0 })
            .collect();

        // Process groups of players with the same rank (consecutive in sorted order).
        // Within each group, iterate from smallest bet to largest to handle side pots.
        let mut group_start = 0;
        while group_start < ranked_players.len() {
            let rank = ranked_players[group_start].0;
            let mut group_end = group_start + 1;
            while group_end < ranked_players.len() && ranked_players[group_end].0 == rank {
                group_end += 1;
            }

            let mut start_idx = group_start;

            // We'll continue until every player has been given the matching money
            // up to their wager. However since some players might have gone allin
            // earlier we keep removing from the pot and splitting it equally to all
            // those players still left in the pot.
            while start_idx < group_end {
                // Because our lists are ordered from smallest bets to largest
                // we can just assume the first one is the smallest
                //
                // Here we use that property to find the max bet that this pot
                // will give for this round of splitting ties.
                let max_wager = bets[ranked_players[start_idx].1];
                let mut pot: f64 = f64::from(folded_pot);
                folded_pot = 0.0;

                // Most common is that ties will
                // be for wagers that are all the same.
                // So check if there's no more
                // bets to award for this player.
                if max_wager <= 0.0 {
                    start_idx += 1;
                    continue;
                }

                // Take all the wagers remaining into a
                // side pot. However this side pot might
                // be the only pot if there were no allins
                for b in bets.iter_mut() {
                    let w = (*b).min(max_wager);
                    *b -= w;
                    pot += w as f64;
                }

                // Now all the winning players get
                // an equal share of the side pot
                let num_players = (group_end - start_idx) as f64;
                let split = pot / num_players;

                for entry in &ranked_players[start_idx..group_end] {
                    let idx = entry.1;
                    // Record that this player won something
                    event!(Level::DEBUG, idx, split, pot, ?rank, "pot_awarded");
                    self.game_state.award(idx, split as f32);
                    self.record_action(Action::Award(AwardPayload {
                        idx,
                        total_pot: pot as f32,
                        award_amount: split as f32,
                        // Since we had a showdown we can copy the hand
                        // and the resulting rank.
                        rank: Some(rank),
                        hand: Some(self.game_state.hands[idx]),
                    }))
                    .await;
                }

                // Since the first player is bet size
                // that we used. They have won everything that they're eligible for.
                start_idx += 1;
            }

            group_start = group_end;
        }

        self.end_game().await;
    }

    async fn deal_player_cards(&mut self, num_cards: usize) {
        let new_hand = self.deal_cards(num_cards);
        for c in &new_hand {
            self.record_action(Action::DealStartingHand(DealStartingHandPayload {
                card: *c,
                idx: self.game_state.to_act_idx(),
            }))
            .await;
        }

        let idx = self.game_state.to_act_idx();
        self.game_state.hands[idx].extend(new_hand);
    }

    async fn deal_comunity_cards(&mut self, num_cards: usize) {
        let community_cards = self.deal_cards(num_cards);
        for c in &community_cards {
            self.record_action(Action::DealCommunity(*c)).await;
        }
        // Add all the cards to the hands as well.
        for h in &mut self.game_state.hands {
            h.extend(community_cards.to_owned());
        }
        // Move the community_cards into the game_state board.
        self.game_state.board.extend(community_cards);
    }

    /// Pull num_cards from the deck and return them. A single deal is small (≤5:
    /// flop, turn, river, or 2 hole cards), so an inline `SmallVec` keeps it off
    /// the heap.
    fn deal_cards(&mut self, num_cards: usize) -> SmallVec<[Card; 5]> {
        // Reborrow the boxed RNG as a sized `&mut` reference so it satisfies
        // the `R: Rng` (Sized) bound on `Deck::deal`.
        let deck = &mut self.deck;
        let mut rng = &mut *self.rng;
        let mut cards: SmallVec<[Card; 5]> = (0..num_cards)
            .map(|_| deck.deal(&mut rng).unwrap())
            .collect();

        // Keep the cards sorted in min to max order
        // this keeps the number of permutations down since
        // its now AsKsKd is the same as KdAsKs after sorting.
        cards.sort();

        cards
    }

    /// This runs betting for the round to completion. It will run until
    /// everyone has acted or until the round has been completed because no one
    /// can act anymore.
    ///
    /// When fewer than 2 players are active (the rest are all-in or folded),
    /// we skip the round since the lone active player has no one to bet against.
    /// However, if there's an unmatched bet (e.g., an all-in or a blind that
    /// hasn't been called), active players must still fold or call.
    async fn run_betting_round(&mut self) {
        let current_round = self.game_state.round;
        if self.game_state.player_active.count() < 2 {
            let has_unmatched_bet = self.game_state.player_active.ones().any(|idx| {
                self.game_state.round_data.player_bet[idx] < self.game_state.round_data.bet
            });
            if !has_unmatched_bet {
                return;
            }
        }
        while self.needs_action() && self.game_state.round == current_round {
            self.run_single_agent().await;
        }
    }

    fn needs_action(&self) -> bool {
        let active_players = self.game_state.player_active;

        let players_needing_action = self.game_state.round_data.needs_action;

        let active_players_needing_action = active_players & players_needing_action;
        !active_players_needing_action.empty()
    }

    /// Run the next agent in the game state to act.
    async fn run_single_agent(&mut self) {
        let idx = self.game_state.to_act_idx();
        let action = self.agents[idx].act(self.id, &self.game_state).await;

        event!(Level::TRACE, ?action, idx, "run_agent");
        self.run_agent_action(action).await;
    }

    /// Given the action that an agent wants to take, this function will
    /// determine if the action is valid and then apply it to the game state.
    /// If the action is invalid, the agent will be forced to fold.
    pub async fn run_agent_action(&mut self, agent_action: AgentAction) {
        event!(Level::TRACE, ?agent_action, "run_agent_action");

        let idx = self.game_state.to_act_idx();
        let starting_bet = self.game_state.current_round_bet();
        let starting_player_bet = self.game_state.current_round_player_bet(idx);
        let starting_min_raise = self.game_state.current_round_min_raise();
        let starting_pot = self.game_state.total_pot;

        match agent_action {
            AgentAction::Fold => {
                // It plays hell on verifying games if there are players that quit when there's
                // no money in being asked for. For now do exact equality, but
                // this might be a place we should use approxiate compaison
                // crate.
                if starting_player_bet == starting_bet {
                    event!(Level::WARN, "fold_error");

                    let new_action = AgentAction::Bet(starting_bet);

                    self.game_state.do_bet(starting_bet, false).unwrap();
                    self.record_action(Action::FailedAction(FailedActionPayload {
                        action: agent_action,
                        result: PlayedActionPayload {
                            action: new_action,
                            player_stack: self.game_state.stacks[idx],
                            idx,
                            round: self.game_state.round,
                            starting_bet,
                            final_bet: starting_bet,
                            starting_min_raise,
                            final_min_raise: self.game_state.current_round_min_raise(),
                            starting_player_bet,
                            final_player_bet: starting_player_bet,
                            players_active: self.game_state.player_active,
                            players_all_in: self.game_state.player_all_in,
                            starting_pot,
                            final_pot: self.game_state.total_pot,
                        },
                    }))
                    .await;
                } else {
                    self.record_action(Action::PlayedAction(PlayedActionPayload {
                        action: agent_action,
                        player_stack: self.game_state.stacks[idx],
                        idx,
                        round: self.game_state.round,
                        // None of the bets move if this is a fold
                        starting_bet,
                        final_bet: starting_bet,
                        starting_min_raise,
                        final_min_raise: self.game_state.current_round_min_raise(),
                        starting_player_bet,
                        final_player_bet: starting_player_bet,
                        players_active: self.game_state.player_active,
                        players_all_in: self.game_state.player_all_in,
                        starting_pot,
                        final_pot: self.game_state.total_pot,
                    }))
                    .await;
                    self.player_fold().await;
                }
            }
            AgentAction::Bet(bet_amount) => {
                // Check if this raise would exceed the max raises per round limit
                let is_raise = bet_amount > starting_bet;
                let is_raise_capped = self.game_state.is_raise_capped();

                // All-in is always allowed regardless of raise cap
                // A bet is all-in if it uses the player's entire remaining stack
                let stack = self.game_state.current_player_stack();
                let is_all_in = bet_amount >= starting_player_bet + stack;

                // If this is a raise but raises are capped (and not all-in), convert to call
                let effective_bet_amount = if is_raise && is_raise_capped && !is_all_in {
                    starting_bet
                } else {
                    bet_amount
                };

                let bet_result = self.game_state.do_bet(effective_bet_amount, false);

                match bet_result {
                    Err(error) => {
                        // If the agent failed to give us a good bet then they lose this round.
                        //
                        // We emit the error as an event with detailed context for debugging.
                        // Assume that game_state.do_bet() will have changed nothing since it
                        // errored out Add an action that shows the user was
                        // force folded. Actually fold the user
                        event!(
                            Level::WARN,
                            ?error,
                            agent_name = %self.agents[idx].name(),
                            bet_amount = bet_amount,
                            current_bet = starting_bet,
                            player_bet = starting_player_bet,
                            player_stack = self.game_state.stacks[idx],
                            min_raise = starting_min_raise,
                            "bet_error"
                        );

                        // Record this errant action
                        self.record_action(Action::FailedAction(FailedActionPayload {
                            action: agent_action,
                            result: PlayedActionPayload {
                                action: AgentAction::Fold,
                                player_stack: self.game_state.stacks[idx],
                                idx,
                                round: self.game_state.round,
                                starting_bet,
                                final_bet: starting_bet,
                                starting_min_raise,
                                final_min_raise: self.game_state.current_round_min_raise(),
                                starting_player_bet,
                                final_player_bet: starting_player_bet,
                                players_active: self.game_state.player_active,
                                players_all_in: self.game_state.player_all_in,
                                // What's the pot worth
                                starting_pot,
                                final_pot: self.game_state.total_pot,
                            },
                        }))
                        .await;

                        // Actually fold the user
                        self.player_fold().await;
                    }
                    Ok(_added) => {
                        let player_bet = self.game_state.current_round_player_bet(idx);

                        let new_action = match agent_action {
                            AgentAction::Bet(_) => AgentAction::Bet(player_bet),
                            AgentAction::Call => AgentAction::Call,
                            AgentAction::Fold => AgentAction::Fold,
                            AgentAction::AllIn => AgentAction::AllIn,
                        };

                        let payload = PlayedActionPayload {
                            action: new_action,
                            player_stack: self.game_state.stacks[idx],
                            idx,
                            round: self.game_state.round,
                            starting_bet,
                            final_bet: self.game_state.current_round_bet(),
                            starting_min_raise,
                            final_min_raise: self.game_state.current_round_min_raise(),
                            starting_player_bet,
                            final_player_bet: player_bet,
                            players_active: self.game_state.player_active,
                            players_all_in: self.game_state.player_all_in,
                            starting_pot,
                            final_pot: self.game_state.total_pot,
                        };

                        // If the raise was capped (and not all-in), record as failed action
                        if is_raise && is_raise_capped && !is_all_in {
                            event!(
                                Level::DEBUG,
                                agent_name = %self.agents[idx].name(),
                                original_bet = bet_amount,
                                effective_bet = effective_bet_amount,
                                raise_count = self.game_state.round_data.total_raise_count,
                                "raise_capped_to_call"
                            );
                            self.record_action(Action::FailedAction(FailedActionPayload {
                                action: agent_action,
                                result: payload,
                            }))
                            .await;
                        } else {
                            self.record_action(Action::PlayedAction(payload)).await;
                        }
                    }
                }
            }
            AgentAction::Call => {
                let call_amount = self.game_state.current_round_bet();
                let bet_result = self.game_state.do_bet(call_amount, false);

                match bet_result {
                    Err(error) => {
                        // If the agent failed to give us a good bet then they lose this round.
                        //
                        // We emit the error as an event with detailed context for debugging.
                        // Assume that game_state.do_bet() will have changed nothing since it
                        // errored out Add an action that shows the user was
                        // force folded. Actually fold the user
                        event!(
                            Level::WARN,
                            ?error,
                            agent_name = %self.agents[idx].name(),
                            current_bet = starting_bet,
                            player_bet = starting_player_bet,
                            player_stack = self.game_state.stacks[idx],
                            min_raise = starting_min_raise,
                            "bet_error"
                        );

                        // Record this errant action
                        self.record_action(Action::FailedAction(FailedActionPayload {
                            action: agent_action,
                            result: PlayedActionPayload {
                                action: AgentAction::Fold,
                                player_stack: self.game_state.stacks[idx],
                                idx,
                                round: self.game_state.round,
                                starting_bet,
                                final_bet: starting_bet,
                                starting_min_raise,
                                final_min_raise: self.game_state.current_round_min_raise(),
                                starting_player_bet,
                                final_player_bet: starting_player_bet,
                                players_active: self.game_state.player_active,
                                players_all_in: self.game_state.player_all_in,
                                // What's the pot worth
                                starting_pot,
                                final_pot: self.game_state.total_pot,
                            },
                        }))
                        .await;

                        // Actually fold the user
                        self.player_fold().await;
                    }
                    Ok(_added) => {
                        let player_bet = self.game_state.current_round_player_bet(idx);

                        let new_action = match agent_action {
                            AgentAction::Call => AgentAction::Call,
                            AgentAction::Bet(_) => AgentAction::Bet(player_bet),
                            AgentAction::Fold => AgentAction::Fold,
                            AgentAction::AllIn => AgentAction::AllIn,
                        };
                        // If the game_state.do_bet function returned Ok then
                        // the state is already changed so record the action as played.
                        self.record_action(Action::PlayedAction(PlayedActionPayload {
                            action: new_action,
                            player_stack: self.game_state.stacks[idx],
                            idx,
                            round: self.game_state.round,
                            starting_bet,
                            final_bet: self.game_state.current_round_bet(),
                            starting_min_raise,
                            final_min_raise: self.game_state.current_round_min_raise(),
                            starting_player_bet,
                            final_player_bet: player_bet,
                            // Keep track of who's in a
                            players_active: self.game_state.player_active,
                            players_all_in: self.game_state.player_all_in,
                            // What's the pot worth
                            starting_pot,
                            final_pot: self.game_state.total_pot,
                        }))
                        .await;
                    }
                }
            }
            AgentAction::AllIn => {
                let all_in_amount = self.game_state.current_round_current_player_bet()
                    + self.game_state.current_player_stack();
                let bet_result = self.game_state.do_bet(all_in_amount, false);

                match bet_result {
                    Err(error) => {
                        // If the agent failed to give us a good bet then they lose this round.
                        //
                        // We emit the error as an event with detailed context for debugging.
                        // Assume that game_state.do_bet() will have changed nothing since it
                        // errored out Add an action that shows the user was
                        // force folded. Actually fold the user
                        event!(
                            Level::WARN,
                            ?error,
                            agent_name = %self.agents[idx].name(),
                            current_bet = starting_bet,
                            player_bet = starting_player_bet,
                            player_stack = self.game_state.stacks[idx],
                            min_raise = starting_min_raise,
                            "bet_error"
                        );

                        // Record this errant action
                        self.record_action(Action::FailedAction(FailedActionPayload {
                            action: agent_action,
                            result: PlayedActionPayload {
                                action: AgentAction::Fold,
                                player_stack: self.game_state.stacks[idx],
                                idx,
                                round: self.game_state.round,
                                starting_bet,
                                final_bet: starting_bet,
                                starting_min_raise,
                                final_min_raise: self.game_state.current_round_min_raise(),
                                starting_player_bet,
                                final_player_bet: starting_player_bet,
                                players_active: self.game_state.player_active,
                                players_all_in: self.game_state.player_all_in,
                                // What's the pot worth
                                starting_pot,
                                final_pot: self.game_state.total_pot,
                            },
                        }))
                        .await;

                        // Actually fold the user
                        self.player_fold().await;
                    }
                    Ok(_added) => {
                        let player_bet = self.game_state.current_round_player_bet(idx);

                        let new_action = match agent_action {
                            AgentAction::Bet(_) => AgentAction::Bet(player_bet),
                            AgentAction::Fold => AgentAction::Fold,
                            AgentAction::Call => AgentAction::Call,
                            AgentAction::AllIn => AgentAction::AllIn,
                        };
                        // If the game_state.do_bet function returned Ok then
                        // the state is already changed so record the action as played.
                        self.record_action(Action::PlayedAction(PlayedActionPayload {
                            action: new_action,
                            player_stack: self.game_state.stacks[idx],
                            idx,
                            round: self.game_state.round,
                            starting_bet,
                            final_bet: self.game_state.current_round_bet(),
                            starting_min_raise,
                            final_min_raise: self.game_state.current_round_min_raise(),
                            starting_player_bet,
                            final_player_bet: player_bet,
                            // Keep track of who's in a
                            players_active: self.game_state.player_active,
                            players_all_in: self.game_state.player_all_in,

                            // What's the pot worth
                            starting_pot,
                            final_pot: self.game_state.total_pot,
                        }))
                        .await;
                    }
                }
            }
        }
    }

    #[instrument(level = "trace", skip(self))]
    async fn player_fold(&mut self) {
        self.game_state.fold();
        let left = self.game_state.player_active | self.game_state.player_all_in;

        // If there's only one person left then they win.
        // If there's no one left, and one person went all in they win.
        //
        if left.count() <= 1 {
            if let Some(winning_idx) = left.ones().next() {
                let total_pot = self.game_state.total_pot;
                event!(Level::DEBUG, winning_idx, total_pot, "folded_to_winner");
                self.game_state.award(winning_idx, total_pot);
                self.record_action(Action::Award(AwardPayload {
                    idx: winning_idx,
                    total_pot,
                    award_amount: total_pot,
                    rank: None,
                    hand: None,
                }))
                .await
            }

            self.end_game().await;
        }
    }

    #[instrument(level = "trace", skip(self))]
    async fn end_game(&mut self) {
        let current_round = self.game_state.round;
        self.game_state.complete();
        if current_round != self.game_state.round {
            self.record_action(Action::RoundAdvance(self.game_state.round))
                .await;
        }
    }

    #[instrument(level = "trace", skip(self))]
    async fn advance_round(&mut self) {
        let current_round = self.game_state.round;
        self.game_state.advance_round();
        if self.game_state.round != current_round {
            self.record_action(Action::RoundAdvance(self.game_state.round))
                .await;
        }
    }

    // Make sure all modifications to game_state are complete before calling
    // `record_action`. Critical for deterministic replays.
    async fn record_action(&mut self, action: Action) {
        event!(Level::TRACE, action = ?action, "add_action");
        let panic_on_error = self.panic_on_historian_error;
        let id = self.id;

        // Walk historians in order; drop any that error. Index walk (not
        // retain_mut) because the body awaits.
        let mut i = 0;
        while i < self.historians.len() {
            let result = {
                let game_state = &self.game_state;
                self.historians[i]
                    .record_action(id, game_state, &action)
                    .await
            };
            match result {
                Ok(()) => i += 1,
                Err(error) => {
                    event!(Level::ERROR, ?error, "historian_error");
                    if panic_on_error {
                        panic!(
                            "Historian error {}\naction={:?}\ngame_state = {:?}",
                            error, action, self.game_state
                        );
                    }
                    self.historians.remove(i);
                }
            }
        }
    }
}

impl fmt::Debug for HoldemSimulation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HoldemSimulation")
            .field("game_state", &self.game_state)
            .field("deck", &self.deck.len())
            .field("historians", &self.historians.len())
            .field("agents", &self.agents.len())
            .field("panic_on_historian_error", &self.panic_on_historian_error)
            .finish()
    }
}