native-solver 0.1.0

Heads-up postflop No-Limit Hold'em solver: hand evaluator, ranges, betting trees, and combo-vectorized CFR / CFR+ / DCFR.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Reproducible, end-to-end solver benchmark using only the public API.
//!
//! Build separately from measurement:
//!   cargo build --release --example solver_performance
//!   target/release/examples/solver_performance --workload river-broad --threads 1
//! Use the identical file, arguments, compiler and host for both revisions.
//! Run each workload in a fresh process for comparable cold initialization, and
//! repeat/alternate revisions to measure noise. No bucketing or suit reduction.
//! Output is JSON Lines (default), or CSV with a JSON checkpoint-array column.
//! Times exclude compilation, thread-pool creation and result serialization.
//! A fixed-iteration run is explicitly selected with --fixed-iterations; it does
//! not claim convergence. Otherwise hitting the cap without the target exits 2.

use native_solver::card::{Card, CardSet};
use native_solver::range::{all_canonical_hands, Combo, Range};
use native_solver::solver::quality::ReferenceEvaluator;
use native_solver::solver::Chips;
use native_solver::solver::TrainerOptions;
use native_solver::solver::{
    build_tree_bounded, Exploitability, GameConfig, Node, Player, SolverAlgorithm, Trainer,
};
use rayon::ThreadPoolBuilder;
use std::fmt::Write;
use std::time::{Duration, Instant};

const MAX_REFERENCE_WORK: usize = 6_000_000;
const MAX_DECISION_NODES: usize = 250_000;

const HELP: &str = "solver_performance [OPTIONS]
  --workload NAME       river-narrow, river-broad, turn-moderate, river-paired,
                        river-monotone, turn-draws, flop-dry, flop-two-tone,
                        flop-monotone, flop-paired, or all (legacy six; default)
  --algorithm NAME      cfr, cfr-plus (default), dcfr
  --iterations N        maximum iterations, or exact count in fixed mode (1000)
  --check-every N       exploitability checkpoint spacing in iterations (50)
  --target-chips X      exploitability target, in chips, not percent (0.1)
  --threads N           dedicated Rayon thread count (1)
  --format FORMAT       json (one object per workload) or csv (json)
  --fixed-iterations    train to cap unless timed out; convergence is separate
  --reference-check     independent final profile/BR audit (bounded trees only)
  --max-seconds X       soft solve budget; checked between batches (default 180)
  --help                show this help

All games use pot=100, no abstraction or suit reduction.
CFR+ means the legacy simultaneous, uniformly averaged RM+ variant.
DCFR uses simultaneous updates and published alpha=1.5, beta=0, gamma=2.
river-narrow: 37 OOP / 27 IP combos, two bet sizes, one raise.
river-broad: every legal combo for each player, two bet sizes, one raise.
turn-moderate: 37 OOP / 27 IP combos, one bet size, no raises.
Flop fixtures use one bet size, no raises, and exact full runouts.
Use the Python runner for a hard process timeout and RSS guard.
The three original held-out fixtures are river-paired (weighted, stack=75),
river-monotone (weighted, stack=150), turn-draws (stack=100).
Checkpoints include iteration 0 and the exact final cap. Exit 2 means at least
one target-mode workload hit its cap without convergence; invalid input or
nonfinite results exit 1. Each workload's first initialization may include
process-global evaluator table initialization; prefer separate processes.
";

struct Options {
    workload: String,
    algorithm: SolverAlgorithm,
    iterations: u32,
    check_every: u32,
    target: f64,
    threads: usize,
    csv: bool,
    fixed: bool,
    reference: bool,
    max_seconds: f64,
}

