Files
pokerfreak/src/engine/river_subgame.rs
T
mmintelandClaude Opus 5.5 eacf6810c9 Kandidat VETO_AB: River-Defensiv-Veto nur gegen Einsaetze >= 0,9 Topf (Call-Auswahl in grossen Toepfen)
Leckkarte-Umschnitt 18.11.: Live (mit BETTOR+VORFLOP_BAND) foldet gegen kleine River-Einsaetze
Top-Paar/Overpair/Zwei Paar vor allem ueber den Defensiv-Veto. VETO_AB=0.9 auf echten NL2-Spots:
Dev +19 788 bb, Holdout +12 287 bb (sicher). Pflichtfaelle bestanden, LBR und Sim-Leiter bitgleich.
Schalter aus (BEKANNTE_SCHALTER), nicht live. Bericht messung/grosse_calls/TOR.md, STAND §24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:03:12 +01:00

1276 lines
61 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Engine bridge from a live river spot to the pure CFR river solver (`cfr::river`).
//!
//! This is the Stage-A wiring: it turns the engine's own belief (the villain range model, as built
//! in `engine::decide::postflop`) into strength buckets, solves the heads-up river subgame to
//! equilibrium, and reads back hero's **mixed** action for the bucket its real hand sits in. All
//! poker-specific sourcing lives here; the solver stays a pure game over abstract buckets.
//!
//! # What changed from the first slice (and why it matters for exploitability)
//!
//! The first version solved with hero as a revealed **point mass** (one known hand) and then
//! collapsed the equilibrium mix to its majority action. Both make the line maximally exploitable:
//! a point-mass hero lets the solved villain best-respond to hero's exact strength (no need to
//! balance), and a pure readback cannot bluff or defend at the right frequency. Against a villain
//! that best-responds over hero's TRUE range, that bleeds — which the postflop-exploitability
//! harness (`sim::exploit_river`) measured at 32–108 bb/100.
//!
//! This version models hero with the **same strength distribution as the villain** (a symmetric
//! river prior — both players reach the river with strength spread over the board's quantiles) and
//! returns the equilibrium **mix** for hero's bucket. That is a balanced RANGE strategy: value
//! buckets bet, a calibrated fraction of air bluffs (bluff-to-value `s/(P+s)`), bluff-catchers
//! defend at MDF `P/(P+s)`. Live play realises the mix from the spot seed; the harness reads the
//! frequency directly.
//!
//! # Slice (v1)
//!
//! **Heads-up river**, both hero nodes of the solver's tree:
//! - hero first to act (`to_call == 0`) → check / bet,
//! - hero facing a bet (`to_call > 0`, the pre-bet pot `pot - to_call`, bet `to_call`) → fold / call.
//!
//! Multiway, or a villain range the engine cannot enumerate, returns `None` so the caller keeps the
//! heuristic. The solver equilibrium is the unexploitable baseline; whether wiring it into live play
//! also holds the bb/100 ladder is a measured question, not an assumption.
//!
//! # Named approximations
//!
//! - Hero's river range is modelled as the villain's strength distribution, not hero's true line-
//! consistent range. The closer the two, the lower the residual exploitability.
//! - The villain range is cut into `BUCKETS` equal-count (quantile) buckets, so a higher bucket index
//! always wins the showdown; the quantile cut makes the modelled distribution uniform over buckets.
//! - The solver's action abstraction is one bet size, no raises (`cfr::river` v1).
use crate::card::Card;
use crate::cfr::dbr::{solve_restricted, Restriction};
use crate::cfr::kl_br::kl_best_response;
use crate::cfr::river::tree_with_chance;
use crate::cfr::river_game::{build, Act, Bets};
use crate::cfr::solve::{solve, Solved};
use crate::cfr::strategy::Strategy;
use crate::cfr::tree::{Node, Tree};
use crate::exploit::fold_chance::DEFAULT_FOLD_TO_BET;
use crate::exploit::posterior::DEFAULT_AGGRESSION;
use crate::exploit::profile::Profile;
use crate::exploit::range_read::{self, RangeRead};
use crate::game::{Choice, Decision, SeenAction, Spot, Street, Villain};
use crate::hand::showdown::judge;
use crate::hand::strength::Strength;
use crate::rng::Rng;
use crate::sizing::candidates::candidates;
/// CFR+ iterations per live solve. Enough for the tiny tree (9 nodes) to converge; an
/// under-converged solve is itself exploitable, so this is not shaved.
const ITERS: u32 = 12_000;
/// Target bet size as a fraction of the pot; the nearest legal candidate is used.
const TARGET_BET_FRACTION: f64 = 0.66;
// --- Belief + trust gearbox (the crown): turn the read into a believed villain strategy and a KL
// trust radius, so the solver EXPLOITS a known opponent instead of balancing against it, bounded by
// how much the read is trusted. λ = ∞ (no read) returns the proven-unexploitable GTO mix. ---
/// Normalised ladder rank at/above which the believed villain value-bets when checked to (top buckets).
const VALUE_RANK: f64 = 0.60;
/// Normalised ladder rank at/below which the believed villain may bluff when checked to (bottom buckets).
const BLUFF_RANK: f64 = 0.30;
/// Chip-scale of the KL radius at confidence 0.5 (as a fraction of the subgame pot). λ is in payoff
/// (chip) units; tying it to the pot keeps the trust radius scale-free across spot sizes. The map is
/// `λ = LAMBDA_POT_SCALE · pot · (1−c)/c`: c→0 ⇒ λ→∞ (pure GTO), c→1 ⇒ λ→0 (full best response).
const LAMBDA_POT_SCALE: f64 = 1.0;
/// Below this read confidence the gearbox stands down (returns `None`) and the proven heuristic keeps
/// the blind/exploit edge. Rationale: at a weak read λ is huge and the tilt collapses to near-GTO,
/// and GTO river play is itself worse than the heuristic against an unread exploitable field (the −43
/// revert). So the solver only takes over once the read is strong enough to EXPLOIT, never to balance.
const CONFIDENCE_FLOOR: f64 = 0.25;
/// Hero's equilibrium mix at the river node the spot sits on.
pub struct RiverPlan {
/// `true` = hero is facing a bet (`mix` is `[fold, call]`); `false` = hero acts first
/// (`mix` is `[check, bet]`).
pub facing: bool,
/// The two action probabilities for hero's bucket, in the order above.
pub mix: [f64; 2],
/// The bet-to total when acting first (the raise size); `0` facing a bet.
pub bet_to: f64,
/// Human reason for the decision log.
pub reason: String,
}
impl RiverPlan {
/// Probability of the aggressive action (bet, or call facing a bet).
fn forward(&self) -> f64 {
self.mix[1]
}
}
/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable.
fn bet_to(spot: &Spot) -> Option<f64> {
let target = TARGET_BET_FRACTION * spot.pot;
candidates(spot)
.into_iter()
.filter(|to| *to > 0.0 && *to <= spot.hero_stack)
.min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()))
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// A solved card-exact river subgame plus the shared strength ladder, so hero's real hand can be
/// placed on the same buckets the solve used. The `tree` is kept so the belief/trust gearbox can
/// best-respond to a believed villain (`kl_best_response`) over the same game the GTO solve used.
struct Subgame {
tree: Tree,
solved: Solved,
ladder: Vec<Strength>,
}
impl Subgame {
/// The bucket a strength sits in on the shared ladder (its ascending rank, clamped to the top).
fn bucket(&self, s: Strength) -> usize {
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
}
}
/// Build and solve the card-exact heads-up river subgame the engine believes it is in. Hero's range
/// is modelled as the villain's believed range (`hero_combos == villain_combos`, a symmetric river
/// prior); both are bucketed by **exact showdown strength** on one shared ascending ladder, and the
/// joint deal table carries **card removal** between the two ranges — the same construction the
/// exploitability harness uses for the true game. This faithfulness is what lets the equilibrium it
/// plays actually be unexploitable; the coarse symmetric-uniform first cut was not, and measured
/// worse than the heuristic. `None` for fewer than two distinct strengths.
fn subgame(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], pot: f64, bet: f64) -> Option<Subgame> {
let (tree, ladder) = river_tree(spot, hero_combos, villain_combos, pot, bet)?;
let solved = solve(&tree, ITERS, Rng::seeded(spot.seed));
Some(Subgame { tree, solved, ladder })
}
/// The shared strength ladder and the card-exact joint deal table (no solve): what the node-locked
/// best response (`engine::river_br`) evaluates hero on against a fixed villain, without a CFR solve.
pub(crate) fn ladder_chance(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>]) -> Option<(Vec<Strength>, Vec<f64>)> {
let (tree, ladder) = river_tree(spot, hero_combos, villain_combos, 1.0, 1.0)?;
Some((ladder, tree.chance))
}
/// The card-exact river tree and its strength ladder, unsolved (see `subgame`).
fn river_tree(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], pot: f64, bet: f64) -> Option<(Tree, Vec<Strength>)> {
river_tree_weighted(spot, hero_combos, villain_combos, None, pot, bet)
}
/// `river_tree` with a weight per villain combo (the read's range tilt, `RangeRead::reweigh`):
/// each deal counts its villain combo's weight instead of 1. `None` = all 1 (bit-identical).
fn river_tree_weighted(
spot: &Spot,
hero_combos: &[Vec<Card>],
villain_combos: &[Vec<Card>],
villain_weights: Option<&[f64]>,
pot: f64,
bet: f64,
) -> Option<(Tree, Vec<Strength>)> {
let rules = spot.rules();
let judged = |combos: &[Vec<Card>], weights: Option<&[f64]>| -> Vec<(Vec<Card>, Strength, f64)> {
combos
.iter()
.enumerate()
.filter_map(|(i, c)| {
let w = weights.and_then(|w| w.get(i).copied()).unwrap_or(1.0);
judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s, w))
})
.collect()
};
let hero = judged(hero_combos, None);
let villain = judged(villain_combos, villain_weights);
if hero.is_empty() || villain.is_empty() {
return None;
}
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, s, _)| *s).collect();
ladder.sort();
ladder.dedup();
let n = ladder.len();
if n < 2 {
return None;
}
let bucket = |s: Strength| ladder.partition_point(|d| *d < s).min(n - 1);
let mut chance = vec![0.0; n * n];
for (hc, hs, _) in &hero {
let hb = bucket(*hs);
for (vc, vs, w) in &villain {
if disjoint(hc, vc) {
chance[hb * n + bucket(*vs)] += *w;
}
}
}
let total: f64 = chance.iter().sum();
if total <= 0.0 {
return None;
}
chance.iter_mut().for_each(|x| *x /= total);
Some((tree_with_chance(n, chance, pot, bet), ladder))
}
/// The believed villain strategy over the river tree, read off the opponent's `Profile`: how this
/// specific opponent plays the two villain nodes, as opposed to the balanced GTO villain the
/// symmetric solve assumes. `kl_best_response` best-responds hero toward this belief, bounded by λ.
///
/// - **`v_bet` `[fold, call]`** (villain facing hero's bet): folds the weakest `fold_to_bet` fraction
/// of the ladder by rank, calls the rest. A calling station (low fold-to-bet) calls almost
/// everything → hero value-bets thin and never bluffs; an over-folder folds more → hero bluffs.
/// - **`v_check` `[check, bet]`** (villain checked to): value-bets the top buckets, bluffs the bottom
/// buckets at a frequency scaled from the read's `aggression` around the GTO bluff ratio
/// `s/(P+s)`. A tight under-bluffer bets a value-heavy range → hero folds its bluff-catchers (the
/// river-overbet-defense fix); a maniac over-bluffs → hero calls down.
///
/// `aggression` is passed in by the caller so it can be STREET-SPECIFIC (the turn gearbox feeds turn
/// aggression, the river gearbox river aggression, each falling back to the pooled read). A single
/// pooled aggression under-sells a turn-barreler's turn bluffing and made the defensive veto fold a
/// good call against aggressive opponents; the per-street value fixes that misfire. `None` → the GTO
/// default. Only the two villain rows matter to `kl_best_response` (it keeps hero's GTO rows); the
/// base is a uniform strategy over the same tree, so the node widths line up.
pub(crate) fn believed_villain(tree: &Tree, n: usize, profile: Option<&Profile>, pot: f64, bet: f64, aggression: Option<f64>) -> Strategy {
let rank = |c: usize| if n <= 1 { 1.0 } else { c as f64 / (n - 1) as f64 };
believed_villain_ranked(tree, profile, pot, bet, aggression, rank)
}
/// `believed_villain` with the position of each bucket in the villain's range given by `rank`.
fn believed_villain_ranked(
tree: &Tree,
profile: Option<&Profile>,
pot: f64,
bet: f64,
aggression: Option<f64>,
rank: impl Fn(usize) -> f64,
) -> Strategy {
let f = profile.and_then(|p| p.fold_to_bet).filter(|x| !x.is_nan()).unwrap_or(DEFAULT_FOLD_TO_BET).clamp(0.0, 1.0);
let a = aggression.filter(|x| !x.is_nan()).unwrap_or(DEFAULT_AGGRESSION).clamp(0.0, 1.0);
let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 };
let bluff_prob = if DEFAULT_AGGRESSION > 0.0 { (gto_bluff * a / DEFAULT_AGGRESSION).clamp(0.0, 1.0) } else { 0.0 };
let base = Strategy::uniform(tree);
let with_call = base
.with_rows(tree, "v_bet", |c| if rank(c) >= f { vec![0.0, 1.0] } else { vec![1.0, 0.0] })
.unwrap_or(base);
with_call
.with_rows(tree, "v_check", |c| {
let r = rank(c);
let bet_p = if r >= VALUE_RANK {
1.0
} else if r <= BLUFF_RANK {
bluff_prob
} else {
0.0
};
vec![1.0 - bet_p, bet_p]
})
.unwrap_or(with_call)
}
/// Shown river bets at which the showdown read and the aggression read weigh the same (the street
/// prior, `exploit::sample::STREET_PRIOR`).
const SHOWN_HALF: f64 = crate::exploit::sample::STREET_PRIOR;
/// The aggression the river belief runs on. Without a showdown read: the river (else pooled)
/// aggression, as before. With one (`Profile::river_bluff_share` over `river_bluff_shown` river bets
/// seen at showdown): the aggression `believed_villain` would need to produce that air share — inverted
/// from its own model (bets = value above `VALUE_RANK` + `bluff_prob` of the range below `BLUFF_RANK`,
/// `bluff_prob = gto_bluff · a / DEFAULT_AGGRESSION`) — blended in by `n / (n + SHOWN_HALF)`. Direct
/// evidence beats the aggression proxy: a player who bets often with value (aggressive, not bluffy) or
/// rarely but always as air.
pub(crate) fn river_bluff_aggression(profile: Option<&Profile>, pot: f64, bet: f64) -> Option<f64> {
let p = profile?;
let a = p.river_aggression.or(p.aggression).filter(|x| !x.is_nan());
let ok = |x: Option<f64>| x.filter(|v| !v.is_nan());
let (Some(share), Some(n)) = (ok(p.river_bluff_share), ok(p.river_bluff_shown).filter(|n| *n > 0.0)) else {
return a;
};
let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 };
if gto_bluff <= 0.0 {
return a;
}
let shown = aggression_for_share(share, gto_bluff);
let base = a.unwrap_or(DEFAULT_AGGRESSION);
let w = n / (n + SHOWN_HALF);
Some(base + w * (shown - base))
}
/// The aggression at which `believed_villain` bets a range whose air share is `share` (bets = value
/// above `VALUE_RANK` + `bluff_prob` of the range below `BLUFF_RANK`, `bluff_prob = gto_bluff · a /
/// DEFAULT_AGGRESSION`), inverted. `gto_bluff = bet/(pot+bet)` > 0.
fn aggression_for_share(share: f64, gto_bluff: f64) -> f64 {
let s = share.clamp(0.0, 0.999);
let bluff_prob = (s * (1.0 - VALUE_RANK) / (BLUFF_RANK * (1.0 - s))).clamp(0.0, 1.0);
(bluff_prob * DEFAULT_AGGRESSION / gto_bluff).clamp(0.0, 1.0)
}
/// Strength percentile of each villain combo within its own range (mid-rank, equal weight per
/// combo, ties share their middle): the `p` of `RangeRead::reweigh`. Unjudgeable combos get ½.
fn range_percentiles(spot: &Spot, combos: &[Vec<Card>]) -> Vec<f64> {
let rules = spot.rules();
let strengths: Vec<Option<Strength>> = combos.iter().map(|c| judge(&rules, c, &spot.board).ok()).collect();
let mut sorted: Vec<Strength> = strengths.iter().flatten().copied().collect();
sorted.sort();
let n = sorted.len().max(1) as f64;
strengths
.iter()
.map(|s| match s {
Some(s) => {
let below = sorted.partition_point(|d| d < s) as f64;
let equal = sorted.partition_point(|d| d <= s) as f64 - below;
(below + equal / 2.0) / n
}
None => 0.5,
})
.collect()
}
/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`) applied to the river gearbox: the
/// game the believed villain plays on (villain range tilted), the believed villain (fold-to-bet and
/// the air share of its betting range for this size, node-locked) and the trust behind it. Hero's
/// reference stays the UNtilted equilibrium, so the KL bound covers the tilt too.
fn read_belief(spot: &Spot, game: &Subgame, villain_combos: &[Vec<Card>], read: &RangeRead, profile: Option<&Profile>, pot: f64, bet: f64) -> Option<(Tree, Strategy)> {
let tree = if read.tilt != 0.0 {
let pct = range_percentiles(spot, villain_combos);
let weights = read.reweigh(&pct.iter().map(|p| (1.0, *p)).collect::<Vec<_>>());
let (tree, ladder) = river_tree_weighted(spot, villain_combos, villain_combos, Some(&weights), pot, bet)?;
if ladder != game.ladder {
return None;
}
tree
} else {
game.tree.clone()
};
let gto_bluff = if pot + bet > 0.0 { bet / (pot + bet) } else { 0.0 };
if gto_bluff <= 0.0 {
return None;
}
let share = read.bluff_share(2, if pot > 0.0 { bet / pot } else { 0.0 });
let believed = Profile { fold_to_bet: read.fold_to_bet(2).or(profile.and_then(|p| p.fold_to_bet)), ..profile.copied().unwrap_or_default() };
let opponent = believed_villain(&tree, game.ladder.len(), Some(&believed), pot, bet, Some(aggression_for_share(share, gto_bluff)));
Some((tree, opponent))
}
/// The KL trust radius from the read's confidence (payoff/chip units). `λ = LAMBDA_POT_SCALE · pot ·
/// (1−c)/c`: no confidence (`None`/0) → `∞` → `kl_best_response` returns exact GTO (the proven
/// unexploitable baseline — it can never again balance against a fish it cannot read); confidence → 1
/// → `λ → 0` → full best response to the believed villain. Monotone decreasing in `c`.
pub(crate) fn lambda_from_confidence(confidence: Option<f64>, pot: f64) -> f64 {
let c = confidence.filter(|x| !x.is_nan()).unwrap_or(0.0).clamp(0.0, 0.999);
if c <= 0.0 {
return f64::INFINITY;
}
LAMBDA_POT_SCALE * pot.max(0.0) * (1.0 - c) / c
}
/// Solve the heads-up river subgame from the engine's belief (`villain_combos`) and return hero's
/// equilibrium mix at the node the spot sits on, or `None` when the v1 slice does not apply (the
/// caller then keeps the heuristic).
pub fn river_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
if spot.to_call == 0.0 {
let bet = bet_to(spot)?;
let game = subgame(spot, villain_combos, villain_combos, spot.pot, bet)?;
let hb = game.bucket(hero_strength);
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
let bet_p = probs.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing: false,
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
bet_to: bet,
reason: format!("river subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
})
} else {
// Facing a bet: the solver's pre-bet pot is `pot - to_call`, the bet is `to_call`.
let p = spot.pot - spot.to_call;
let bet = spot.to_call;
if p <= 0.0 || bet <= 0.0 {
return None;
}
let game = subgame(spot, villain_combos, villain_combos, p, bet)?;
let hb = game.bucket(hero_strength);
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
let call_p = row.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing: true,
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
bet_to: 0.0,
reason: format!("river subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
})
}
}
/// The belief + trust version of `river_plan`: solve the subgame for GTO, then tilt hero's strategy
/// toward best-responding to the **believed** villain (`believed_villain`, from `profile`) inside a
/// KL ball of radius λ (`lambda_from_confidence`, from the read's confidence). Returns hero's tilted
/// mix at the node the spot sits on.
///
/// This is the fix for the −43 "balanced vs a fish" revert: a strong read exploits (value-bets thin,
/// folds under-bluffed overbets), a weak or absent read collapses to the proven-unexploitable GTO
/// mix (λ → ∞). `None` outside the v1 slice, so the caller keeps the heuristic.
pub fn river_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
// Only exploit on a read strong enough to trust; otherwise the heuristic keeps the edge.
// The gearbox exploits a belief about BLUFFING: trust it only as far as the aggression read goes.
// With the read layer on (GEGNER_RANGE=1), its own bluff trust (shown river bets count too).
let read = if range_read::on() { RangeRead::from_profile(profile) } else { None };
let confidence = match &read {
Some(r) => Some(r.trust(true, 2)),
None => profile.and_then(Profile::bluff_read_confidence),
};
if confidence.unwrap_or(0.0) < CONFIDENCE_FLOOR {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let (pot, bet, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
let p = spot.pot - spot.to_call;
if p <= 0.0 || spot.to_call <= 0.0 {
return None;
}
(p, spot.to_call, true)
};
let game = subgame(spot, villain_combos, villain_combos, pot, bet)?;
let n = game.ladder.len();
let lambda = lambda_from_confidence(confidence, pot);
let tilted = match read.as_ref().and_then(|r| read_belief(spot, &game, villain_combos, r, profile, pot, bet)) {
Some((tree, opponent)) => kl_best_response(&tree, &opponent, &game.solved.strategy, 0, lambda),
None => {
let opponent = believed_villain(&game.tree, n, profile, pot, bet, river_bluff_aggression(profile, pot, bet));
kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda)
}
};
let hb = game.bucket(hero_strength);
// Node 0 "hero" [check, bet] when first to act; node 4 "hero_vs_bet" [fold, call] facing a bet.
let node = if facing { 4 } else { 0 };
let row = tilted.row(node, hb).to_vec();
let forward = row.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing,
mix: [row.first().copied().unwrap_or(1.0 - forward), forward],
bet_to: if facing { 0.0 } else { bet },
reason: format!(
"river gearbox: bucket {hb}/{n}{}, λ {:.2}, p(fwd) {forward:.2}",
if facing { " facing bet" } else { "" },
lambda
),
})
}
static DBR: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// River solver as the whole heads-up river player (ladder arm until proven). Default `Off`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RiverPlayer {
Off,
/// Data-biased robust counter-strategy (read confidence per node).
Dbr,
/// The plain equilibrium of the river model (all weights 0, no read): what the model is worth
/// as a player before any exploitation.
Nash,
/// The equilibrium of the full river game (`river_game_decision`).
Game,
/// The full river game with both ranges from the blueprint (plan E2e); only where the spot is
/// a blueprint scenario, else the heuristic plays.
Grund,
}
pub fn set_river_player(mode: RiverPlayer) {
let v = match mode {
RiverPlayer::Off => 0,
RiverPlayer::Dbr => 1,
RiverPlayer::Nash => 2,
RiverPlayer::Game => 3,
RiverPlayer::Grund => 4,
};
DBR.store(v, std::sync::atomic::Ordering::Relaxed);
}
pub fn river_player() -> RiverPlayer {
match DBR.load(std::sync::atomic::Ordering::Relaxed) {
1 => RiverPlayer::Dbr,
2 => RiverPlayer::Nash,
3 => RiverPlayer::Game,
4 => RiverPlayer::Grund,
_ => RiverPlayer::Off,
}
}
/// Switch the data-biased river counter-strategy on or off. Default off.
pub fn set_dbr(on: bool) {
set_river_player(if on { RiverPlayer::Dbr } else { RiverPlayer::Off });
}
pub fn dbr_on() -> bool {
river_player() != RiverPlayer::Off
}
/// The believed villain with its thresholds on the COMBO MASS of its range, not on the rank of the
/// deduplicated strength ladder: `q[b]` is the mid-quantile of bucket `b` in the villain's marginal of
/// the deal table. On a paired board a few strength levels carry most combos; folding "the weakest
/// 45 %" must mean 45 % of the hands, not of the levels (BEFUND-river-gearbox-belief-trust, defect a).
fn believed_villain_by_mass(tree: &Tree, profile: Option<&Profile>, pot: f64, bet: f64, aggression: Option<f64>) -> Strategy {
let n = tree.classes;
let mut mass = vec![0.0; n];
for h in 0..n {
for v in 0..n {
mass[v] += tree.chance.get(h * n + v).copied().unwrap_or(0.0);
}
}
let total: f64 = mass.iter().sum::<f64>().max(1e-12);
let mut below = 0.0;
let q: Vec<f64> = mass
.iter()
.map(|m| {
let mid = (below + m / 2.0) / total;
below += m;
mid
})
.collect();
believed_villain_ranked(tree, profile, pot, bet, aggression, |c| q[c])
}
/// The data-biased robust river counter-strategy (`cfr::dbr`): the villain plays the believed model
/// (`believed_villain_by_mass`) with the weight its data earns at each node - the fold-to-bet read's
/// confidence where it faces hero's bet, the bluff read's where it was checked to - and best-responds
/// wherever the data is thin. Hero's average strategy exploits the read only as far as the data goes,
/// with a FREE support (thin value against a station, which the KL tilt around GTO could not reach).
/// Below `CONFIDENCE_FLOOR` on both nodes the heuristic keeps the spot (`None`).
pub fn river_dbr_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>) -> Option<RiverPlan> {
let p = profile?;
let ok = |x: Option<f64>| x.filter(|c| !c.is_nan()).unwrap_or(0.0).clamp(0.0, 1.0);
let (w_call, w_bet) = (ok(p.confidence), ok(p.bluff_read_confidence()));
if w_call.max(w_bet) < CONFIDENCE_FLOOR {
return None;
}
river_weighted_plan(spot, villain_combos, Some(p), w_call, w_bet)
}
/// The river model's own equilibrium as hero's plan (no read): the reference for what the model is
/// worth as a player.
pub fn river_nash_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<RiverPlan> {
river_weighted_plan(spot, villain_combos, None, 0.0, 0.0)
}
fn river_weighted_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>, w_call: f64, w_bet: f64) -> Option<RiverPlan> {
if spot.street != Street::River || spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let hero_strength = judge(&spot.rules(), &spot.hero_cards, &spot.board).ok()?;
let (pot, bet, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
let pre = spot.pot - spot.to_call;
if pre <= 0.0 || spot.to_call <= 0.0 {
return None;
}
(pre, spot.to_call, true)
};
let (tree, ladder) = river_tree(spot, villain_combos, villain_combos, pot, bet)?;
let model = believed_villain_by_mass(&tree, profile, pot, bet, river_bluff_aggression(profile, pot, bet));
let weight: Vec<f64> = tree
.nodes
.iter()
.map(|node| match node {
Node::Decision { player: 1, name, .. } if *name == "v_bet" => w_call,
Node::Decision { player: 1, name, .. } if *name == "v_check" => w_bet,
_ => 0.0,
})
.collect();
let counter = solve_restricted(&tree, &Restriction { player: 1, model: &model, weight }, DBR_ITERS);
let hb = ladder.partition_point(|d| *d < hero_strength).min(ladder.len() - 1);
let node = if facing { 4 } else { 0 };
let row = counter.row(node, hb).to_vec();
let forward = row.get(1).copied().unwrap_or(0.0);
Some(RiverPlan {
facing,
mix: [row.first().copied().unwrap_or(1.0 - forward), forward],
bet_to: if facing { 0.0 } else { bet },
reason: format!(
"river DBR: bucket {hb}/{}{}, w call {w_call:.2} bet {w_bet:.2}, p(fwd) {forward:.2}",
ladder.len(),
if facing { " facing bet" } else { "" }
),
})
}
/// CFR+ iterations of the restricted river solve (same tiny tree as `ITERS`).
const DBR_ITERS: u32 = 4_000;
/// The live DBR decision for a heads-up river spot (villain range from the engine's range model), or
/// `None` when it does not apply - the caller keeps the heuristic.
pub fn dbr_decision(spot: &Spot) -> Option<Decision> {
if !dbr_on() || spot.street != Street::River || spot.live_villains().count() != 1 {
return None;
}
if matches!(river_player(), RiverPlayer::Game | RiverPlayer::Grund) {
return river_game_decision(spot);
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
let plan = match river_player() {
RiverPlayer::Nash => river_nash_plan(spot, &list)?,
_ => river_dbr_plan(spot, &list, villain.profile.as_ref())?,
};
Some(realize(spot, &plan))
}
/// Messschalter (einmal gelesen) `VETO_AB=<Topfanteil>`: the defensive veto stands down against a river
/// bet smaller than this share of the pot before it (`to_call / (pot - to_call)`). The veto's proven
/// edge is the under-bluffed river OVERBET (nemesis-3); on real NL2 spots (hhDealer 19.10.-16.11.,
/// `messung/grosse_calls/`) it folds top pair, overpairs and two pair against small river bets in big
/// pots that the population calls at a profit (often at "equity 0.45-0.72, heuristic would call").
/// Unset: off, bit-identical.
fn veto_ab() -> Option<f64> {
use std::sync::OnceLock;
static V: OnceLock<Option<f64>> = OnceLock::new();
*V.get_or_init(|| std::env::var("VETO_AB").ok()?.trim().parse::<f64>().ok().filter(|x| x.is_finite() && *x > 0.0))
}
/// Below this believed call frequency the defensive veto folds: when the KL-bounded best response to
/// the believed villain calls hero's bucket less than half the time, the believed bet is value-heavy
/// enough that the heuristic's call is −EV. A full 0.5 keeps the veto to clear under-bluff reads.
const VETO_CALL_FLOOR: f64 = 0.5;
/// Defensive river veto: on a confident read that the villain UNDER-bluffs its bet, fold a heuristic
/// CALL that the belief+trust gearbox would not make. This is the gearbox's one proven edge — the
/// single-street heuristic over-calls under-bluffed river overbets (nemesis-3) because its range model
/// carries the GTO bluff share a tight bettor does not have. Everything else is left to the heuristic:
/// the veto only ever turns a call into a fold facing a bet, never touches a bet/check/raise, and
/// stands down on a thin read (confidence floor) or off the heads-up river slice.
///
/// Safe by construction against the −43/−48 "balanced vs a fish" regression: it cannot change hero's
/// OFFENSE, only decline a call the read prices as losing. The caller gates it to cash (no ICM premium).
pub fn fold_veto(spot: &Spot, base: Decision) -> Decision {
if base.choice != Choice::Call {
return base;
}
if veto_ab().is_some_and(|ab| spot.to_call < ab * (spot.pot - spot.to_call)) {
return base;
}
// The veto answers a read that the bettor UNDER-bluffs. Without a postflop aggression read there
// is no bluff evidence at all (the belief would fall back to the balanced default and fold the
// bottom of a GTO range against a player nobody measured): stand down. Replay 10.11., hand
// 174898200346: vpip-only read, river top pair vetoed into a fold against a pair of tens.
let bluff_read = spot
.live_villains()
.next()
.and_then(|v| v.profile.as_ref())
.and_then(|p| p.river_aggression.or(p.aggression))
.is_some_and(|a| !a.is_nan());
if !bluff_read {
return base;
}
let Some(plan) = river_exploit_mix(spot) else {
return base;
};
if !plan.facing || plan.mix[1] >= VETO_CALL_FLOOR {
return base;
}
Decision {
choice: Choice::Fold,
reason: format!("defensive veto: {} (heuristic would call)", plan.reason),
..base
}
}
/// Realise a `RiverPlan` into a concrete decision, mixing from the spot seed (deterministic per spot,
/// correct frequency across the range of deals). Confidence rises as the mix leaves 50/50.
pub fn realize(spot: &Spot, plan: &RiverPlan) -> Decision {
let (draw, _) = Rng::seeded(spot.seed).unit();
let aggressive = draw < plan.forward();
let choice = match (plan.facing, aggressive) {
(false, true) => Choice::Raise { to: plan.bet_to },
(false, false) => Choice::Check,
(true, true) => Choice::Call,
(true, false) => Choice::Fold,
};
let confidence = 0.5 + (plan.forward() - 0.5).abs();
Decision::new(choice, confidence, plan.reason.clone())
}
/// Build the villain belief combos the way `decide::postflop` does (gated reads, enumerated range)
/// and return hero's river mix — the measurement entry point for `sim::exploit_river`, faithful to
/// what the live engine would play. `None` when the slice does not apply.
pub fn river_mix(spot: &Spot) -> Option<RiverPlan> {
if spot.street != Street::River {
return None;
}
let gated = crate::engine::read_gate::gate_reads(spot);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
river_plan(spot, &list)
}
/// Live entry for the belief + trust gearbox: source the villain belief range from the **raw**
/// (ungated) read and hand the solver the opponent's real `Profile` (tendencies + confidence). The
/// gate that blinds the heuristic is not applied here — the KL trust radius (λ from confidence) is
/// the gearbox's own safety, so it reads the true opponent and the floor keeps it from acting on a
/// thin read. `None` outside the v1 slice or below the confidence floor, so the caller keeps the
/// heuristic.
pub fn river_exploit_mix(spot: &Spot) -> Option<RiverPlan> {
let (list, profile) = belief_combos(spot)?;
river_exploit_plan(spot, &list, profile.as_ref())
}
/// The villain's believed river range from the raw (ungated) read, and his profile; heads-up river only.
pub(crate) fn belief_combos(spot: &Spot) -> Option<(Vec<Vec<Card>>, Option<Profile>)> {
if spot.street != Street::River {
return None;
}
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let profile = villain.profile;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
Some((list, profile))
}
// --- The full river game (A.1): position, several sizes, raises, hero's own range. ---
/// CFR+ iterations for the full river game (tens of nodes, at most `GAME_BUCKETS` classes).
const GAME_ITERS: u32 = 2_000;
/// Most strength classes of the full river game; finer ladders are merged by combo mass.
const GAME_BUCKETS: usize = 40;
/// The river line so far for hero and `villain`: who acted first (0 = hero), the forced actions and
/// both street contributions. Falls back to "villain bet `to_call`" / "hero first" without a history.
pub(crate) fn river_line(spot: &Spot, villain: &Villain) -> (usize, Vec<Act>, [f64; 2]) {
let mut first = None;
let mut acts = Vec::new();
let mut c = [0.0f64, 0.0];
let mut aggressed = false;
for r in spot.history.iter().filter(|r| r.street == Street::River) {
let who = if r.seat == spot.hero_seat {
0
} else if r.seat == villain.seat {
1
} else {
continue;
};
first.get_or_insert(who);
let amount = r.amount.unwrap_or(c[who]);
match r.action {
SeenAction::Check => acts.push(Act::Check),
SeenAction::Bet | SeenAction::Raise | SeenAction::AllIn if amount > c[1 - who] => {
acts.push(if aggressed { Act::Raise(amount) } else { Act::Bet(amount) });
aggressed = true;
c[who] = amount;
}
SeenAction::Call | SeenAction::AllIn => {
acts.push(Act::Call);
c[who] = c[1 - who];
}
_ => {}
}
}
let consistent = (c[1] - c[0] - spot.to_call).abs() < 1e-6 * spot.pot.max(1.0);
match first {
Some(f) if consistent => (f, acts, c),
_ if spot.to_call > 0.0 => (1, vec![Act::Bet(spot.to_call)], [0.0, spot.to_call]),
_ => (0, Vec::new(), [0.0, 0.0]),
}
}
/// Strength classes for both lists: the joint deal table (card removal inside) and, per ladder level,
/// its class. Ladders finer than `GAME_BUCKETS` are merged into classes of equal combo mass.
pub(crate) fn deal_classes(spot: &Spot, hero_combos: &[(Vec<Card>, f64)], villain_combos: &[(Vec<Card>, f64)]) -> Option<(usize, Vec<f64>, Vec<Strength>, Vec<usize>)> {
let rules = spot.rules();
let judged = |combos: &[(Vec<Card>, f64)]| -> Vec<(Vec<Card>, Strength, f64)> {
combos.iter().filter_map(|(c, w)| judge(&rules, c, &spot.board).ok().map(|s| (c.clone(), s, *w))).collect()
};
let hero = judged(hero_combos);
let villain = judged(villain_combos);
if hero.is_empty() || villain.is_empty() {
return None;
}
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, s, _)| *s).collect();
ladder.sort();
ladder.dedup();
let levels = ladder.len();
if levels < 2 {
return None;
}
let level = |s: Strength| ladder.partition_point(|d| *d < s).min(levels - 1);
// Class of each level: equal shares of the combined combo mass.
let mut mass = vec![0.0; levels];
for (_, s, w) in hero.iter().chain(&villain) {
mass[level(*s)] += w;
}
let total_mass: f64 = mass.iter().sum();
let n = levels.min(GAME_BUCKETS);
let mut class_of = vec![0usize; levels];
let mut below = 0.0;
for (l, m) in mass.iter().enumerate() {
let mid = (below + m / 2.0) / total_mass;
below += m;
class_of[l] = if levels <= GAME_BUCKETS { l } else { ((mid * n as f64) as usize).min(n - 1) };
}
let mut chance = vec![0.0; n * n];
for (hc, hs, hw) in &hero {
let hb = class_of[level(*hs)];
for (vc, vs, vw) in &villain {
if disjoint(hc, vc) {
chance[hb * n + class_of[level(*vs)]] += hw * vw;
}
}
}
let total: f64 = chance.iter().sum();
if total <= 0.0 {
return None;
}
chance.iter_mut().for_each(|x| *x /= total);
Some((n, chance, ladder, class_of))
}
/// The legal choice nearest to a game action.
pub(crate) fn legal_choice(spot: &Spot, act: Act) -> Choice {
let passive = if spot.to_call > 0.0 { Choice::Call } else { Choice::Check };
match act {
Act::Fold if spot.to_call > 0.0 => Choice::Fold,
Act::Fold | Act::Check | Act::Call => passive,
// The candidates are pot fractions; the all-in (`max_raise_to`) joins them, else a game
// jam came out as the nearest fraction (93.7 → 27.1 on a 15-bb river).
Act::Bet(to) | Act::Raise(to) => candidates(spot)
.into_iter()
.chain(spot.max_raise_to)
.filter(|t| *t > 0.0)
.min_by(|a, b| (a - to).abs().total_cmp(&(b - to).abs()))
.map_or(passive, |t| Choice::Raise { to: t }),
}
}
/// The equilibrium of the full river game at hero's actual node, for hero's actual hand. Hero's range
/// comes from hero's own line (the same range model the villain gets, without a read); the villain's
/// from the (gated) range model. `None` outside heads-up river or when the line left the tree.
pub fn river_game_decision(spot: &Spot) -> Option<Decision> {
if spot.street != Street::River {
return None;
}
let gated = crate::engine::read_gate::gate_reads(spot);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let list = |who: &Villain| {
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, who),
rules,
spot.variant,
&spot.board,
);
crate::engine::range_combos::combos(&rules, &filter, &spot.board)
};
let (hero_list, villain_list) = if river_player() == RiverPlayer::Grund {
crate::blueprint::ranges::gewichtete_listen(spot)?
} else {
let me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None };
let eins = |l: Vec<Vec<Card>>| l.into_iter().map(|c| (c, 1.0)).collect::<Vec<_>>();
(eins(list(&me)?), eins(list(villain)?))
};
let (n, chance, ladder, class_of) = deal_classes(spot, &hero_list, &villain_list)?;
let (first, forced, c) = river_line(spot, villain);
let pot = spot.pot - c[0] - c[1];
if pot <= 0.0 {
return None;
}
let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]);
let game = build(n, chance, &Bets::standard(pot, stack, first), &forced);
let at = game.at?;
if !matches!(game.tree.nodes.get(at), Some(Node::Decision { player: 0, .. })) {
return None;
}
let solved = solve(&game.tree, GAME_ITERS, Rng::seeded(spot.seed));
let strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let class = class_of[ladder.partition_point(|d| *d < strength).min(ladder.len() - 1)];
let row = solved.strategy.row(at, class).to_vec();
let (draw, _) = Rng::seeded(spot.seed).unit();
let mut acc = 0.0;
let mut pick = row.len().saturating_sub(1);
for (k, p) in row.iter().enumerate() {
acc += p;
if draw < acc {
pick = k;
break;
}
}
let act = *game.acts[at].get(pick)?;
let choice = legal_choice(spot, act);
let p = row.get(pick).copied().unwrap_or(0.0);
Some(Decision::new(
choice,
p.clamp(0.0, 1.0),
format!("river game: class {class}/{n}, {} nodes, {act:?} p {p:.2}", game.tree.nodes.len()),
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::game::{ActionKind, Villain};
use crate::variant::Variant;
/// A heads-up river spot where hero is first to act into `pot` with check or a two-thirds bet.
fn river_to_act(board: &[Card], hero: &str, pot: f64) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::River,
pot,
to_call: 0.0,
hero_stack: pot * 4.0,
min_raise_to: Some(pot * 0.66),
max_raise_to: Some(pot * 4.0),
legal: vec![ActionKind::Check, ActionKind::Raise],
allowed_sizes: Some(vec![pot * 0.66]),
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile: None }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// A river spot the slice accepts (heads-up, hero to act) returns a mix, and a strong made hand
/// leans to betting. Guards the wiring, not the exact frequency.
#[test]
fn a_made_hand_to_act_gets_a_river_mix_that_leans_to_bet() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain: Vec<Vec<Card>> = ["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect();
let spot = river_to_act(&board, "Ac As", 6.0); // overpair-strength: top two on this board
let plan = river_plan(&spot, &villain).expect("heads-up river to-act is in slice");
assert!(!plan.facing);
assert!(plan.bet_to > 0.0);
assert!(
plan.forward() > 0.5,
"a strong made hand should lean to betting, got p(bet) {:.2}",
plan.forward()
);
}
// --- belief + trust gearbox ---
use crate::cfr::river::tree_with_chance;
fn prof(fold_to_bet: f64, aggression: f64, confidence: f64) -> Profile {
Profile {
fold_to_bet: Some(fold_to_bet),
aggression: Some(aggression),
confidence: Some(confidence),
..Default::default()
}
}
fn uniform_tree(n: usize, pot: f64, bet: f64) -> Tree {
tree_with_chance(n, vec![1.0 / (n * n) as f64; n * n], pot, bet)
}
/// λ is ∞ without a read (⇒ kl_br returns exact GTO), finite with one, and falls as the read
/// strengthens; at confidence 0.5 it is exactly `LAMBDA_POT_SCALE · pot`.
#[test]
fn lambda_falls_as_confidence_rises_and_is_infinite_without_a_read() {
assert!(lambda_from_confidence(None, 6.0).is_infinite());
assert!(lambda_from_confidence(Some(0.0), 6.0).is_infinite());
let mid = lambda_from_confidence(Some(0.5), 6.0);
let high = lambda_from_confidence(Some(0.9), 6.0);
assert!(mid.is_finite() && high.is_finite());
assert!(high < mid, "λ must fall as confidence rises: {high} !< {mid}");
assert!((mid - LAMBDA_POT_SCALE * 6.0).abs() < 1e-9, "c=0.5 ⇒ λ = pot·scale");
}
/// The believed villain facing a bet calls a wider slice of the ladder when it is a low-fold
/// station than when it is a high-fold over-folder.
#[test]
fn a_believed_station_calls_wider_than_a_believed_overfolder() {
let n = 6;
let tree = uniform_tree(n, 2.0, 1.0);
let station = believed_villain(&tree, n, Some(&prof(0.10, 0.35, 0.8)), 2.0, 1.0, Some(0.35));
let overfolder = believed_villain(&tree, n, Some(&prof(0.80, 0.35, 0.8)), 2.0, 1.0, Some(0.35));
// node 2 "v_bet", action 1 = call.
let calls = |s: &Strategy| (0..n).filter(|&c| s.probability(2, c, 1) > 0.5).count();
assert!(
calls(&station) > calls(&overfolder),
"station calls wider: {} vs {}",
calls(&station),
calls(&overfolder)
);
}
/// The believed villain bluffs its air (bottom bucket) more when checked to the more aggressive
/// the read — a passive under-bluffer bets a value-heavy range.
#[test]
fn a_believed_aggressive_villain_bluffs_more_when_checked_to() {
let n = 10;
let tree = uniform_tree(n, 2.0, 1.0);
let passive = believed_villain(&tree, n, Some(&prof(0.45, 0.10, 0.8)), 2.0, 1.0, Some(0.10));
let maniac = believed_villain(&tree, n, Some(&prof(0.45, 0.80, 0.8)), 2.0, 1.0, Some(0.80));
// node 1 "v_check", bucket 0 = air, action 1 = bet.
assert!(
maniac.probability(1, 0, 1) > passive.probability(1, 0, 1),
"a maniac bluffs its air more: {} !> {}",
maniac.probability(1, 0, 1),
passive.probability(1, 0, 1)
);
}
fn river_to_act_vs(board: &[Card], hero: &str, pot: f64, profile: Option<Profile>) -> Spot {
Spot {
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
..river_to_act(board, hero, pot)
}
}
fn sample_villain() -> Vec<Vec<Card>> {
["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect()
}
/// Below the confidence floor the gearbox stands down (`None`) so the heuristic keeps the edge.
#[test]
fn the_gearbox_stands_down_below_the_confidence_floor() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
let thin = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.10)));
assert!(
river_exploit_plan(&thin, &villain, thin.live_villains().next().unwrap().profile.as_ref()).is_none(),
"confidence 0.10 < floor ⇒ no plan"
);
let confident = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.80)));
assert!(
river_exploit_plan(&confident, &villain, confident.live_villains().next().unwrap().profile.as_ref()).is_some(),
"confidence 0.80 ≥ floor ⇒ a plan"
);
}
/// A confident calling-station read makes hero value-bet a strong made hand (exploit, not balance).
#[test]
fn a_confident_station_read_value_bets_a_strong_hand() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
let spot = river_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.08, 0.15, 0.85)));
let plan = river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up river to-act is in slice");
assert!(!plan.facing);
assert!(plan.forward() > 0.5, "value-bet a strong hand into a station, got p(bet) {:.2}", plan.forward());
}
/// A heads-up river spot where hero faces a `bet` into the pre-bet pot `pot`, with fold or call.
fn river_vs_bet(board: &[Card], hero: &str, pot: f64, bet: f64, profile: Option<Profile>) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::River,
pot: pot + bet,
to_call: bet,
hero_stack: pot * 4.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![ActionKind::Fold, ActionKind::Call],
allowed_sizes: None,
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// The core nemesis-3 mechanism the defensive veto rides on: a confident read that the villain
/// UNDER-bluffs its river bet (tight, passive) best-responds hero's bluff-catcher toward a FOLD
/// (believed call frequency below the veto floor), where the single-street heuristic would call.
#[test]
fn a_confident_underbluff_read_folds_a_bluff_catcher_facing_a_bet() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
// Jc Js: a genuine bluff-catcher on this A-K-high board — it loses to the villain's value
// (AJ=aces, KQ=kings, QQ) and beats only the bottom (99, 88, 66, 54). Vs a believed
// UNDER-bluffer the bet is value-heavy, so calling is −EV and the gearbox folds.
let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let plan = river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up river vs-bet is in slice");
assert!(plan.facing, "facing a bet");
assert!(
plan.mix[1] < VETO_CALL_FLOOR,
"a bluff-catcher vs a believed under-bluffer should fold (p(call) {:.2} < {VETO_CALL_FLOOR})",
plan.mix[1]
);
}
/// The read layer (`GEGNER_RANGE`): a looser range (tilt < 0) and more believed air both make
/// hero call a bluff-catcher more; the tilt keeps the ladder, and a population read with no
/// shown bets leaves the believed fold-to-bet as read.
#[test]
fn the_read_layer_tilts_the_range_and_locks_the_believed_bettor() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let villain = sample_villain();
let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, None);
let game = subgame(&spot, &villain, &villain, 6.0, 6.0).unwrap();
let hb = game.bucket(judge(&spot.rules(), &spot.hero_cards, &board).unwrap());
let call = |p: Profile| {
let r = RangeRead::from_profile(Some(&p)).unwrap();
let (tree, opp) = read_belief(&spot, &game, &villain, &r, Some(&p), 6.0, 6.0).unwrap();
let lambda = lambda_from_confidence(Some(r.trust(true, 2)), 6.0);
kl_best_response(&tree, &opp, &game.solved.strategy, 0, lambda).row(4, hb)[1]
};
let base = Profile { vpip: Some(0.28), ..prof(0.45, 0.35, 0.85) };
let loose = call(Profile { vpip: Some(0.84), ..base });
let tight = call(Profile { vpip: Some(0.10), ..base });
assert!(loose > tight, "a looser range is called more: {loose:.3} vs {tight:.3}");
let bluffer = call(Profile { river_aggression: Some(0.9), ..base });
let honest = call(Profile { river_aggression: Some(0.03), ..base });
assert!(bluffer > honest, "more believed air is called more: {bluffer:.3} vs {honest:.3}");
let pct = range_percentiles(&spot, &villain);
assert!(pct.iter().all(|p| (0.0..=1.0).contains(p)));
assert!(pct[0] > pct[5], "AJ (aces) above 54 (nothing)");
}
/// The veto never touches hero's offense: a base that is not a call is returned unchanged even
/// though a plan exists (guards against the −43/−48 full-replacement regression returning).
#[test]
fn the_veto_leaves_a_non_call_decision_untouched() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let spot = river_vs_bet(&board, "Qc Qd", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let check = Decision::new(Choice::Check, 0.7, "heuristic check");
assert_eq!(fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed");
}
/// The showdown read moves the river belief toward what was SHOWN: all-air river bets raise the
/// believed aggression, all-value ones lower it, a thin sample barely moves it, none leaves it.
#[test]
fn shown_river_bets_move_the_bluff_belief() {
let base = prof(0.4, 0.35, 0.9);
let (pot, bet) = (10.0, 7.5);
assert_eq!(river_bluff_aggression(Some(&base), pot, bet), Some(0.35));
let shown = |share: f64, n: f64| Profile { river_bluff_share: Some(share), river_bluff_shown: Some(n), ..base };
let honest = river_bluff_aggression(Some(&shown(0.0, 60.0)), pot, bet).unwrap();
let bluffer = river_bluff_aggression(Some(&shown(0.45, 60.0)), pot, bet).unwrap();
let thin = river_bluff_aggression(Some(&shown(0.0, 1.0)), pot, bet).unwrap();
assert!(honest < 0.1, "never bluffed at showdown: {honest}");
assert!(bluffer > 0.6, "mostly air at showdown: {bluffer}");
assert!(thin > 0.3 && thin < 0.35, "one showdown barely moves it: {thin}");
// The air share the model implies at the balanced aggression maps back onto it (round trip).
let gto_bluff = bet / (pot + bet);
let b = gto_bluff; // bluff_prob at a = DEFAULT_AGGRESSION
let s = BLUFF_RANK * b / (BLUFF_RANK * b + (1.0 - VALUE_RANK));
let back = river_bluff_aggression(Some(&shown(s, 1e9)), pot, bet).unwrap();
assert!((back - DEFAULT_AGGRESSION).abs() < 1e-6, "{back}");
}
/// No aggression read = no under-bluff evidence: the veto stands down even on a confident read
/// of other stats (replay 10.11., vpip-only HUD, river top pair vetoed into a fold).
#[test]
fn the_veto_needs_an_aggression_read() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let no_aggr = Profile { aggression: None, vpip: Some(0.6), ..prof(0.30, 0.06, 0.85) };
let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(no_aggr));
let call = Decision::new(Choice::Call, 0.6, "heuristic call");
assert_eq!(fold_veto(&spot, call.clone()), call, "no bluff read, no veto");
// A strong HUD read (confidence 0.85) whose aggression rests on two seen moves: the gearbox
// trusts the bluff read only as far as the aggression goes -> below the floor, no plan.
let thin = Profile { aggression_confidence: Some(2.0 / 32.0), ..prof(0.30, 0.06, 0.85) };
let spot = river_vs_bet(&board, "Jc Js", 6.0, 6.0, Some(thin));
assert_eq!(fold_veto(&spot, call.clone()), call, "thin aggression read, no veto");
let villain = sample_villain();
assert!(river_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref()).is_none());
}
// --- data-biased robust counter-strategy (cfr::dbr) ---
fn station_range() -> Vec<Vec<Card>> {
["Ad Jc", "Kc Qc", "Kh Jh", "9d 8d", "9s Ts", "7d 6d", "7h 5h", "Qs Js", "Td Jd", "5c 4c", "6s 5s", "3c 3d", "4h 4d", "8h 8s"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect()
}
/// A confident station read: hero's middle pair, which the equilibrium mostly checks, turns into a
/// thin value bet - the free support the KL tilt could not reach.
#[test]
fn dbr_value_bets_a_middle_pair_into_a_confident_station() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let mut spot = river_to_act(&board, "9c Tc", 6.0);
let station = prof(0.05, 0.05, 0.9);
spot.villains[0].profile = Some(station.clone());
let range = station_range();
let nash = river_plan(&spot, &range).expect("in slice");
let dbr = river_dbr_plan(&spot, &range, Some(&station)).expect("confident read is in slice");
eprintln!("nash p(bet) {:.2}, dbr {}", nash.forward(), dbr.reason);
assert!(dbr.forward() > 0.8, "{}", dbr.reason);
assert!(dbr.forward() > nash.forward() + 0.2, "nash {:.2} {}", nash.forward(), dbr.reason);
}
/// Below the confidence floor on both nodes DBR stays out (the heuristic keeps the spot).
#[test]
fn dbr_stays_out_on_a_thin_read() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let spot = river_to_act(&board, "9c Tc", 6.0);
let thin = prof(0.05, 0.05, 0.1);
assert!(river_dbr_plan(&spot, &station_range(), Some(&thin)).is_none());
assert!(river_dbr_plan(&spot, &station_range(), None).is_none());
}
#[test]
fn the_full_river_game_decides_a_heads_up_river() {
let board = Card::parse_list("Ah Kd 7c 2s 9h").unwrap();
let spot = river_to_act(&board, "Ac As", 6.0);
let t = std::time::Instant::now();
let d = river_game_decision(&spot).expect("heads-up river is in the game");
eprintln!("{:?} {} in {:?}", d.choice, d.reason, t.elapsed());
assert!(matches!(d.choice, Choice::Raise { .. }), "top set bets: {}", d.reason);
}
}