//! The decision deadline of the postflop solvers ("Solver ueberall"): `decide_with` marks the start of //! each decision on its thread, and a solver gets what is left of its street's total before it starts. //! Since 19.11. every deadline counts the CPU time of the deciding thread, not wall time: a decision that //! waits for a core under load (Idle/BelowNormal next to full measurements) used to run out of wall time //! before its solve and fall back to the heuristic, so the same spot played differently with the load. //! Totals per decision (live table): river and flop 2 s, turn 1.25 s, each minus `MARGIN_MS` for the //! work after the solve. Without a mark (tests, tools calling a solver directly) the full total is left. use std::cell::Cell; use std::time::Instant; thread_local! { static START: Cell> = const { Cell::new(None) }; /// Wall time of the mark, only for the live emergency brake (`notbremse`). static WAND: Cell> = const { Cell::new(None) }; /// `fest_hier`: this thread ignores wall time like `SOLVER_ZEIT=fest` (tests, tools). static FEST_HIER: Cell = const { Cell::new(false) }; } /// Total wall time of one decision per street, in ms. pub const RIVER_MS: f64 = 2000.0; pub const TURN_MS: f64 = 1250.0; pub const FLOP_MS: f64 = 2000.0; /// Kept free after the solve (strategy readout, sampling, the answer). pub const MARGIN_MS: f64 = 150.0; /// Mark the start of a decision on this thread. pub fn begin() { START.with(|s| s.set(Some(thread_cpu_ms()))); WAND.with(|s| s.set(Some(Instant::now()))); } /// Live emergency brake in wall time (`KERN_NOTBREMSE_MS`, set only by the live bridge /// `entscheiden/decide.py`, 8 s): past it no solver starts and a running one stops with what it has, so a /// starved machine never times out a table. Measurement and Pflicht paths do not set it and stay purely /// in CPU time (deterministic); `SOLVER_ZEIT=fest` ignores it. pub fn notbremse() -> bool { static MS: std::sync::OnceLock> = std::sync::OnceLock::new(); let Some(ms) = *MS.get_or_init(|| std::env::var("KERN_NOTBREMSE_MS").ok().and_then(|v| v.trim().parse().ok()).filter(|x: &f64| *x > 0.0)) else { return false; }; !fixed() && wand_ueber(ms) } /// Wall time since `begin` exceeds `ms`. fn wand_ueber(ms: f64) -> bool { WAND.with(|w| w.get().is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 > ms)) } /// CPU milliseconds this thread used since the mark (0 without one). Not wall time: waiting for a core /// does not count, so the deadlines do not depend on machine load. pub fn elapsed_ms() -> f64 { START.with(|s| s.get().map_or(0.0, |t| thread_cpu_ms() - t)) } /// What a solver may still spend of `total_ms` (may be ≤ 0: then it must not start). pub fn left_ms(total_ms: f64) -> f64 { if notbremse() { return 0.0; } total_ms - MARGIN_MS - elapsed_ms() } /// Measurement switch `SOLVER_ZEIT=fest`: solvers ignore wall time and always run their full iteration /// count, so ladder and LBR results do not depend on machine load (read once). pub fn fixed() -> bool { static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); FEST_HIER.with(Cell::get) || *FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest")) || iter_aktiv() } /// Measurement switch `SOLVER_ITER=` (NOT a live switch: not in `kern_schalter.txt`, not in `BEKANNTE_SCHALTER`): every /// postflop solve loop ignores time and the emergency brake (as `SOLVER_ZEIT=fest`: `fixed()` is true) and runs exactly the /// iterations the spec names for its kind, so the same engine state gives bit-identical answers at a fixed amount of work. /// Spec: `kind:N` pairs separated by `,`, e.g. `hu_river:100,hu_turn:40,mw_flop:3000`. A kind without a pair runs its own full /// cap (as `fest`); an empty spec or `1` is plain `fest`. N is counted on the solver's outer iteration counter (one `iterate()` /// call). An explicit N also lowers the solver's own floor (`MIN_ITERS`) to N, so a spot is never dropped for time. Staged /// multiway solves (`SOLVER3_ALLE`) always take their first, full stage (the live fallback to smaller stages is a time decision). /// Kinds: `hu_river`, `hu_turn`, `hu_turn_breit` (the second turn solve of `tgstark=breit`), `hu_flop` (the `solver_kern` /// core); `rs_river` (`river_spieler`), `tg_turn` (`turn_game`), `fs_flop` (`flop_spieler`); `mw_flop`, `mw_turn` /// (`multi3_spieler`), `mw_river` (`river3_spieler`). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Art { HuRiver, HuTurn, HuTurnBreit, HuFlop, RsRiver, TgTurn, FsFlop, MwFlop, MwTurn, MwRiver, } impl Art { pub const ALLE: [Art; 10] = [Art::HuRiver, Art::HuTurn, Art::HuTurnBreit, Art::HuFlop, Art::RsRiver, Art::TgTurn, Art::FsFlop, Art::MwFlop, Art::MwTurn, Art::MwRiver]; pub fn name(self) -> &'static str { match self { Art::HuRiver => "hu_river", Art::HuTurn => "hu_turn", Art::HuTurnBreit => "hu_turn_breit", Art::HuFlop => "hu_flop", Art::RsRiver => "rs_river", Art::TgTurn => "tg_turn", Art::FsFlop => "fs_flop", Art::MwFlop => "mw_flop", Art::MwTurn => "mw_turn", Art::MwRiver => "mw_river", } } } /// The parsed `SOLVER_ITER` (read once): `None` = switch unset. fn iter_spec() -> &'static Option> { static SPEC: std::sync::OnceLock>> = std::sync::OnceLock::new(); SPEC.get_or_init(|| { let v = std::env::var("SOLVER_ITER").ok()?; Some( v.split(',') .filter_map(|t| { let (k, n) = t.trim().split_once(':')?; let art = Art::ALLE.into_iter().find(|a| a.name() == k.trim())?; Some((art, n.trim().parse::().ok().filter(|n| *n > 0)?)) }) .collect(), ) }) } /// `SOLVER_ITER` is set: deterministic measurement mode (see `Art`). pub fn iter_aktiv() -> bool { iter_spec().is_some() } /// The iteration count `SOLVER_ITER` names for `art`, if any. pub fn iter_vorgabe(art: Art) -> Option { iter_spec().as_ref()?.iter().find(|(a, _)| *a == art).map(|(_, n)| *n) } /// Iteration cap of a solve loop: the spec's N for `art`, else `standard` (the unchanged cap). pub fn iter_cap(art: Art, standard: u32) -> u32 { iter_vorgabe(art).unwrap_or(standard) } /// Fewest iterations a solve may rest on: `standard`, but never above an explicit N. pub fn iter_min(art: Art, standard: u32) -> u32 { iter_vorgabe(art).map_or(standard, |n| n.min(standard)) } /// Diagnostic `SOLVER_ITER_LOG=1`: one stderr line per finished solve loop with its kind and the iterations it ran. pub fn iter_log(art: Art, done: u64) { static LOG: std::sync::OnceLock = std::sync::OnceLock::new(); if *LOG.get_or_init(|| std::env::var("SOLVER_ITER_LOG").is_ok_and(|v| !v.is_empty() && v != "0")) { eprintln!("SOLVER_ITER_LOG\t{}\t{done}", art.name()); } } thread_local! { static BREIT: Cell = const { Cell::new(false) }; } /// Runs `f` marked as the second turn solve of `tgstark=breit` (its own kind `hu_turn_breit`). pub fn breit_dabei(f: impl FnOnce() -> R) -> R { let vorher = BREIT.with(|b| b.replace(true)); let r = f(); BREIT.with(|b| b.set(vorher)); r } /// Inside `breit_dabei`. pub fn breit_hier() -> bool { BREIT.with(Cell::get) } /// While the guard lives, solvers on THIS thread run their full iteration count whatever the load (as /// `SOLVER_ZEIT=fest`, but per thread). For tests that check a solver's result rather than its deadline: /// under a busy machine the wall-time budget otherwise cuts iterations (different numbers) or drops the /// solve below its minimum (the heuristic decides). Never called on the live path. pub fn fest_hier() -> FestHier { FestHier(FEST_HIER.with(|f| f.replace(true))) } /// Guard of `fest_hier`; restores the previous state on drop. pub struct FestHier(bool); impl Drop for FestHier { fn drop(&mut self) { FEST_HIER.with(|f| f.set(self.0)); } } /// CPU time this thread has used so far, in ms. A cap on it does not depend on machine load: a thread /// that waits for a core uses no CPU time, so the same solve stops after the same work (Solver-Kern 18.11.). /// Windows counts in scheduler ticks (~15.6 ms); elsewhere without a thread clock: wall time. pub fn thread_cpu_ms() -> f64 { #[cfg(windows)] { #[repr(C)] struct FileTime { lo: u32, hi: u32, } #[link(name = "kernel32")] extern "system" { fn GetCurrentThread() -> isize; fn GetThreadTimes(h: isize, c: *mut FileTime, e: *mut FileTime, k: *mut FileTime, u: *mut FileTime) -> i32; } let z = || FileTime { lo: 0, hi: 0 }; let (mut c, mut e, mut k, mut u) = (z(), z(), z(), z()); // SAFETY: GetCurrentThread returns a pseudo handle; the four out pointers are valid for the call. if unsafe { GetThreadTimes(GetCurrentThread(), &mut c, &mut e, &mut k, &mut u) } != 0 { let ms = |f: &FileTime| (((f.hi as u64) << 32) | f.lo as u64) as f64 / 1e4; return ms(&k) + ms(&u); } } #[cfg(any(target_os = "linux", target_os = "macos"))] { #[repr(C)] struct TimeSpec { sec: i64, nsec: i64, } extern "C" { fn clock_gettime(id: i32, t: *mut TimeSpec) -> i32; } let id = if cfg!(target_os = "linux") { 3 } else { 16 }; // CLOCK_THREAD_CPUTIME_ID let mut t = TimeSpec { sec: 0, nsec: 0 }; // SAFETY: t is a valid out pointer for the call. if unsafe { clock_gettime(id, &mut t) } == 0 { return t.sec as f64 * 1e3 + t.nsec as f64 / 1e6; } } thread_local! { static NULL: Instant = Instant::now(); } NULL.with(|t| t.elapsed().as_secs_f64() * 1e3) } /// The budget a solve gets: `cap_ms` (its own limit), cut to what is left of the street's total; /// infinite under `SOLVER_ZEIT=fest`. pub fn budget_ms(cap_ms: f64, total_ms: f64) -> f64 { if fixed() { f64::INFINITY } else { cap_ms.min(left_ms(total_ms)) } } #[cfg(test)] mod tests { #[test] fn notbremse_zaehlt_uhrzeit() { super::begin(); std::thread::sleep(std::time::Duration::from_millis(300)); assert!(super::wand_ueber(200.0) && !super::wand_ueber(5000.0)); assert!(super::elapsed_ms() < 100.0); // Ohne KERN_NOTBREMSE_MS (Mess- und Pflichtpfad) greift sie nie. if std::env::var("KERN_NOTBREMSE_MS").is_err() { assert!(!super::notbremse()); } } #[test] fn warten_zaehlt_nicht_zur_frist() { // Pflichtfälle 19.11.: unter Last wartete der Kern (Idle) Sekunden auf einen Kern, die 3-s-Notuhr // griff vor dem River-Solve, und die Heuristik spielte ihre Overbets. Warten darf nicht zählen. super::begin(); std::thread::sleep(std::time::Duration::from_millis(400)); assert!(super::elapsed_ms() < 100.0, "{}", super::elapsed_ms()); assert!(super::left_ms(super::RIVER_MS) > 1700.0); } #[test] fn thread_cpu_ms_zaehlt_kein_warten() { let a = super::thread_cpu_ms(); std::thread::sleep(std::time::Duration::from_millis(200)); let b = super::thread_cpu_ms(); let t = std::time::Instant::now(); let mut x = 0u64; while t.elapsed().as_millis() < 200 { x = x.wrapping_mul(6364136223846793005).wrapping_add(std::hint::black_box(1)); } std::hint::black_box(x); let c = super::thread_cpu_ms(); assert!(b - a < 100.0, "Schlafen zählt als Rechenzeit: {}", b - a); assert!(c - b > 50.0, "Rechnen zählt nicht: {}", c - b); } }