impl Options {
    fn parse() -> Result<Option<Self>, String> {
        let mut options = Self {
            workload: "all".into(),
            algorithm: SolverAlgorithm::CfrPlus,
            iterations: 1000,
            check_every: 50,
            target: 0.1,
            threads: 1,
            csv: false,
            fixed: false,
            reference: false,
            max_seconds: 180.0,
        };
        let mut args = std::env::args().skip(1);
        while let Some(arg) = args.next() {
            if arg == "--help" || arg == "-h" {
                print!("{HELP}");
                return Ok(None);
            }
            if arg == "--reference-check" {
                options.reference = true;
                continue;
            }
            if arg == "--fixed-iterations" {
                options.fixed = true;
                continue;
            }
            let value = args
                .next()
                .ok_or_else(|| format!("missing value for {arg}"))?;
            match arg.as_str() {
                "--workload" => options.workload = value,
                "--algorithm" => {
                    options.algorithm = match value.as_str() {
                        "cfr" => SolverAlgorithm::Cfr,
                        "cfr-plus" => SolverAlgorithm::CfrPlus,
                        "dcfr" => SolverAlgorithm::Dcfr,
                        _ => return Err("--algorithm must be cfr, cfr-plus or dcfr".into()),
                    }
                }
                "--iterations" => {
                    options.iterations = value.parse().map_err(|_| "invalid --iterations")?
                }
                "--check-every" => {
                    options.check_every = value.parse().map_err(|_| "invalid --check-every")?
                }
                "--threads" => options.threads = value.parse().map_err(|_| "invalid --threads")?,
                "--max-seconds" => {
                    options.max_seconds = value.parse().map_err(|_| "invalid --max-seconds")?
                }
                "--target-chips" => {
                    options.target = value.parse().map_err(|_| "invalid --target-chips")?
                }
                "--format" => {
                    options.csv = match value.as_str() {
                        "json" => false,
                        "csv" => true,
                        _ => return Err("--format must be json or csv".into()),
                    }
                }
                _ => return Err(format!("unknown argument {arg}")),
            }
        }
        if ![
            "all",
            "river-narrow",
            "river-broad",
            "turn-moderate",
            "river-paired",
            "river-monotone",
            "turn-draws",
            "flop-dry",
            "flop-two-tone",
            "flop-monotone",
            "flop-paired",
        ]
        .contains(&options.workload.as_str())
        {
            return Err("unknown workload (see --help)".into());
        }
        if options.iterations == 0 || options.check_every == 0 || options.threads == 0 {
            return Err("iterations, check-every and threads must all be positive".into());
        }
        if !options.target.is_finite() || options.target <= 0.0 {
            return Err("--target-chips must be positive and finite".into());
        }
        if !options.max_seconds.is_finite() || options.max_seconds <= 0.0 {
            return Err("--max-seconds must be positive and finite".into());
        }
        Ok(Some(options))
    }
}

struct Checkpoint {
    elapsed_seconds: f64,
    iterations: u32,
    train_seconds: f64,
    diagnostic_seconds: f64,
    exploitability: Exploitability,
}

struct ResultRow {
    name: String,
    reference_json: String,
    board: String,
    range_specs: [String; 2],
    range_sizes: [usize; 2],
    decision_nodes: usize,
    bet_sizes: Vec<f64>,
    effective_stack: f64,
    peak_rss_kib: Option<u64>,
    max_raises: u32,
    joint_mass: f64,
    initialization_seconds: f64,
    train_seconds: f64,
    diagnostic_seconds: f64,
    evaluate_seconds: f64,
    solve_seconds: f64,
    total_seconds: f64,
    iterations: u32,
    converged: bool,
    time_budget_reached: bool,
    first_target_iteration: Option<u32>,
    root_ev: [f64; 2],
    strategy_checksum: f64,
    evaluation_checksum: f64,
    checkpoints: Vec<Checkpoint>,
}

fn sorted_combos(spec: &str, board: &[Card]) -> Result<Vec<Combo>, String> {
    let mut combos = Range::parse(spec)
        .map_err(|e| e.to_string())?
        .combos(CardSet::from_cards(board));
    // Fix each pair's orientation as well as the combo order so reductions
    // are repeatable.
    for combo in &mut combos {
        combo.cards.sort_unstable();
    }
    combos.sort_by_key(|c| c.cards);
    Ok(combos)
}

