From 38de1e9c9f901e7630fa06a2913c2e08a500bd63 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 21:29:07 +0100 Subject: [PATCH 1/3] STAND 11: ES Solver ueberall, Abdeckung A/B, Read-Haken, Tor A laeuft Co-Authored-By: Claude Opus 5.5 --- docs/notizen/STAND-weltklasse.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/notizen/STAND-weltklasse.md b/docs/notizen/STAND-weltklasse.md index 11e28e4f..aeb72aa9 100644 --- a/docs/notizen/STAND-weltklasse.md +++ b/docs/notizen/STAND-weltklasse.md @@ -278,3 +278,16 @@ das E1-Tor erneut. | Regression durch den Handkarten-Fix (Lauf 4) | Mit dem Gedächtnis kamen alte, schon beantwortete Züge wieder heraus. Ihr Tischzustand lag vor dem Fenster, die Übersetzung baute sie als „PREFLOP, Platz/Knopf unbekannt“, der Läufer hielt sie für neu: **308 Enthaltungen, 233 geklickt** (fold/check ins Leere). Schaden erkennbar: 1 Hand, −2,5 BB. Behoben: Karten nur aus dem Gedächtnis zählen nur für einen Zug, nach dem am Tisch noch nicht gehandelt wurde. Nachspiel main.1 (gleitendes 4-MB-Fenster): alt 218 Züge / 0 Enthaltungen, neu 219 / 1 (ein River-Zug zurück). Spec 7/7. Greift ab dem nächsten Läuferstart | L2 | | Engine-Röntgen (Transparenz je Lauf) | `lesen/roentgen.py` (CLI, `--json`), Cockpit-Seite `/roentgen` (sicht-Server, Nachspiel im Hintergrund, Cache je Lauf), Spec `tests/roentgen_spec.py` 11/11. Lauf 4 (pid 43432, 18:57–20:14, 1192 Hände, −12,9 bb/100 [−76, +51]): **Gegner-Read ändert 7 von 2060 Entscheidungen (0,3 %)**, Preflop-CFR 60,9 % der Preflop-Kern-Züge, E3 7,2 % der Turn-Züge, Turn-/River-Veto 0, MDF-Boden 0, Flop/River 100 % Heuristik; Read-Stichprobe Median 23 Hände, kein Gegner ≥ 100; Nachspiel = live 99,9 % | Transparenz, D2 | | Strang E | gestoppt am Tor (Abschnitt 9); Plan nachgezogen, offene Owner-Entscheidungen O1–O4 in `PLAN-weltklasse.md` 4a | Tor E2 | + +## 11. Nachtrag 14.11. abends: ES Solver überall (Stufen A/B/C) + +Ein CFR+-Teilspiel-Solver über echte Kombos (`cfr::turn_river_game`) entscheidet jede Heads-up-Postflop-Straße; Multiway bleibt Heuristik. Ranges: Grundstrategie, wo sie den Spot erkennt, sonst das Range-Modell der Aktionsgeschichte. Schalter `SOLVER_RIVER`, `SOLVER_TURN`, `SOLVER_FLOP` (aus), Branch `claude/solver-ueberall-44ecc1`. Unter `MIN_ITERS` im Zeitbudget entscheidet die Heuristik. + +| Schritt | Ergebnis | Plan | +|---|---|---| +| A River: Abdeckung echte Anfragen | 366 eindeutige River-Anfragen aus `betrieb/scratch/shadow*.jsonl`: **HU 322/322 = 100 % Solver**, p50 740 ms, p99 1333 ms, max 1772 ms; 2/3 Gegner (44) Heuristik | ES-A | +| B Turn: Abdeckung (vor Zeitbudget) | 575 Anfragen, HU 478: **427 Solver (89,3 %)**, 43 E3, 8 Heuristik; p50 2045, p99 3781, max 4345 ms → zu langsam, Turn bekam ein Wandzeitbudget 1700 ms je Entscheidung (inkl. Rückfall-Solve), Flop-Rückfall nur im Restbudget. Neumessung läuft | ES-B | +| C Flop | gebaut (120 Kombos, 8 Turnkarten, exakte River-Equity, ~1 s); Abdeckung läuft | ES-C | +| Read-Haken (Orchestrator-Entscheid) | `river_spieler::solver_lists` kippt die Gegnerrange (`RangeRead::reweigh`, nur bei confidence > 0); `lock_villain`/`TrSolver::lock` sperrt am River die geglaubte Gegnerstrategie (fold_to_bet, bluff_share) mit Gewicht trust. Ohne Read / confidence 0 bitgleich (Test). Schalter `GEGNER_RANGE=1`. KL-Schranke (c) offen | ES, D1c | +| A LBR gepaart (Tor) | läuft seit 21:14: basis vs `SOLVER_RIVER=1`, je 2000 Hände, je 4 Threads Idle (`messung_solver/`, ~7 h). Pilot 8 Hände: identisch +187,5 ±106,1 | ES-A | +| Leiter A/AB/ABC | eingereiht in `messung_engine/warteschlange.txt` (solver-leiter-*, 21 Zeilen inkl. micro-passiv, 500/1000/2) | ES | From ca30bc621338864decdd5be96b5ccd84a9bcb49d Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 21:16:52 +0100 Subject: [PATCH 2/3] D1c: RangeRead::believed_row fuer das Knoten-Festlegen im TrSolver (restricted Nash response) Co-Authored-By: Claude Opus 5.5 --- src/exploit/range_read.rs | 84 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/src/exploit/range_read.rs b/src/exploit/range_read.rs index 86b749f3..12a88595 100644 --- a/src/exploit/range_read.rs +++ b/src/exploit/range_read.rs @@ -23,6 +23,7 @@ //! Live only behind the switch `GEGNER_RANGE=1` (default off). use super::posterior::DEFAULT_AGGRESSION; +use crate::cfr::river_game::Act; use super::profile::Profile; use super::sample::{PRIOR, STREET_PRIOR}; @@ -32,6 +33,13 @@ use super::sample::{PRIOR, STREET_PRIOR}; pub const TILT_SCALE: f64 = 1.0; /// The tilt never exceeds this either way (a 90 % vpip player is not infinitely weak). pub const TILT_MAX: f64 = 2.0; +/// Range percentile at/above which the believed villain value-bets when it may bet (as the river +/// gearbox's `VALUE_RANK`). +pub const VALUE_PCT: f64 = 0.60; +/// Range percentile at/below which the believed villain may bluff (as `BLUFF_RANK`). +pub const BLUFF_PCT: f64 = 0.30; +/// The bet size (pot fraction) the believed villain uses when several are offered: the nearest. +pub const BELIEVED_BET_FRACTION: f64 = 0.66; /// The read the solver applies to one villain. #[derive(Clone, Copy, Debug, PartialEq)] @@ -120,6 +128,61 @@ impl RangeRead { self.fold.get(street).copied().flatten() } + /// The believed villain's strategy at one decision node, for node-locking in the solver + /// (restricted Nash response: villain plays `(1−w)·σ_cfr + w·believed`, `w` = the solver's trust). + /// `acts` are the node's actions (sizes = street totals in chips), `pot` the pot before this + /// street's bets, `pct` the combo's strength percentile in the villain's (weighted) range. One + /// probability per act, or `None` = no opinion (the node stays pure CFR). + /// + /// - **Facing a bet** (`Fold` and `Call` offered): folds below the street's fold-to-bet read by + /// percentile, calls above; never raises (the read says nothing about raising). No fold read → + /// `None`. + /// - **May bet** (`Check` and `Bet` offered): value-bets from `VALUE_PCT`, bluffs below `BLUFF_PCT` + /// with the probability that makes the air share of its betting range `bluff_share(street, size)`, + /// checks the middle; one size (nearest `BELIEVED_BET_FRACTION`). No aggression read on the street + /// (and, on the river, no shown bets) → `None`. + /// + /// On flop and turn `pct` is current strength (draw-blind), so the bluff region holds the draws: + /// read it as "bets with nothing made", semi-bluffs included. + pub fn believed_row(&self, street: u8, acts: &[Act], pot: f64, pct: f64) -> Option> { + let st = street as usize; + if st > 2 || acts.is_empty() || !pct.is_finite() { + return None; + } + let pct = pct.clamp(0.0, 1.0); + let has = |f: fn(&Act) -> bool| acts.iter().any(f); + if has(|a| matches!(a, Act::Fold)) && has(|a| matches!(a, Act::Call)) { + let f = self.fold_to_bet(st)?; + let fold = pct < f; + return Some(acts.iter().map(|a| match a { + Act::Fold => fold as u8 as f64, + Act::Call => !fold as u8 as f64, + _ => 0.0, + }).collect()); + } + if has(|a| matches!(a, Act::Check)) && has(|a| matches!(a, Act::Bet(_))) { + let read = self.aggression_ratio[st].is_some() || (st == 2 && self.shown.is_some()); + if !read || pot <= 0.0 { + return None; + } + let (ix, to) = acts + .iter() + .enumerate() + .filter_map(|(i, a)| if let Act::Bet(x) = a { Some((i, *x)) } else { None }) + .min_by(|a, b| (a.1 / pot - BELIEVED_BET_FRACTION).abs().total_cmp(&(b.1 / pot - BELIEVED_BET_FRACTION).abs()))?; + let share = self.bluff_share(st, to / pot).clamp(0.0, 0.95); + // air share = BLUFF_PCT·b / ((1−VALUE_PCT) + BLUFF_PCT·b) → b + let bluff = (share * (1.0 - VALUE_PCT) / (BLUFF_PCT * (1.0 - share))).clamp(0.0, 1.0); + let bet = if pct >= VALUE_PCT { 1.0 } else if pct <= BLUFF_PCT { bluff } else { 0.0 }; + return Some(acts.iter().enumerate().map(|(i, a)| match a { + Act::Check => 1.0 - bet, + _ if i == ix => bet, + _ => 0.0, + }).collect()); + } + None + } + /// The confidence a hero line exploiting this read may use: the bluff confidence for lines that /// rest on the villain's betting (calling down, folding bluff-catchers), the plain one otherwise. /// A shown-hand count lifts the bluff confidence to at least its own weight on the river. @@ -188,6 +251,27 @@ mod tests { assert_eq!(unread.trust(true, 1), 0.0); } + #[test] + fn believed_rows_for_the_solver_lock() { + let r = RangeRead::from_profile(Some(&Profile { river_aggression: Some(0.35), ..p() })).unwrap(); + let facing = [Act::Fold, Act::Call, Act::Raise(30.0)]; + assert_eq!(r.believed_row(2, &facing, 10.0, 0.2), Some(vec![1.0, 0.0, 0.0])); + assert_eq!(r.believed_row(2, &facing, 10.0, 0.7), Some(vec![0.0, 1.0, 0.0])); + let open = [Act::Check, Act::Bet(3.3), Act::Bet(6.6), Act::Bet(10.0)]; + assert_eq!(r.believed_row(2, &open, 10.0, 0.9), Some(vec![0.0, 0.0, 1.0, 0.0]), "value on the 2/3 size"); + assert_eq!(r.believed_row(2, &open, 10.0, 0.45), Some(vec![1.0, 0.0, 0.0, 0.0]), "middle checks"); + let air = r.believed_row(2, &open, 10.0, 0.1).unwrap(); + // the betting range's air share is the indifference share at 0.66 pot + let b = air[2]; + let share = BLUFF_PCT * b / ((1.0 - VALUE_PCT) + BLUFF_PCT * b); + assert!((share - 0.66 / 2.32).abs() < 1e-9, "air share {share}"); + assert!((air.iter().sum::() - 1.0).abs() < 1e-12); + let unread = RangeRead::from_profile(Some(&Profile { fold_to_bet: None, aggression: None, ..p() })).unwrap(); + assert_eq!(unread.believed_row(2, &facing, 10.0, 0.2), None, "no fold read, no opinion"); + assert_eq!(unread.believed_row(2, &open, 10.0, 0.2), None, "no aggression read, no opinion"); + assert_eq!(r.believed_row(3, &open, 10.0, 0.2), None); + } + #[test] fn bluff_trust_is_the_weaker_read() { let thin = Profile { aggression_confidence: Some(0.06), ..p() }; From 3b5cee54425e87896c5e1cef7858c000a723c737 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 21:30:17 +0100 Subject: [PATCH 3/3] river_spieler::lock_villain nutzt RangeRead::believed_row (eine Quelle mit der Leseschicht), Gewicht je Knoten trust(gegen Bets / Fold) Co-Authored-By: Claude Opus 5.5 --- messung_solver/abdeckung-turn.txt | 6 - src/engine/river_spieler.rs | 799 +++++++++++++++--------------- 2 files changed, 394 insertions(+), 411 deletions(-) diff --git a/messung_solver/abdeckung-turn.txt b/messung_solver/abdeckung-turn.txt index 7fb894dc..e69de29b 100644 --- a/messung_solver/abdeckung-turn.txt +++ b/messung_solver/abdeckung-turn.txt @@ -1,6 +0,0 @@ -575 eindeutige Anfragen, Schalter ['SOLVER_RIVER=1', 'SOLVER_TURN=1', 'GRUNDSTRATEGIE=D:\\Projects\\pokerfreak\\.claude\\worktrees\\engine-lecks-angreifen-de7b88\\daten', 'MDF_UNREAD=0', 'TURN_SPIEL=grund'] -TURN 1-Gegner: 478 Solver 427 ( 89.3 %) Zeit Solver p50 2045 p99 3781 max 4345 ms solver=427 e3=43 heuristik=8 -TURN 2-Gegner: 88 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=88 -TURN 3-Gegner: 7 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=7 -TURN 4-Gegner: 2 Solver 0 ( 0.0 %) Zeit Solver p50 0 p99 0 max 0 ms heuristik=2 -TURN alle Anfragen: p50 1191 p99 3753 max 4345 ms diff --git a/src/engine/river_spieler.rs b/src/engine/river_spieler.rs index 74ac5478..6698d30d 100644 --- a/src/engine/river_spieler.rs +++ b/src/engine/river_spieler.rs @@ -1,405 +1,394 @@ -//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos, -//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off). -//! -//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line -//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the -//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo -//! (no strength buckets, blockers count). -//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario -//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along -//! the line played; everywhere else both come from the engine's range model -//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's -//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range -//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario). -//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card -//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state. -//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a -//! strategy without moving the equilibrium. -//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under -//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`). -//! -//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash), -//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree. - -use crate::card::Card; -use crate::cfr::river_game::Act; -use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; -use crate::exploit::range_read::RangeRead; -use crate::engine::river_subgame::{legal_choice, river_line}; -use crate::game::{Decision, Spot, Street, Villain}; -use crate::hand::fast7; -use crate::rng::Rng; -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::{Arc, Mutex}; - -/// Who plays the heads-up river. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RiverSpieler { - /// The heuristic (default). - Aus, - /// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model. - An, - /// The solver with range-model ranges everywhere (measurement arm). - Modell, -} - -static MODE: AtomicU8 = AtomicU8::new(0); - -pub fn set_river_spieler(mode: RiverSpieler) { - MODE.store( - match mode { - RiverSpieler::Aus => 0, - RiverSpieler::An => 1, - RiverSpieler::Modell => 2, - }, - Ordering::Relaxed, - ); -} - -pub fn river_spieler() -> RiverSpieler { - match MODE.load(Ordering::Relaxed) { - 1 => RiverSpieler::An, - 2 => RiverSpieler::Modell, - _ => RiverSpieler::Aus, - } -} - -/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`. -pub fn from_env() -> RiverSpieler { - match std::env::var("SOLVER_RIVER").as_deref() { - Ok("1") | Ok("an") => RiverSpieler::An, - Ok("modell") => RiverSpieler::Modell, - _ => RiverSpieler::Aus, - } -} - -/// CFR+ iterations at most. -pub const ITERS: u32 = 600; -/// Fewer finished iterations than this (time budget hit): the heuristic decides. -pub const MIN_ITERS: u32 = 100; -/// Wall-time budget of one solve. -pub const BUDGET_MS: f64 = 1500.0; - -/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises. -fn river_menu() -> Menu { - Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true } -} - -/// One solved river node: what every hero hand at this public state shares. -pub struct Solved { - rows: Vec, - acts: Vec, - hero_masks: Vec, - pub millis: f64, - pub iterations: u32, - pub combos: [usize; 2], - pub nodes: usize, - pub source: &'static str, -} - -/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a -/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do -/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving -/// the equilibrium). -fn hands_of(list: &[(Vec, f64)], dead: u64, fill: bool) -> Hands { - let mut w: HashMap = HashMap::new(); - for (c, x) in list { - if c.len() == 2 && *x > 0.0 && x.is_finite() { - let m = fast7::mask(c); - if m & dead == 0 && m.count_ones() == 2 { - let e = w.entry(m).or_insert(0.0); - *e = e.max(*x); - } - } - } - let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12); - if fill { - let bits: Vec = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect(); - for i in 0..bits.len() { - for j in i + 1..bits.len() { - w.entry(bits[i] | bits[j]).or_insert(top * TOKEN); - } - } - } - let mut v: Vec<(u64, f64)> = w.into_iter().collect(); - v.sort_by(|a, b| a.0.cmp(&b.0)); - Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } -} - -/// Relative weight of a hero hand outside the modelled range. -const TOKEN: f64 = 1e-6; - -/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. -pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str, read: Option<&RangeRead>) -> Option { - if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { - return None; - } - let villain = spot.live_villains().next()?; - let (first, forced, c) = river_line(spot, villain); - let pot = spot.pot - c[0] - c[1]; - let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]); - if pot <= 0.0 || stack <= 0.0 { - return None; - } - let started = std::time::Instant::now(); - let turn = fast7::mask(&spot.board[..4]); - let river = fast7::bit(spot.board[4]); - let dead = turn | river; - let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)]; - if hands[0].masks.is_empty() || hands[1].masks.is_empty() { - return None; - } - let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() }; - let game = build_river(&bets, &forced); - let at = game.at?; - if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) { - return None; - } - let combos = [hands[0].masks.len(), hands[1].masks.len()]; - let hero_masks = hands[0].masks.clone(); - let acts = game.acts[at].clone(); - let nodes = game.nodes.len(); - let villain_weights = hands[1].weights.clone(); - let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); - if let Some(r) = read { - lock_villain(&mut solver, r, pot, dead, &villain_weights); - } - let mut done = 0; - while done < ITERS { - solver.iterate(); - done += 1; - if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS { - break; - } - } - if done < MIN_ITERS { - return None; - } - let strategy = solver.strategy(); - let rows: Vec = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); - let millis = started.elapsed().as_secs_f64() * 1e3; - Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source }) -} - -/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed. -fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option { - let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?; - let a = solved.acts.len(); - let row = &solved.rows[idx * a..(idx + 1) * a]; - let (draw, _) = Rng::seeded(spot.seed).unit(); - let mut acc = 0.0; - let mut pick = a.saturating_sub(1); - for (k, p) in row.iter().enumerate() { - acc += p; - if draw < acc { - pick = k; - break; - } - } - let act = *solved.acts.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 solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", - solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis - ), - )) -} - -/// Both ranges from the range model (the action history): hero's as the model reads hero's own line -/// (no read), the villain's with its gated read. Board cards only are dead (not hero's). -pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { - 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 me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; - let eins = |l: Vec>| l.into_iter().map(|c| (c, 1.0)).collect::>(); - Some((eins(list(&me)?), eins(list(villain)?))) -} - -/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from -/// its UNGATED profile, or `None` = the plain solver. -pub fn read_of(raw: &Spot) -> Option { - if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { - return None; - } - let villain = raw.live_villains().next()?; - RangeRead::from_profile(villain.profile.as_ref()) -} - -/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within -/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. -pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec { - let score: Vec = masks.iter().map(|m| fast7::score(m | board)).collect(); - let mut order: Vec = (0..masks.len()).collect(); - order.sort_by_key(|i| score[*i]); - let total: f64 = weights.iter().sum::().max(1e-300); - let mut out = vec![0.5; masks.len()]; - let mut below = 0.0; - let mut k = 0; - while k < order.len() { - let mut e = k; - let mut tie = 0.0; - while e < order.len() && score[order[e]] == score[order[k]] { - tie += weights[order[e]]; - e += 1; - } - for &i in &order[k..e] { - out[i] = (below + tie / 2.0) / total; - } - below += tie; - k = e; - } - out -} - -/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises -/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the -/// read layer: with a read, the villain's final weights are tilted by strength percentile -/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. -pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { - let (h, mut v, source) = match mode { - RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { - Some((h, v)) => (h, v, "grund"), - None => { - let (h, v) = model_lists(spot)?; - (h, v, "modell") - } - }, - _ => { - let (h, v) = model_lists(spot)?; - (h, v, "modell") - } - }; - if let Some(r) = read.filter(|r| r.confidence > 0.0) { - let board = fast7::mask(&spot.board); - let masks: Vec = v.iter().map(|(c, _)| fast7::mask(c)).collect(); - let weights: Vec = v.iter().map(|(_, w)| *w).collect(); - let pct = percentiles(&masks, &weights, board); - let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); - for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { - *w = x; - } - } - Some((h, v, source)) -} - -/// Value hands bet from this strength percentile up when the believed villain is checked to -/// (as `river_subgame`'s VALUE_RANK). -const BELIEVED_VALUE_RANK: f64 = 0.60; - -/// Lock the villain's river decisions toward the read (restricted Nash response): facing a bet it folds -/// the weakest `fold_to_bet` share of its range and calls the rest (weight = the fold read's trust); -/// checked to, it bets its top `1 - BELIEVED_VALUE_RANK` at the size nearest 75 % pot plus the weakest -/// hands as bluffs so that the air share of the bet is `bluff_share` (weight = the bluff read's trust). -/// Facing a raise it stays free. -fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { - let pct = percentiles(solver.masks(1), villain_weights, board); - // The action that led into each node (a raise faced vs an opening bet faced). - let mut incoming: Vec> = vec![None; solver.game.nodes.len()]; - for (k, n) in solver.game.nodes.iter().enumerate() { - if let TNode::Dec { kids, .. } = n { - for (c, kid) in kids.iter().enumerate() { - incoming[*kid] = solver.game.acts[k].get(c).copied(); - } - } - } - let nodes: Vec<(usize, Vec)> = solver - .game - .nodes - .iter() - .enumerate() - .filter_map(|(k, n)| match n { - TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), - _ => None, - }) - .collect(); - for (node, acts) in nodes { - let a = acts.len(); - let facing_bet = acts.contains(&Act::Fold) && matches!(incoming[node], Some(Act::Bet(_))); - if facing_bet { - let Some(f) = read.fold_to_bet(2) else { continue }; - let call = acts.iter().position(|x| *x == Act::Call).unwrap_or(1); - let rows: Vec = pct.iter().flat_map(|p| (0..a).map(move |k| if *p < f { f64::from(k == 0) } else { f64::from(k == call) })).collect(); - solver.lock(node, rows, read.trust(false, 2)); - } else if !acts.contains(&Act::Fold) && acts.first() == Some(&Act::Check) { - let Some((bet, to)) = acts.iter().enumerate().filter_map(|(k, x)| if let Act::Bet(t) = x { Some((k, *t)) } else { None }).min_by(|x, y| (x.1 / pot - 0.75).abs().total_cmp(&(y.1 / pot - 0.75).abs())) else { continue }; - let bs = read.bluff_share(2, to / pot).clamp(0.0, 0.9); - let value = 1.0 - BELIEVED_VALUE_RANK; - let bluff = (value * bs / (1.0 - bs)).min(BELIEVED_VALUE_RANK); - let rows: Vec = pct.iter().flat_map(|p| (0..a).map(move |k| if *p >= BELIEVED_VALUE_RANK || *p < bluff { f64::from(k == bet) } else { f64::from(k == 0) })).collect(); - solver.lock(node, rows, read.trust(true, 2)); - } - } -} - -static CACHE: Mutex>>> = Mutex::new(None); -const CACHE_MAX: usize = 4096; - -/// Identity of the public state, the villain's read and the mode (not hero's cards). -fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - format!("{:?}", spot.history).hash(&mut h); - format!("{:?}", spot.board).hash(&mut h); - [spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h)); - spot.live_villains().for_each(|v| { - (v.seat, v.stack.to_bits()).hash(&mut h); - format!("{:?}", v.profile).hash(&mut h); - }); - (spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h); - h.finish() -} - -/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not -/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries -/// the ungated reads; the villain range uses the gated ones, as the heuristic's does. -pub fn river_spieler_decision(raw: &Spot) -> Option { - let mode = river_spieler(); - if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 { - return None; - } - let gated = crate::engine::read_gate::gate_reads(raw); - let spot = &gated; - if spot.live_villains().count() != 1 { - return None; - } - let hero_mask = fast7::mask(&spot.hero_cards); - if hero_mask & fast7::mask(&spot.board) != 0 { - return None; - } - let read = read_of(raw); - let mut key = public_key(spot, mode); - if read.is_some() { - let mut h = std::collections::hash_map::DefaultHasher::new(); - (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); - key = h.finish(); - } - let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); - let solved = match cached { - Some(s) => s, - None => { - let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; - let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); - if let Ok(mut m) = CACHE.lock() { - let map = m.get_or_insert_with(HashMap::new); - if map.len() >= CACHE_MAX { - map.clear(); - } - map.insert(key, solved.clone()); - } - solved - } - }; - decide_from(spot, &solved, hero_mask) -} - -#[cfg(test)] -mod tests; +//! Stage A of "solver everywhere": the heads-up RIVER decided by an equilibrium solve over real combos, +//! as the primary decision maker (not a veto). Switch `SOLVER_RIVER` (default off). +//! +//! - **Game:** `cfr::turn_river_game::build_river` - the river alone, with the observed river line +//! inside the tree (exact sizes), position, three bet sizes plus all-in, raises. Solved with the +//! vectorised CFR+ of `TrSolver` over real combos: card removal and showdowns are exact per combo +//! (no strength buckets, blockers count). +//! - **Ranges** come from the hand's action history: where the blueprint recognises the spot (scenario +//! family of `blueprint::ranges`, loaded via `GRUNDSTRATEGIE`) both ranges are the blueprint's along +//! the line played; everywhere else both come from the engine's range model +//! (`exploit::range_model::range_spec` -> `range_filter`): the villain's with its (gated) read, hero's +//! own as the same model sees hero's line, without a read. `SOLVER_RIVER=modell` forces the range +//! model also in blueprint spots (a measurement arm: it shows the model path on the LBR scenario). +//! - **One solve per public state.** The ranges do not depend on hero's cards (the game deals card +//! removal itself), so a solve serves every hero hand at the node; solves are cached by public state. +//! Every hero hand outside the modelled range joins the solve at a token weight, so it gets a +//! strategy without moving the equilibrium. +//! - **Time budget:** CFR+ runs at most `ITERS` iterations and stops at `BUDGET_MS` wall time; under +//! `MIN_ITERS` finished iterations the heuristic keeps the decision (`None`). +//! +//! Not in the slice (the heuristic plays): multiway rivers, tournaments (the caller only asks for cash), +//! Omaha and other variants (hole cards != 2), spots whose line leaves the tree. + +use crate::card::Card; +use crate::cfr::river_game::Act; +use crate::cfr::turn_river_game::{build_river, Hands, Menu, TNode, TrBets, TrSolver}; +use crate::exploit::range_read::RangeRead; +use crate::engine::river_subgame::{legal_choice, river_line}; +use crate::game::{Decision, Spot, Street, Villain}; +use crate::hand::fast7; +use crate::rng::Rng; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex}; + +/// Who plays the heads-up river. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RiverSpieler { + /// The heuristic (default). + Aus, + /// The solver; blueprint ranges where the spot is a blueprint scenario, else the range model. + An, + /// The solver with range-model ranges everywhere (measurement arm). + Modell, +} + +static MODE: AtomicU8 = AtomicU8::new(0); + +pub fn set_river_spieler(mode: RiverSpieler) { + MODE.store( + match mode { + RiverSpieler::Aus => 0, + RiverSpieler::An => 1, + RiverSpieler::Modell => 2, + }, + Ordering::Relaxed, + ); +} + +pub fn river_spieler() -> RiverSpieler { + match MODE.load(Ordering::Relaxed) { + 1 => RiverSpieler::An, + 2 => RiverSpieler::Modell, + _ => RiverSpieler::Aus, + } +} + +/// `SOLVER_RIVER`: `1`/`an` -> `An`, `modell` -> `Modell`, else `Aus`. +pub fn from_env() -> RiverSpieler { + match std::env::var("SOLVER_RIVER").as_deref() { + Ok("1") | Ok("an") => RiverSpieler::An, + Ok("modell") => RiverSpieler::Modell, + _ => RiverSpieler::Aus, + } +} + +/// CFR+ iterations at most. +pub const ITERS: u32 = 600; +/// Fewer finished iterations than this (time budget hit): the heuristic decides. +pub const MIN_ITERS: u32 = 100; +/// Wall-time budget of one solve. +pub const BUDGET_MS: f64 = 1500.0; + +/// The river bet menu: 33 %, 75 %, 125 % pot and all-in; raises to 3x or all-in, two raises. +fn river_menu() -> Menu { + Menu { fracs: vec![0.33, 0.75, 1.25], raise_mult: vec![3.0], max_raises: 2, allin: true } +} + +/// One solved river node: what every hero hand at this public state shares. +pub struct Solved { + rows: Vec, + acts: Vec, + hero_masks: Vec, + pub millis: f64, + pub iterations: u32, + pub combos: [usize; 2], + pub nodes: usize, + pub source: &'static str, +} + +/// Masks and weights of a combo list off the `dead` cards. `fill`: every other two-card combo joins at a +/// token weight, so each possible hero hand has a strategy in the one solve (CFR's regrets of a hand do +/// not depend on its own reach, so a token-weight hand plays its counterfactual best line without moving +/// the equilibrium). +fn hands_of(list: &[(Vec, f64)], dead: u64, fill: bool) -> Hands { + let mut w: HashMap = HashMap::new(); + for (c, x) in list { + if c.len() == 2 && *x > 0.0 && x.is_finite() { + let m = fast7::mask(c); + if m & dead == 0 && m.count_ones() == 2 { + let e = w.entry(m).or_insert(0.0); + *e = e.max(*x); + } + } + } + let top = w.values().copied().fold(0.0f64, f64::max).max(1e-12); + if fill { + let bits: Vec = (0..4u32).flat_map(|s| (0..13u32).map(move |r| 1u64 << (16 * s + r))).filter(|b| b & dead == 0).collect(); + for i in 0..bits.len() { + for j in i + 1..bits.len() { + w.entry(bits[i] | bits[j]).or_insert(top * TOKEN); + } + } + } + let mut v: Vec<(u64, f64)> = w.into_iter().collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + Hands { masks: v.iter().map(|x| x.0).collect(), weights: v.iter().map(|x| x.1).collect() } +} + +/// Relative weight of a hero hand outside the modelled range. +const TOKEN: f64 = 1e-6; + +/// Solve the river of `spot`'s public state with these ranges; every hero hand gets a strategy. `None` off the heads-up river slice, off the tree, or when the budget left too few iterations. +pub fn solve_river(spot: &Spot, hero: &[(Vec, f64)], villain_list: &[(Vec, f64)], source: &'static str, read: Option<&RangeRead>) -> Option { + if spot.street != Street::River || spot.board.len() != 5 || spot.live_villains().count() != 1 { + return None; + } + let villain = spot.live_villains().next()?; + let (first, forced, c) = river_line(spot, villain); + let pot = spot.pot - c[0] - c[1]; + let stack = (spot.hero_stack + c[0]).min(villain.stack + c[1]); + if pot <= 0.0 || stack <= 0.0 { + return None; + } + let started = std::time::Instant::now(); + let turn = fast7::mask(&spot.board[..4]); + let river = fast7::bit(spot.board[4]); + let dead = turn | river; + let hands = [hands_of(hero, dead, true), hands_of(villain_list, dead, false)]; + if hands[0].masks.is_empty() || hands[1].masks.is_empty() { + return None; + } + let bets = TrBets { pot, stack, first, turn: river_menu(), river: river_menu() }; + let game = build_river(&bets, &forced); + let at = game.at?; + if !matches!(game.nodes.get(at), Some(TNode::Dec { player: 0, street: 1, .. })) { + return None; + } + let combos = [hands[0].masks.len(), hands[1].masks.len()]; + let hero_masks = hands[0].masks.clone(); + let acts = game.acts[at].clone(); + let nodes = game.nodes.len(); + let villain_weights = hands[1].weights.clone(); + let mut solver = TrSolver::with_cards(game, hands, turn, vec![river], 1.0); + if let Some(r) = read { + lock_villain(&mut solver, r, pot, dead, &villain_weights); + } + let mut done = 0; + while done < ITERS { + solver.iterate(); + done += 1; + if done % 10 == 0 && started.elapsed().as_secs_f64() * 1e3 > BUDGET_MS { + break; + } + } + if done < MIN_ITERS { + return None; + } + let strategy = solver.strategy(); + let rows: Vec = (0..combos[0]).flat_map(|i| strategy.row(at, 0, i).to_vec()).collect(); + let millis = started.elapsed().as_secs_f64() * 1e3; + Some(Solved { rows, acts, hero_masks, millis, iterations: done, combos, nodes, source }) +} + +/// Hero's action for the real hand from a solved node: the equilibrium mix, realised from the spot seed. +fn decide_from(spot: &Spot, solved: &Solved, hero_mask: u64) -> Option { + let idx = solved.hero_masks.iter().position(|m| *m == hero_mask)?; + let a = solved.acts.len(); + let row = &solved.rows[idx * a..(idx + 1) * a]; + let (draw, _) = Rng::seeded(spot.seed).unit(); + let mut acc = 0.0; + let mut pick = a.saturating_sub(1); + for (k, p) in row.iter().enumerate() { + acc += p; + if draw < acc { + pick = k; + break; + } + } + let act = *solved.acts.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 solver ({}): {}x{} combos, {} nodes, {} iters, {act:?} p {p:.2}, {:.0} ms", + solved.source, solved.combos[0], solved.combos[1], solved.nodes, solved.iterations, solved.millis + ), + )) +} + +/// Both ranges from the range model (the action history): hero's as the model reads hero's own line +/// (no read), the villain's with its gated read. Board cards only are dead (not hero's). +pub fn model_lists(spot: &Spot) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>)> { + 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 me = Villain { seat: spot.hero_seat, stack: spot.hero_stack, folded: false, profile: None }; + let eins = |l: Vec>| l.into_iter().map(|c| (c, 1.0)).collect::>(); + Some((eins(list(&me)?), eins(list(villain)?))) +} + +/// The read layer (`exploit::range_read`, switch `GEGNER_RANGE=1`, default off): the villain's read from +/// its UNGATED profile, or `None` = the plain solver. +pub fn read_of(raw: &Spot) -> Option { + if std::env::var("GEGNER_RANGE").as_deref() != Ok("1") { + return None; + } + let villain = raw.live_villains().next()?; + RangeRead::from_profile(villain.profile.as_ref()) +} + +/// Weighted mid-rank percentile of each combo's current strength (`fast7` score with `board`) within +/// the list. Exact on the river; current strength only (draw-blind) on flop and turn. +pub fn percentiles(masks: &[u64], weights: &[f64], board: u64) -> Vec { + let score: Vec = masks.iter().map(|m| fast7::score(m | board)).collect(); + let mut order: Vec = (0..masks.len()).collect(); + order.sort_by_key(|i| score[*i]); + let total: f64 = weights.iter().sum::().max(1e-300); + let mut out = vec![0.5; masks.len()]; + let mut below = 0.0; + let mut k = 0; + while k < order.len() { + let mut e = k; + let mut tie = 0.0; + while e < order.len() && score[order[e]] == score[order[k]] { + tie += weights[order[e]]; + e += 1; + } + for &i in &order[k..e] { + out[i] = (below + tie / 2.0) / total; + } + below += tie; + k = e; + } + out +} + +/// The ranges of this spot (hero, villain) and where they came from: the blueprint where it recognises +/// the spot (unless `mode` is `Modell`), else the range model of the action history. THE HOOK of the +/// read layer: with a read, the villain's final weights are tilted by strength percentile +/// (`RangeRead::reweigh`); `read = None` returns the lists unchanged. Used by stages A, B and C. +pub fn solver_lists(spot: &Spot, mode: RiverSpieler, read: Option<&RangeRead>) -> Option<(Vec<(Vec, f64)>, Vec<(Vec, f64)>, &'static str)> { + let (h, mut v, source) = match mode { + RiverSpieler::An => match crate::blueprint::ranges::gewichtete_listen_offen(spot) { + Some((h, v)) => (h, v, "grund"), + None => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }, + _ => { + let (h, v) = model_lists(spot)?; + (h, v, "modell") + } + }; + if let Some(r) = read.filter(|r| r.confidence > 0.0) { + let board = fast7::mask(&spot.board); + let masks: Vec = v.iter().map(|(c, _)| fast7::mask(c)).collect(); + let weights: Vec = v.iter().map(|(_, w)| *w).collect(); + let pct = percentiles(&masks, &weights, board); + let pairs: Vec<(f64, f64)> = weights.iter().copied().zip(pct).collect(); + for ((_, w), x) in v.iter_mut().zip(r.reweigh(&pairs)) { + *w = x; + } + } + Some((h, v, source)) +} + +/// Lock the villain's river decisions toward the read (restricted Nash response, `TrSolver::lock`): +/// the believed row per combo is `RangeRead::believed_row` (one source of truth with the read layer). +/// Facing an opening bet the weight is the fold read's trust, where it may bet the bluff read's trust; +/// facing a raise the node stays free (the read says nothing about raises). Nodes the read has no +/// opinion on stay pure CFR. +fn lock_villain(solver: &mut TrSolver, read: &RangeRead, pot: f64, board: u64, villain_weights: &[f64]) { + let pct = percentiles(solver.masks(1), villain_weights, board); + // The action that led into each node (a raise faced vs an opening bet faced). + let mut incoming: Vec> = vec![None; solver.game.nodes.len()]; + for (k, n) in solver.game.nodes.iter().enumerate() { + if let TNode::Dec { kids, .. } = n { + for (c, kid) in kids.iter().enumerate() { + incoming[*kid] = solver.game.acts[k].get(c).copied(); + } + } + } + let nodes: Vec<(usize, Vec)> = solver + .game + .nodes + .iter() + .enumerate() + .filter_map(|(k, n)| match n { + TNode::Dec { player: 1, .. } => Some((k, solver.game.acts[k].clone())), + _ => None, + }) + .collect(); + for (node, acts) in nodes { + let facing = acts.contains(&Act::Fold); + if facing && !matches!(incoming[node], Some(Act::Bet(_))) { + continue; + } + let rows: Option> = pct.iter().map(|p| read.believed_row(2, &acts, pot, *p)).collect::>>>().map(|r| r.concat()); + if let Some(rows) = rows { + solver.lock(node, rows, read.trust(!facing, 2)); + } + } +} + +static CACHE: Mutex>>> = Mutex::new(None); +const CACHE_MAX: usize = 4096; + +/// Identity of the public state, the villain's read and the mode (not hero's cards). +fn public_key(spot: &Spot, mode: RiverSpieler) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", spot.history).hash(&mut h); + format!("{:?}", spot.board).hash(&mut h); + [spot.pot, spot.to_call, spot.hero_stack, spot.big_blind].iter().for_each(|x| x.to_bits().hash(&mut h)); + spot.live_villains().for_each(|v| { + (v.seat, v.stack.to_bits()).hash(&mut h); + format!("{:?}", v.profile).hash(&mut h); + }); + (spot.hero_seat, spot.button_seat, spot.seats, MODE.load(Ordering::Relaxed), mode as u8, ITERS).hash(&mut h); + h.finish() +} + +/// The live decision: the river solved to equilibrium for hero's real hand, or `None` (switch off, not +/// a heads-up Hold'em river, off the tree, budget) and the heuristic keeps the decision. `spot` carries +/// the ungated reads; the villain range uses the gated ones, as the heuristic's does. +pub fn river_spieler_decision(raw: &Spot) -> Option { + let mode = river_spieler(); + if mode == RiverSpieler::Aus || raw.street != Street::River || raw.hero_cards.len() != 2 || raw.board.len() != 5 { + return None; + } + let gated = crate::engine::read_gate::gate_reads(raw); + let spot = &gated; + if spot.live_villains().count() != 1 { + return None; + } + let hero_mask = fast7::mask(&spot.hero_cards); + if hero_mask & fast7::mask(&spot.board) != 0 { + return None; + } + let read = read_of(raw); + let mut key = public_key(spot, mode); + if read.is_some() { + let mut h = std::collections::hash_map::DefaultHasher::new(); + (key, format!("{:?}", raw.live_villains().next().map(|v| v.profile.clone()))).hash(&mut h); + key = h.finish(); + } + let cached = CACHE.lock().ok().and_then(|m| m.as_ref().and_then(|m| m.get(&key).cloned())); + let solved = match cached { + Some(s) => s, + None => { + let (hero, villain, source) = solver_lists(spot, mode, read.as_ref())?; + let solved = Arc::new(solve_river(spot, &hero, &villain, source, read.as_ref())?); + if let Ok(mut m) = CACHE.lock() { + let map = m.get_or_insert_with(HashMap::new); + if map.len() >= CACHE_MAX { + map.clear(); + } + map.insert(key, solved.clone()); + } + solved + } + }; + decide_from(spot, &solved, hero_mask) +} + +#[cfg(test)] +mod tests;