Files
pokerfreak/src/engine/frist.rs
T
mmintelandClaude Opus 5.5 55c713d4e0 Notbremse in Uhrzeit nur live (KERN_NOTBREMSE_MS=8000 aus decide.py) + Pflicht in BelowNormal
frist::notbremse(): Uhrzeit seit begin() ueber KERN_NOTBREMSE_MS -> left_ms 0, kein Solver startet,
laufende Solver-Schleifen (turn_game, flop/river/river3/multi3, solver_kern) geben ab, die Heuristik
entscheidet. Gesetzt nur von entscheiden/decide.py (Live-Pfad); roentgen.kern_aufruf entfernt sie,
Mess- und Pflichtpfade bleiben rein in Rechenzeit. Pflichtfaelle: Kern in BelowNormal, Frist 30 s je Fall
(vorher Idle, 275 s gesamt, brach unter Volllast ab). Nachweis: Bremse 1 ms -> 0/20 Solver, ohne -> 20/20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 01:26:48 +01:00

185 lines
7.8 KiB
Rust

//! 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<Option<f64>> = const { Cell::new(None) };
/// Wall time of the mark, only for the live emergency brake (`notbremse`).
static WAND: Cell<Option<Instant>> = const { Cell::new(None) };
/// `fest_hier`: this thread ignores wall time like `SOLVER_ZEIT=fest` (tests, tools).
static FEST_HIER: Cell<bool> = 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<Option<f64>> = 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<bool> = std::sync::OnceLock::new();
FEST_HIER.with(Cell::get) || *FIXED.get_or_init(|| std::env::var("SOLVER_ZEIT").as_deref() == Ok("fest"))
}
/// 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);
}
}