fn run(name: &str, options: &Options) -> Result<ResultRow, String> {
    let total_start = Instant::now();
    let (board_text, range_specs, bet_sizes, max_raises, effective_stack) = match name {
        "river-narrow" => (
            "2c,7d,9h,Ks,3c",
            ["QQ,JJ,TT,99,AQs,AQo".into(), "88,77,66,KTs,KTo".into()],
            vec![0.5, 1.0],
            1,
            200.0,
        ),
        "river-broad" => {
            let all = all_canonical_hands().join(",");
            (
                "2c,7d,9h,Ks,3c",
                [all.clone(), all],
                vec![0.5, 1.0],
                1,
                200.0,
            )
        }
        "turn-moderate" => (
            "2c,7d,9h,Ks",
            ["QQ,JJ,TT,99,AQs,AQo".into(), "88,77,66,KTs,KTo".into()],
            vec![1.0],
            0,
            200.0,
        ),
        "river-paired" => (
            "Qc,Qd,7h,4s,2c",
            [
                "AA:0.5,KK,JJ,AQs,AQo:0.25".into(),
                "77,88,99,KQs,KQo:0.5".into(),
            ],
            vec![0.33, 0.75, 1.5],
            1,
            75.0,
        ),
        "river-monotone" => (
            "Ah,Kh,8h,5h,2c",
            [
                "QJs,QJo:0.5,TT,99,76s".into(),
                "QQ,JJ,T9s,T9o:0.4,AQs".into(),
            ],
            vec![0.5, 1.0],
            1,
            150.0,
        ),
        "turn-draws" => (
            "Ts,9s,4d,2c",
            ["AKs,AQs,KQs,JJ,TT".into(), "AJs,KJs,QJs,99,88".into()],
            vec![0.75],
            0,
            100.0,
        ),
        "flop-dry" => (
            "Ks,7d,2c",
            ["AA,AKs".into(), "QQ,KQs".into()],
            vec![0.5],
            0,
            100.0,
        ),
        "flop-two-tone" => (
            "Js,9s,4d",
            ["AA,KK,QQ,AQs,AKs,KQs".into(), "JJ,TT,99,QTs,T8s,AJs".into()],
            vec![0.75],
            0,
            100.0,
        ),
        "flop-monotone" => (
            "Ah,8h,3h",
            ["AKs,AQo:0.5,KK".into(), "QJs,JTs,88:0.5".into()],
            vec![0.5],
            0,
            75.0,
        ),
        "flop-paired" => (
            "Qc,Qd,5s",
            ["AA:0.5,KK,AQs,KQs".into(), "JJ,TT,55,QJs".into()],
            vec![1.0],
            0,
            150.0,
        ),
        _ => return Err(format!("unknown workload: {name}")),
    };
    let board: Vec<Card> = board_text
        .split(',')
        .map(|c| c.parse::<Card>().expect("valid fixture board"))
        .collect();
    let combos = [
        sorted_combos(&range_specs[0], &board)?,
        sorted_combos(&range_specs[1], &board)?,
    ];
    let range_sizes = [combos[0].len(), combos[1].len()];
    if options.reference && range_sizes[0] * range_sizes[1] > 10000 {
        return Err(
            "--reference-check is limited to at most 10000 private-pair entries; use small ranges"
                .into(),
        );
    }
    // This one-time normalization is deliberately outside timed training and
    // included in initialization. evaluate() returns raw range-weighted CFVs;
    // divide by compatible initial joint range mass for an EV in chips.
    let joint_mass: f64 = combos[0]
        .iter()
        .map(|a| {
            combos[1]
                .iter()
                .filter(|b| {
                    a.cards[0] != b.cards[0]
                        && a.cards[0] != b.cards[1]
                        && a.cards[1] != b.cards[0]
                        && a.cards[1] != b.cards[1]
                })
                .map(|b| a.weight * b.weight)
                .sum::<f64>()
        })
        .sum();
    if !joint_mass.is_finite() || joint_mass <= 0.0 {
        return Err("invalid compatible initial range mass".into());
    }
    let cfg = GameConfig::new(
        board.clone(),
        Chips::whole(100),
        Chips::from_f64(effective_stack).expect("workload stacks are whole chips"),
    )
    .with_bet_sizes(bet_sizes.clone())
    .with_max_raises(max_raises);
    let tree = build_tree_bounded(&cfg, MAX_DECISION_NODES).map_err(|e| e.to_string())?;
    let decision_nodes = tree.num_decision_nodes;
    // Pair count alone is insufficient on a flop: reject a large independent
    // traversal before allocating its state. This is a conservative work proxy,
    // not an estimate of resident bytes. The runner provides hard limits too.
    let reference_work = decision_nodes
        .saturating_mul(range_sizes[0])
        .saturating_mul(range_sizes[1]);
    if options.reference && reference_work > MAX_REFERENCE_WORK {
        return Err(format!("--reference-check exceeds {MAX_REFERENCE_WORK} decision/private-pair work units ({reference_work}); use the production exact metric without an independent audit"));
    }
    let mut trainer = Trainer::new(
        tree,
        combos,
        TrainerOptions {
            algorithm: options.algorithm,
            ..TrainerOptions::default()
        },
    )
    .unwrap();
    let initialization_seconds = total_start.elapsed().as_secs_f64();
    let mut train_time = Duration::ZERO;
    let mut diagnostic_time = Duration::ZERO;
    let mut iterations = 0;
    let mut first_target_iteration = None;
    let mut checkpoints = Vec::new();
    loop {
        let start = Instant::now();
        let exploitability = trainer.exploitability();
        diagnostic_time += start.elapsed();
        if ![exploitability.oop, exploitability.ip, exploitability.total]
            .iter()
            .all(|v| v.is_finite())
        {
            return Err(format!(
                "{name}: nonfinite exploitability at iteration {iterations}"
            ));
        }
        let converged = exploitability.total <= options.target;
        if converged && first_target_iteration.is_none() {
            first_target_iteration = Some(iterations);
        }
        checkpoints.push(Checkpoint {
            elapsed_seconds: total_start.elapsed().as_secs_f64(),
            iterations,
            train_seconds: train_time.as_secs_f64(),
            diagnostic_seconds: diagnostic_time.as_secs_f64(),
            exploitability,
        });
        if iterations >= options.iterations
            || (!options.fixed && converged)
            || total_start.elapsed().as_secs_f64() >= options.max_seconds
        {
            break;
        }
        let batch = options.check_every.min(options.iterations - iterations);
        let start = Instant::now();
        let current_raw_cfv = trainer.train(batch);
        train_time += start.elapsed();
        if !current_raw_cfv.iter().all(|v| v.is_finite()) {
            return Err(format!("{name}: nonfinite current-strategy CFV"));
        }
        iterations += batch;
    }
    let solve_seconds = total_start.elapsed().as_secs_f64();
    let start = Instant::now();
    let evaluation = trainer.evaluate();
    let (evaluations, raw_root_cfv) = (evaluation.nodes, evaluation.root_values);
    let evaluate_seconds = start.elapsed().as_secs_f64();
    let root_ev = [raw_root_cfv[0] / joint_mass, raw_root_cfv[1] / joint_mass];
    let mut strategy_checksum = 0.0;
    let mut evaluation_checksum = 0.0;
    // Weighted numeric checksums are compact drift indicators, not proofs of
    // numerical equivalence. Include every node's board-legal acting-player
    // combos only: impossible rows have no meaning and must not affect output.
    // Calculation is excluded from solve/evaluate timing, included in total.
    let mut players = vec![0; decision_nodes];
    collect_players(trainer.game().tree(), &mut players);
    for (node_id, &player) in players.iter().enumerate() {
        let board_mask = CardSet::from_cards(trainer.game().node_board(node_id));
        let live: Vec<bool> = trainer
            .game()
            .combos(Player::ALL[player])
            .iter()
            .map(|c| !board_mask.contains(c.cards[0]) && !board_mask.contains(c.cards[1]))
            .collect();
        let strategy = trainer.average_strategy(node_id);
        for (action, row) in strategy.iter().enumerate() {
            for (combo, &value) in row.iter().enumerate() {
                if !live[combo] {
                    continue;
                }
                if !value.is_finite() {
                    return Err(format!("{name}: nonfinite strategy at node {node_id}"));
                }
                strategy_checksum += value
                    * ((node_id + 1) as f64
                        + (action + 1) as f64 / 17.0
                        + (combo + 1) as f64 / 65537.0);
            }
        }
        let evaluation = evaluations
            .get(node_id)
            .ok_or_else(|| format!("{name}: missing evaluation node {node_id}"))?;
        for (combo, &value) in evaluation.ev.iter().enumerate() {
            if !live[combo] {
                continue;
            }
            if !value.is_finite() {
                return Err(format!("{name}: nonfinite EV at node {node_id}"));
            }
            evaluation_checksum += value * ((node_id + 1) as f64 + (combo + 1) as f64 / 65537.0);
        }
        if let Some(equity) = &evaluation.equity {
            for (combo, &value) in equity.iter().enumerate() {
                if !live[combo] {
                    continue;
                }
                if !value.is_finite() {
                    return Err(format!("{name}: nonfinite equity at node {node_id}"));
                }
                evaluation_checksum +=
                    value * ((node_id + 1) as f64 / 17.0 + (combo + 1) as f64 / 65537.0);
            }
        }
    }
    if !root_ev
        .iter()
        .chain([&strategy_checksum, &evaluation_checksum])
        .all(|v| v.is_finite())
    {
        return Err(format!("{name}: nonfinite normalized EV or checksum"));
    }
    let converged = checkpoints
        .last()
        .expect("initial checkpoint exists")
        .exploitability
        .total
        <= options.target;
    let time_budget_reached = iterations < options.iterations
        && (options.fixed || !converged)
        && solve_seconds >= options.max_seconds;
    let total_seconds = total_start.elapsed().as_secs_f64();
    let peak_rss_kib = peak_rss_kib();
    // Keep the expensive independent audit outside the production solver's
    // total time and peak RSS. The audit has its own explicit timing field.
    let reference_json = if options.reference {
        let start = Instant::now();
        let evaluator = ReferenceEvaluator::new(
            trainer.game().tree(),
            cfg.board(),
            Player::ALL.map(|player| trainer.game().combos(player)),
        )
        .map_err(|e| e.to_string())?;
        let quality = evaluator
            .evaluate(|id| trainer.average_strategy(id))
            .map_err(|e| e.to_string())?;
        let production = checkpoints.last().unwrap().exploitability;
        let error = (quality.profile_ev[0] - root_ev[0])
            .abs()
            .max((quality.profile_ev[1] - root_ev[1]).abs())
            .max((quality.best_response_ev[0] - production.oop).abs())
            .max((quality.best_response_ev[1] - production.ip).abs());
        if !error.is_finite() || error > 1e-8 {
            return Err(format!("independent reference disagreement: {error} chips"));
        }
        format!("{{\"seconds\":{:.9},\"exploitability_chips\":{:.12},\"max_value_error_chips\":{:.12}}}",
            start.elapsed().as_secs_f64(), quality.exploitability, error)
    } else {
        "null".into()
    };
    Ok(ResultRow {
        name: name.into(),
        reference_json,
        board: board_text.into(),
        range_specs,
        range_sizes,
        decision_nodes,
        bet_sizes,
        effective_stack,
        peak_rss_kib,
        max_raises,
        joint_mass,
        initialization_seconds,
        train_seconds: train_time.as_secs_f64(),
        diagnostic_seconds: diagnostic_time.as_secs_f64(),
        evaluate_seconds,
        solve_seconds,
        total_seconds,
        iterations,
        converged,
        time_budget_reached,
        first_target_iteration,
        root_ev,
        strategy_checksum,
        evaluation_checksum,
        checkpoints,
    })
}

fn collect_players(node: &Node, players: &mut [usize]) {
    match node {
        Node::Decision {
            id,
            player,
            children,
            ..
        } => {
            players[*id] = player.index();
            for child in children {
                collect_players(child, players);
            }
        }
        Node::Chance { children } => {
            for (_, child) in children {
                collect_players(child, players);
            }
        }
        Node::Terminal(_) => {}
    }
}

fn checkpoint_json(checkpoints: &[Checkpoint]) -> String {
    let mut out = String::from("[");
    for (i, c) in checkpoints.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        write!(out, "{{\"elapsed_seconds\":{:.9},\"iterations\":{},\"train_seconds\":{:.9},\"exploitability_seconds_cumulative\":{:.9},\"exploitability_chips\":{:.12},\"best_response_oop_chips\":{:.12},\"best_response_ip_chips\":{:.12}}}",
            c.elapsed_seconds, c.iterations, c.train_seconds, c.diagnostic_seconds, c.exploitability.total, c.exploitability.oop, c.exploitability.ip).unwrap();
    }
    out.push(']');
    out
}

fn algorithm_name(algorithm: SolverAlgorithm) -> &'static str {
    match algorithm {
        SolverAlgorithm::Cfr => "cfr",
        SolverAlgorithm::CfrPlus => "cfr-plus",
        SolverAlgorithm::Dcfr => "dcfr",
        other => unimplemented!("no command-line name for {other:?}"),
    }
}

// Linux VmHWM is sampled by the solver itself after all work. Unlike a
// launcher's wait4 high water it does not carry the launcher's pre-exec RSS.
// This is whole-process resident memory, including tables, Rayon and allocator;
// unsupported platforms return null rather than a misleading zero.
fn peak_rss_kib() -> Option<u64> {
    std::fs::read_to_string("/proc/self/status")
        .ok()?
        .lines()
        .find_map(|line| {
            line.strip_prefix("VmHWM:")
                .and_then(|value| value.split_whitespace().next()?.parse().ok())
        })
}

fn emit(row: &ResultRow, options: &Options, process_workload_index: usize) {
    let status = if row.time_budget_reached {
        "time_budget"
    } else if options.fixed {
        "fixed_iterations"
    } else if row.converged {
        "target_reached"
    } else {
        "iteration_cap"
    };
    let target_iteration = row
        .first_target_iteration
        .map_or_else(|| "null".into(), |n| n.to_string());
    let final_exploitability = row.checkpoints.last().unwrap().exploitability.total;
    let checkpoints = checkpoint_json(&row.checkpoints);
    if options.csv {
        // The fixed fixture strings contain no quotes; escape the JSON column.
        println!("{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{:.9},{:.9},{:.9},{:.9},{:.9},{:.9},{:.12},{:.12},{:.12},{:.12},{:.12},\"{}\",\"{}\",4,{},exact_finite_action_game,{}",
            row.name, algorithm_name(options.algorithm), row.effective_stack, row.peak_rss_kib.map_or_else(String::new, |n| n.to_string()), options.threads, process_workload_index, row.range_sizes[0], row.range_sizes[1], row.decision_nodes,
            options.iterations, options.check_every, options.target, row.iterations, status, row.converged, target_iteration,
            row.max_raises, row.bet_sizes.len(), row.joint_mass,
            row.initialization_seconds, row.train_seconds, row.diagnostic_seconds, row.evaluate_seconds, row.solve_seconds, row.total_seconds,
            final_exploitability, row.root_ev[0], row.root_ev[1], row.strategy_checksum, row.evaluation_checksum, checkpoints.replace('"', "\"\""), row.reference_json.replace('"', "\"\""), options.max_seconds, options.reference);
    } else {
        // All strings here are fixed validated fixture names/specifications.
        println!(concat!(
            "{{\"schema_version\":4,\"workload\":\"{}\",\"algorithm\":\"{}\",\"threads\":{},\"process_workload_index\":{},",
            "\"board\":\"{}\",\"range_specs\":[\"{}\",\"{}\"],\"range_sizes\":[{},{}],\"decision_nodes\":{},",
            "\"pot_chips\":100,\"effective_stack_chips\":{},\"bet_sizes\":{:?},\"max_raises\":{},",
            "\"checksum_scope\":\"all_nodes_board_legal_combos\",\"update_schedule\":\"simultaneous\",\"peak_rss_kib\":{},\"card_abstraction\":false,\"suit_isomorphism\":false,\"joint_range_mass\":{},",
            "\"max_seconds\":{},\"quality_scope\":\"exact_finite_action_game\",\"independent_audit\":{},\"iteration_cap\":{},\"check_every\":{},\"target_chips\":{},\"iterations\":{},\"status\":\"{}\",\"converged\":{},\"first_target_iteration\":{},",
            "\"initialization_seconds\":{:.9},\"train_seconds\":{:.9},\"exploitability_seconds\":{:.9},\"evaluate_seconds\":{:.9},\"solve_seconds\":{:.9},\"total_seconds\":{:.9},",
            "\"exploitability_chips\":{:.12},\"root_average_ev_chips\":[{:.12},{:.12}],\"strategy_checksum\":{:.12},\"evaluation_checksum\":{:.12},\"checkpoints\":{},\"reference_check\":{}}}"),
            row.name, algorithm_name(options.algorithm), options.threads, process_workload_index, row.board, row.range_specs[0], row.range_specs[1], row.range_sizes[0], row.range_sizes[1], row.decision_nodes,
            row.effective_stack, row.bet_sizes, row.max_raises, row.peak_rss_kib.map_or_else(|| "null".into(), |n| n.to_string()), row.joint_mass, options.max_seconds, options.reference, options.iterations, options.check_every, options.target, row.iterations, status, row.converged, target_iteration,
            row.initialization_seconds, row.train_seconds, row.diagnostic_seconds, row.evaluate_seconds, row.solve_seconds, row.total_seconds,
            final_exploitability, row.root_ev[0], row.root_ev[1], row.strategy_checksum, row.evaluation_checksum, checkpoints, row.reference_json);
    }
}

fn main() -> std::process::ExitCode {
    let options = match Options::parse() {
        Ok(Some(options)) => options,
        Ok(None) => return std::process::ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("error: {error}");
            return std::process::ExitCode::from(1);
        }
    };
    if cfg!(debug_assertions) {
        eprintln!("error: benchmark requires a release build (--release)");
        return std::process::ExitCode::from(1);
    }
    let pool = match ThreadPoolBuilder::new()
        .num_threads(options.threads)
        .build()
    {
        Ok(pool) => pool,
        Err(error) => {
            eprintln!("error creating Rayon pool: {error}");
            return std::process::ExitCode::from(1);
        }
    };
    if options.csv {
        println!("workload,algorithm,effective_stack_chips,peak_rss_kib,threads,process_workload_index,oop_combos,ip_combos,decision_nodes,iteration_cap,check_every,target_chips,iterations,status,converged,first_target_iteration,max_raises,bet_size_count,joint_range_mass,initialization_seconds,train_seconds,exploitability_seconds,evaluate_seconds,solve_seconds,total_seconds,exploitability_chips,root_oop_ev_chips,root_ip_ev_chips,strategy_checksum,evaluation_checksum,checkpoints_json,reference_check_json,schema_version,max_seconds,quality_scope,independent_audit");
    }
    let workloads = if options.workload == "all" {
        vec![
            "river-narrow",
            "river-broad",
            "turn-moderate",
            "river-paired",
            "river-monotone",
            "turn-draws",
        ]
    } else {
        vec![options.workload.as_str()]
    };
    let mut missed_target = false;
    for (i, name) in workloads.iter().enumerate() {
        match pool.install(|| run(name, &options)) {
            Ok(row) => {
                emit(&row, &options, i);
                if row.time_budget_reached || (!options.fixed && !row.converged) {
                    eprintln!(
                        "{name}: solve budget/cap reached; target is {} chips",
                        options.target
                    );
                    missed_target = true;
                }
            }
            Err(error) => {
                eprintln!("error: {error}");
                return std::process::ExitCode::from(1);
            }
        }
    }
    std::process::ExitCode::from(if missed_target { 2 } else { 0 })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dry_flop_independent_audit_fits_work_guard() {
        let board: Vec<_> = ["Ks", "7d", "2c"]
            .iter()
            .map(|c| c.parse::<Card>().unwrap())
            .collect();
        let oop = sorted_combos("AA,AKs", &board).unwrap();
        let ip = sorted_combos("QQ,KQs", &board).unwrap();
        let cfg =
            GameConfig::new(board, Chips::whole(100), Chips::whole(100)).with_bet_sizes([0.5]);
        let tree = build_tree_bounded(&cfg, MAX_DECISION_NODES).unwrap();
        assert_eq!([oop.len(), ip.len()], [9, 9]);
        // Four decisions per live street (OOP, IP after check, and the
        // two fold/call responses). Three flop continuations reach the turn.
        // Five histories reach a live river: three after flop check-check,
        // plus turn check-check after either flop bet-call. The other four
        // turn bet-calls are all-in and deal the river without forced checks.
        let expected_nodes = 4 + 49 * (3 * 4) + 49 * 48 * (5 * 4);
        assert_eq!(tree.num_decision_nodes, expected_nodes);
        assert!(tree.num_decision_nodes * oop.len() * ip.len() <= MAX_REFERENCE_WORK);
    }
}