stochastic-search 0.1.2

Planning under probabilistic outcomes for MDPs and POMDPs: LAO*, iLAO*, CG-iLAO*, RTDP, LRTDP, BRTDP, FRTDP, VPI-RTDP, POMCP, DESPOT and multi-objective MOLAO*, iMOLAO* and MOLRTDP
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
//! Determinized sparse partially observable trees (DESPOT; Somani, Ye, Hsu and Lee 2013;
//! Ye, Somani, Hsu and Lee 2017): anytime regularized search over a tree built from `K`
//! sampled scenarios, guided by upper and lower bounds.
//!
//! ```mermaid
//! graph TD
//!     A[sample K scenarios: start state and random stream] --> B{root gap above target?}
//!     B -- yes --> C[explore: action by upper bound, child by excess uncertainty]
//!     C --> D[expand leaves; prune blocked nodes; fix nodes beyond depth D]
//!     D --> E[back up bounds to the root]
//!     E --> B
//!     B -- no --> F[recommend the root action with the best lower bound]
//! ```

mod tree;

use core::mem;

use alloc::vec::Vec;

use crate::budget::{Budget, Limits, TreeStats};
use crate::despot::tree::{Branch, Node, ROOT, Tree, UNEXPANDED};
use crate::error::Error;
use crate::observer::{Event, Observer};
use crate::pomdp::{
    Plan, Pomdp, RolloutPolicy, below, check_horizon, check_reward, collect_actions,
};
use crate::rng::{SplitMix64, derive_seed};
use crate::solution::Status;

/// Settings of [`despot`].
///
/// The struct is `#[non_exhaustive]`: outside this crate, build it from `default()` with
/// the `with_*` methods; fields stay readable and assignable.
///
/// ```
/// use stochastic_search::{DespotConfig, Limits};
///
/// let config = DespotConfig::default()
///     .with_scenarios(200)
///     .with_regularization(0.1)
///     .with_budget(Limits { max_trials: Some(5_000), ..DespotConfig::DEFAULT_LIMITS });
/// # let _ = config;
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DespotConfig<B = Limits, O = ()> {
    /// The discount factor `gamma`, in `(0, 1]`. Default `0.95`.
    pub discount: f64,
    /// The number of sampled scenarios `K`, at least `1`. Default `500`, as in the paper.
    pub scenarios: usize,
    /// The regularization constant `lambda`, finite and non-negative: the utility charged
    /// per tree node, which trades tree size against overfitting to the scenarios. In
    /// reward units. Default `0`, as in the reference implementation.
    pub regularization: f64,
    /// The target factor `xi` of the excess uncertainty, in `[0, 1)`: each exploration aims
    /// to shrink the root gap to `xi` times its current size. At `1` the root itself would
    /// have no excess uncertainty and no exploration would leave it. Default `0.95`, as in the
    /// paper.
    pub xi: f64,
    /// The depth `D` of the tree: nodes deeper than `D` follow the default policy, and
    /// default policy simulations take their last step at depth `D`, so every scenario
    /// plays at most `D + 1` steps. At least `1`. Default `90`, as in the paper.
    pub max_depth: usize,
    /// Stop once the root gap `mu(b0) - ell(b0)` is at most this, finite and non-negative.
    /// Default `1e-6`.
    pub target_gap: f64,
    /// Seed of the scenarios. A seed reproduces a call exactly. Default `0`.
    pub seed: u64,
    /// Stops the search. Asked before every exploration with the [`TreeStats`] so far.
    /// Default [`DespotConfig::DEFAULT_LIMITS`].
    pub budget: B,
    /// Receives [`Event::TreeProgress`] every [`DespotConfig::progress_interval`]
    /// simulations. Default `()`, which ignores events at no cost.
    pub observer: O,
    /// Emit [`Event::TreeProgress`] every this many simulations; `None` never. At least
    /// `1`. Default `Some(1_000)`; ignored by the default observer.
    pub progress_interval: Option<u64>,
}

impl DespotConfig {
    /// The default budget: `10^3` explorations, at most `10^6` tree nodes.
    pub const DEFAULT_LIMITS: Limits = Limits {
        max_trials: Some(1_000),
        ..Limits::DEFAULT
    };
}

impl Default for DespotConfig {
    fn default() -> Self {
        Self {
            discount: 0.95,
            scenarios: 500,
            regularization: 0.0,
            xi: 0.95,
            max_depth: 90,
            target_gap: 1e-6,
            seed: 0,
            budget: Self::DEFAULT_LIMITS,
            observer: (),
            progress_interval: Some(1_000),
        }
    }
}

impl<B, O> DespotConfig<B, O> {
    /// Returns the same configuration with another [`DespotConfig::discount`].
    #[must_use]
    pub fn with_discount(self, discount: f64) -> Self {
        Self { discount, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::scenarios`].
    #[must_use]
    pub fn with_scenarios(self, scenarios: usize) -> Self {
        Self { scenarios, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::regularization`].
    #[must_use]
    pub fn with_regularization(self, regularization: f64) -> Self {
        Self {
            regularization,
            ..self
        }
    }

    /// Returns the same configuration with another [`DespotConfig::xi`].
    #[must_use]
    pub fn with_xi(self, xi: f64) -> Self {
        Self { xi, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::max_depth`].
    #[must_use]
    pub fn with_max_depth(self, max_depth: usize) -> Self {
        Self { max_depth, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::target_gap`].
    #[must_use]
    pub fn with_target_gap(self, target_gap: f64) -> Self {
        Self { target_gap, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::seed`].
    #[must_use]
    pub fn with_seed(self, seed: u64) -> Self {
        Self { seed, ..self }
    }

    /// Returns the same configuration with another [`DespotConfig::progress_interval`].
    #[must_use]
    pub fn with_progress_interval(self, progress_interval: Option<u64>) -> Self {
        Self {
            progress_interval,
            ..self
        }
    }

    /// Returns the same configuration with another budget.
    #[must_use]
    pub fn with_budget<B2: Budget<TreeStats>>(self, budget: B2) -> DespotConfig<B2, O> {
        DespotConfig {
            discount: self.discount,
            scenarios: self.scenarios,
            regularization: self.regularization,
            xi: self.xi,
            max_depth: self.max_depth,
            target_gap: self.target_gap,
            seed: self.seed,
            budget,
            observer: self.observer,
            progress_interval: self.progress_interval,
        }
    }

    /// Returns the same configuration with another observer.
    #[must_use]
    pub fn with_observer<O2: Observer>(self, observer: O2) -> DespotConfig<B, O2> {
        DespotConfig {
            discount: self.discount,
            scenarios: self.scenarios,
            regularization: self.regularization,
            xi: self.xi,
            max_depth: self.max_depth,
            target_gap: self.target_gap,
            seed: self.seed,
            budget: self.budget,
            observer,
            progress_interval: self.progress_interval,
        }
    }

    /// Checks the numeric settings.
    ///
    /// # Events
    ///
    /// [`DespotConfig::observer`] receives [`Event::TreeProgress`] every
    /// [`DespotConfig::progress_interval`] explorations, with the root lower bound and the root
    /// gap. The default observer `()` costs nothing, and an observer never changes the plan.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfig`] for a setting outside its documented range.
    fn validate<S>(&self) -> Result<(), Error<S>> {
        check_horizon(self.discount, self.max_depth)?;
        let reason = if self.scenarios == 0 {
            "scenarios must be at least 1"
        } else if !(self.regularization.is_finite() && self.regularization >= 0.0) {
            "regularization must be finite and non-negative"
        } else if !(0.0..1.0).contains(&self.xi) {
            "xi must lie in [0, 1)"
        } else if !(self.target_gap.is_finite() && self.target_gap >= 0.0) {
            "target_gap must be finite and non-negative"
        } else if self.progress_interval == Some(0) {
            "progress_interval must be at least 1"
        } else {
            return Ok(());
        };

        Err(Error::InvalidConfig { reason })
    }
}

/// Plans one action from the particle belief `belief` with anytime regularized DESPOT.
///
/// One [`Despot::plan`] on a fresh planner; keep a [`Despot`] to reuse its tree between
/// decisions.
///
/// Samples `K` scenarios ([`DespotConfig::scenarios`]): a start state drawn from `belief`
/// and a random stream per step, so every scenario plays out deterministically. The tree
/// branches on actions and on the observations the scenarios produce. Each node keeps an
/// upper bound (`upper`, seeded per scenario state) and a lower bound (the return of the
/// default policy `default`, simulated along each scenario) on its value, and their
/// regularized counterparts, which charge [`DespotConfig::regularization`] per node.
///
/// Each exploration (Ye et al. 2017, Algorithm 2) walks down from the root: it expands
/// leaves, takes the action with the best regularized upper bound, and follows the child
/// with the largest excess uncertainty, until that uncertainty is gone, the node is pruned
/// (an ancestor's gap no longer pays for the nodes below it) or the depth limit fixes the
/// node to the default policy. The bounds are then backed up to the root. The search stops
/// when the root gap reaches [`DespotConfig::target_gap`] ([`Status::Converged`]) or the
/// budget runs out ([`Status::BudgetExhausted`]).
///
/// The recommendation is the root action with the best regularized lower bound, or the
/// default policy's action (in the first scenario) if no action beats following the
/// default policy. [`Plan::value`] is the root's regularized lower bound `ell(b0)`: the
/// average discounted return of the best policy tree found, over the sampled scenarios,
/// minus `lambda` per tree node. It is an estimate from `K` scenarios, not a bound on the
/// true value.
///
/// # Bounds
///
/// `upper(s)` must bound the optimal discounted return from state `s` from above, and should
/// not loosen along a step (`upper(s) >= r + gamma * upper(s')`); otherwise the bounds lose
/// their meaning, though the search still returns. A node's averaged upper bound is raised
/// to its default-policy value if it falls below it. `R_max / (1 - gamma)` always works;
/// tighter bounds prune more.
///
/// # Errors
///
/// Returns [`Error::InvalidConfig`] for an invalid configuration, [`Error::EmptyBelief`] for
/// an empty `belief`, [`Error::NoActions`] if the POMDP has no actions,
/// [`Error::InvalidReward`] if a sampled reward is not finite, and
/// [`Error::InvalidHeuristic`] if `upper` returns NaN or an infinity.
///
/// # Panics
///
/// Panics if more than `u32::MAX` tree nodes or scenarios are stored.
///
/// # Example
///
/// The hidden coin from [`Pomdp`], with the bound `10`: peeking first is better than a blind
/// call.
///
/// ```
/// # use rand_core::Rng;
/// # use stochastic_search::{Pomdp, Step, unit_interval};
/// # struct Coin;
/// # impl Pomdp for Coin {
/// #     type State = bool;
/// #     type Action = &'static str;
/// #     type Observation = Option<bool>;
/// #     fn actions(&self, mut emit: impl FnMut(&'static str)) { emit("peek"); emit("heads"); emit("tails"); }
/// #     fn step<R: Rng + ?Sized>(&self, heads: &bool, action: &&'static str, rng: &mut R)
/// #         -> Step<bool, Option<bool>> {
/// #         if *action == "peek" {
/// #             let truthful = unit_interval(rng) < 0.9;
/// #             Step::new(*heads, Some(*heads == truthful), -1.0)
/// #         } else {
/// #             let right = *heads == (*action == "heads");
/// #             Step::new(*heads, None, if right { 10.0 } else { -10.0 }).terminal()
/// #         }
/// #     }
/// # }
/// use stochastic_search::{DespotConfig, UniformRandom, despot};
///
/// let config = DespotConfig::default().with_scenarios(100).with_max_depth(10);
/// let plan = despot(&Coin, &[true, false], UniformRandom, |_: &bool| 10.0, config)?;
///
/// assert_eq!(plan.action, "peek");
/// # Ok::<(), stochastic_search::Error<bool>>(())
/// ```
pub fn despot<P, R, U, B, O>(
    pomdp: &P,
    belief: &[P::State],
    default: R,
    upper: U,
    config: DespotConfig<B, O>,
) -> Result<Plan<P::Action>, Error<P::State>>
where
    P: Pomdp,
    P::State: Clone,
    P::Action: Clone,
    P::Observation: PartialEq,
    R: RolloutPolicy<P::State>,
    U: FnMut(&P::State) -> f64,
    B: Budget<TreeStats>,
    O: Observer,
{
    Despot::new(pomdp, belief, default, upper, config)?.plan()
}

/// A DESPOT planner that keeps its tree between decisions.
///
/// [`despot`] is one [`Despot::plan`] on a fresh planner. Keeping the planner lets
/// [`Despot::advance`] make the belief node after the action taken and the observation
/// received the new root. Its scenarios become the new belief (DESPOT's determinized
/// particle filter, with fewer scenarios than `K`), and its subtree is kept: the branches,
/// observations and rewards stay valid, since every scenario keeps its random stream.
///
/// Tree reuse is this crate's design: the DESPOT papers search from the updated belief at
/// every step and do not discuss reusing the tree. Re-rooting re-simulates the default policy of every kept node
/// (the horizon moves with the root) and recomputes all bounds relative to the new root, so
/// the kept tree equals what exploring from the new root would have built, at the cost of
/// one default-policy simulation per kept scenario and node. With few scenarios left,
/// starting a new planner from an updated belief (for example from
/// [`update_belief`](crate::update_belief())) gives better estimates.
///
/// # Example
///
/// ```
/// # use rand_core::Rng;
/// # use stochastic_search::{Pomdp, Step, unit_interval};
/// # struct Coin;
/// # impl Pomdp for Coin {
/// #     type State = bool;
/// #     type Action = &'static str;
/// #     type Observation = Option<bool>;
/// #     fn actions(&self, mut emit: impl FnMut(&'static str)) { emit("peek"); emit("heads"); emit("tails"); }
/// #     fn step<R: Rng + ?Sized>(&self, heads: &bool, action: &&'static str, rng: &mut R)
/// #         -> Step<bool, Option<bool>> {
/// #         if *action == "peek" {
/// #             let truthful = unit_interval(rng) < 0.9;
/// #             Step::new(*heads, Some(*heads == truthful), -1.0)
/// #         } else {
/// #             let right = *heads == (*action == "heads");
/// #             Step::new(*heads, None, if right { 10.0 } else { -10.0 }).terminal()
/// #         }
/// #     }
/// # }
/// use stochastic_search::{Despot, DespotConfig, UniformRandom};
///
/// let config = DespotConfig::default().with_scenarios(100).with_max_depth(5);
/// let mut planner = Despot::new(&Coin, &[true, false], UniformRandom, |_: &bool| 10.0, config)?;
/// assert_eq!(planner.plan()?.action, "peek");
///
/// // Peeked and saw heads: the root moves to that belief node, whose scenarios are about
/// // 90% heads, and planning continues from its subtree.
/// planner.advance(&"peek", &Some(true))?;
/// let heads = planner.belief().filter(|&&heads| heads).count();
/// assert!(heads * 10 > planner.belief().len() * 8);
/// let plan = planner.plan()?;
/// # let _ = plan;
/// # Ok::<(), stochastic_search::Error<bool>>(())
/// ```
pub struct Despot<'a, P: Pomdp, R, U, B = Limits, O = ()> {
    /// The model.
    pomdp: &'a P,
    /// The actions, in emission order.
    actions: Vec<P::Action>,
    /// The tree.
    tree: Tree<P::State, P::Observation>,
    /// The default policy.
    default: R,
    /// The per-state upper bound.
    upper: U,
    /// The caller's budget.
    budget: B,
    /// The caller's observer.
    observer: O,
    /// Explorations between progress events.
    progress_interval: Option<u64>,
    /// The counters so far.
    stats: TreeStats,
    /// The seed the scenario streams derive from.
    seed: u64,
    /// The discount factor.
    discount: f64,
    /// `gamma^d` for `d` in `0..=max_depth + 1`.
    powers: Vec<f64>,
    /// `K` as a float.
    scenarios: f64,
    /// The regularization constant `lambda`.
    lambda: f64,
    /// The excess uncertainty factor `xi`.
    xi: f64,
    /// The depth `D`.
    max_depth: usize,
    /// The target root gap.
    target_gap: f64,
    /// The depth of the current root: `0` until [`Despot::advance`] moves it. Discounting,
    /// scenario weights and the depth limit count from here; random streams use absolute
    /// depths.
    root_depth: usize,
    /// `K`, the number of scenarios a fresh root samples.
    scenario_count: usize,
    /// Set when [`Despot::advance`] met a history the tree never saw: the tree no longer
    /// matches the agent's belief, so [`Despot::plan`] refuses until [`Despot::reset`].
    lost: bool,
}

impl<'a, P, R, U, B, O> Despot<'a, P, R, U, B, O>
where
    P: Pomdp,
    P::State: Clone,
    P::Action: Clone,
    P::Observation: PartialEq,
    R: RolloutPolicy<P::State>,
    U: FnMut(&P::State) -> f64,
    B: Budget<TreeStats>,
    O: Observer,
{
    /// Validates the input, samples the scenarios and initializes the root.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidConfig`] for an invalid configuration,
    /// [`Error::EmptyBelief`] for an empty `belief`, [`Error::NoActions`] if the POMDP has
    /// no actions, and the errors of [`despot`] for bad model output at the root.
    pub fn new(
        pomdp: &'a P,
        belief: &[P::State],
        default: R,
        upper: U,
        config: DespotConfig<B, O>,
    ) -> Result<Self, Error<P::State>> {
        config.validate()?;
        if belief.is_empty() {
            return Err(Error::EmptyBelief);
        }

        #[expect(
            clippy::cast_precision_loss,
            reason = "scenario counts beyond 2^53 are far outside any memory budget"
        )]
        let scenarios = config.scenarios as f64;
        let mut search = Self {
            pomdp,
            actions: collect_actions(pomdp)?,
            tree: Tree {
                nodes: Vec::new(),
                branches: Vec::new(),
            },
            default,
            upper,
            budget: config.budget,
            observer: config.observer,
            progress_interval: config.progress_interval,
            stats: TreeStats::default(),
            seed: config.seed,
            discount: config.discount,
            powers: powers(config.discount, config.max_depth + 1),
            scenarios,
            lambda: config.regularization,
            xi: config.xi,
            max_depth: config.max_depth,
            target_gap: config.target_gap,
            root_depth: 0,
            scenario_count: config.scenarios,
            lost: false,
        };

        let particles = search.sample_scenarios(belief, config.scenarios);
        search.add_node(None, 0, particles)?;

        Ok(search)
    }

    /// A planner whose root at `depth` holds exactly `scenarios`, as a re-rooted tree's
    /// root would; for checking re-rooting against a fresh build.
    #[cfg(test)]
    fn with_root(
        pomdp: &'a P,
        scenarios: Particles<P::State>,
        depth: usize,
        default: R,
        upper: U,
        config: DespotConfig<B, O>,
    ) -> Result<Self, Error<P::State>> {
        let belief: Vec<P::State> = scenarios.iter().map(|(_, state)| state.clone()).collect();
        let mut search = Self::new(pomdp, &belief, default, upper, config)?;
        search.tree.nodes.clear();
        search.root_depth = depth;
        search.scenarios = count_of(&scenarios);
        search.add_node(None, depth, scenarios)?;

        Ok(search)
    }

    /// Draws the start states of `count` scenarios uniformly from `belief`.
    ///
    /// # Panics
    ///
    /// Panics if `count` exceeds `u32::MAX`.
    fn sample_scenarios(&self, belief: &[P::State], count: usize) -> Vec<(u32, P::State)> {
        let mut rng = SplitMix64::new(self.seed);

        (0..count)
            .map(|k| {
                let id = u32::try_from(k).expect("at most u32::MAX scenarios");
                (id, belief[below(&mut rng, belief.len())].clone())
            })
            .collect()
    }

    /// Explores from the current root until its gap reaches the target or the budget runs
    /// out, and recommends an action as [`despot`] does.
    ///
    /// The counters of the returned [`Plan`] count this call only, except
    /// [`TreeStats::nodes`], the size of the whole tree; the budget sees the same counters.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] or [`Error::InvalidHeuristic`] for bad model output,
    /// and [`Error::UnseenHistory`] after a failed [`Despot::advance`] until
    /// [`Despot::reset`].
    ///
    /// # Panics
    ///
    /// Panics if more than `u32::MAX` tree nodes or branches are stored.
    pub fn plan(&mut self) -> Result<Plan<P::Action>, Error<P::State>> {
        if self.lost {
            return Err(Error::UnseenHistory);
        }

        self.stats = TreeStats::default();
        let status = self.run()?;

        Ok(self.recommend(status))
    }

    /// Makes the belief node after `action` and `observation` the new root, keeping its
    /// subtree and recomputing it relative to the new root (see [`Despot`]).
    ///
    /// If the tree has no such node (the root was never expanded, `action` is not one of
    /// the POMDP's actions, or no scenario produced `observation`), the planner has no
    /// belief for the agent's real history. Unlike [`Pomcp::advance`](crate::Pomcp::advance),
    /// which can start over because its [`Pomcp::plan`](crate::Pomcp::plan) takes the belief,
    /// a DESPOT planner holds its belief in the tree, and keeping the old root would plan
    /// for the wrong history. So this returns [`Error::UnseenHistory`], and [`Despot::plan`]
    /// keeps returning it until [`Despot::reset`] supplies a belief (for example from
    /// [`update_belief`](crate::update_belief())).
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnseenHistory`] as described above, and [`Error::InvalidReward`] for
    /// bad rewards in the re-simulated default policy.
    pub fn advance(
        &mut self,
        action: &P::Action,
        observation: &P::Observation,
    ) -> Result<(), Error<P::State>>
    where
        P::Action: PartialEq,
    {
        let Some(child) = self.child_of_root(action, observation) else {
            self.lost = true;
            return Err(Error::UnseenHistory);
        };

        self.tree = core::mem::replace(
            &mut self.tree,
            Tree {
                nodes: Vec::new(),
                branches: Vec::new(),
            },
        )
        .into_subtree(child, self.actions.len());
        self.root_depth = self.tree.node(ROOT).depth;
        #[expect(
            clippy::cast_precision_loss,
            reason = "scenario counts beyond 2^53 are far outside any memory budget"
        )]
        let scenarios = self.tree.node(ROOT).scenarios.len() as f64;
        self.scenarios = scenarios;
        self.recompute_bounds()?;

        Ok(())
    }

    /// Drops the tree and starts over from `belief` with `K` fresh scenarios, as
    /// [`Despot::new`] does. Clears the state left by a failed [`Despot::advance`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::EmptyBelief`] for an empty `belief`, and the errors of [`despot`]
    /// for bad model output at the root.
    pub fn reset(&mut self, belief: &[P::State]) -> Result<(), Error<P::State>> {
        if belief.is_empty() {
            return Err(Error::EmptyBelief);
        }

        self.tree.nodes.clear();
        self.tree.branches.clear();
        self.root_depth = 0;
        #[expect(
            clippy::cast_precision_loss,
            reason = "scenario counts beyond 2^53 are far outside any memory budget"
        )]
        let scenarios = self.scenario_count as f64;
        self.scenarios = scenarios;
        let particles = self.sample_scenarios(belief, self.scenario_count);
        self.add_node(None, 0, particles)?;
        self.lost = false;

        Ok(())
    }

    /// The number of belief nodes in the tree.
    #[must_use]
    pub fn tree_size(&self) -> usize {
        self.tree.nodes.len()
    }

    /// The scenarios at the root, with their states: the current belief.
    pub fn belief(&self) -> impl ExactSizeIterator<Item = &P::State> {
        self.tree
            .node(ROOT)
            .scenarios
            .iter()
            .map(|(_, state)| state)
    }

    /// The root's child after `action` and `observation`, if the tree has it.
    fn child_of_root(&self, action: &P::Action, observation: &P::Observation) -> Option<u32>
    where
        P::Action: PartialEq,
    {
        let position = self.actions.iter().position(|known| known == action)?;
        if self.tree.node(ROOT).first_branch == UNEXPANDED {
            return None;
        }

        self.tree.branches_of(ROOT, self.actions.len())[position]
            .children
            .iter()
            .find(|(seen, _)| seen == observation)
            .map(|&(_, child)| child)
    }

    /// Re-initializes every node relative to the current root: default policy values over
    /// the new horizon, initial bounds with the new scenario weights and discounting, no
    /// fixed nodes; then backs up every expanded node, children first.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] for bad rewards in the re-simulated default policy.
    fn recompute_bounds(&mut self) -> Result<(), Error<P::State>> {
        for id in 0..self.tree.nodes.len() {
            let id = u32::try_from(id).expect("at most u32::MAX nodes");
            let scenarios = core::mem::take(&mut self.tree.node_mut(id).scenarios);
            let depth = self.tree.node(id).depth;
            let result = self.default_value(&scenarios, depth);
            self.tree.node_mut(id).scenarios = scenarios;
            let default_value = result?;
            let heuristic_upper = self.tree.node(id).heuristic_upper;
            let count = count_of(&self.tree.node(id).scenarios);
            let initial = self.initial_bounds(depth, default_value, heuristic_upper, count);
            let node = self.tree.node_mut(id);
            node.default_value = default_value;
            node.upper = initial.upper;
            node.default_utility = initial.ell;
            node.mu = initial.mu;
            node.ell = initial.ell;
            node.fixed = false;
        }

        for id in (0..self.tree.nodes.len()).rev() {
            self.back_up(u32::try_from(id).expect("at most u32::MAX nodes"));
        }

        Ok(())
    }

    /// Explores and backs up until the root gap reaches the target or the budget runs out.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] or [`Error::InvalidHeuristic`] for bad model output.
    fn run(&mut self) -> Result<Status, Error<P::State>> {
        while self.gap(ROOT) > self.target_gap {
            self.stats.nodes = self.tree.nodes.len() as u64;
            if self.budget.exhausted(&self.stats) {
                return Ok(Status::BudgetExhausted);
            }

            self.stats.simulations += 1;
            let leaf = self.explore()?;
            self.back_up_path(leaf);
            self.report_progress();
        }

        self.stats.nodes = self.tree.nodes.len() as u64;

        Ok(Status::Converged)
    }

    /// One exploration from the root (Ye et al. 2017, Algorithm 2). Returns the node where
    /// it stopped.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] or [`Error::InvalidHeuristic`] for bad model output.
    fn explore(&mut self) -> Result<u32, Error<P::State>> {
        let mut node = ROOT;
        loop {
            if self.tree.node(node).depth - self.root_depth > self.max_depth {
                self.tree.make_default(node);
                return Ok(node);
            }

            if self.tree.node(node).fixed
                || self.excess_uncertainty(node) <= 0.0
                || self.prune(node)
            {
                return Ok(node);
            }

            if self.tree.node(node).first_branch == UNEXPANDED {
                self.expand(node)?;
            }

            let Some(child) = self.most_uncertain_child(node) else {
                return Ok(node);
            };

            node = child;
        }
    }

    /// The child of `node`'s best action by regularized upper bound with the largest excess
    /// uncertainty; `None` if every scenario ended the episode under that action.
    fn most_uncertain_child(&self, node: u32) -> Option<u32> {
        let (action, _) = self.best_action(node, |n| n.mu);
        let branch = &self.tree.branches_of(node, self.actions.len())[action];

        branch
            .children
            .iter()
            .map(|&(_, child)| (child, self.excess_uncertainty(child)))
            .fold(None, |best: Option<(u32, f64)>, (child, e)| match best {
                Some((_, best_e)) if best_e >= e => best,
                _ => Some((child, e)),
            })
            .map(|(child, _)| child)
    }

    /// The gap `mu(b) - ell(b)` of a node.
    fn gap(&self, node: u32) -> f64 {
        let node = self.tree.node(node);

        node.mu - node.ell
    }

    /// The excess uncertainty `E(b) = eps(b) - |Phi_b| / K * xi * eps(b0)`.
    fn excess_uncertainty(&self, node: u32) -> f64 {
        self.gap(node) - self.weight(node) * self.xi * self.gap(ROOT)
    }

    /// The scenario fraction `|Phi_b| / K` of a node.
    fn weight(&self, node: u32) -> f64 {
        #[expect(
            clippy::cast_precision_loss,
            reason = "scenario counts beyond 2^53 are far outside any memory budget"
        )]
        let count = self.tree.node(node).scenarios.len() as f64;

        count / self.scenarios
    }

    /// Prunes the path ending at `node` (Ye et al. 2017, Algorithm 4): fixes every node to
    /// the default policy that an ancestor blocks, from `node` upwards until one is not
    /// blocked, backing up from each. Returns whether `node` was blocked.
    fn prune(&mut self, node: u32) -> bool {
        let mut current = node;
        let mut blocked = false;
        while self.is_blocked(current) {
            self.tree.make_default(current);
            self.back_up_path(current);
            blocked = true;
            match self.tree.node(current).parent {
                Some(parent) => current = parent,
                None => break,
            }
        }

        blocked
    }

    /// Returns `true` if a strict ancestor `b'` of `node` cannot pay for the nodes down to
    /// `node`: `|Phi_b'| / K * gamma^depth(b') * (U(b') - L0(b')) <= lambda * (depth(node) -
    /// depth(b'))` (Ye et al. 2017, eq. 12).
    fn is_blocked(&self, node: u32) -> bool {
        let depth = self.tree.node(node).depth;
        let mut ancestor = self.tree.node(node).parent;
        while let Some(id) = ancestor {
            let candidate = self.tree.node(id);
            let potential = self.weight(id)
                * self.power(candidate.depth)
                * (candidate.upper - candidate.default_value);
            #[expect(
                clippy::cast_precision_loss,
                reason = "depths are bounded by max_depth, far below 2^53"
            )]
            let cost = self.lambda * (depth - candidate.depth) as f64;
            if potential <= cost {
                return true;
            }

            ancestor = candidate.parent;
        }

        false
    }

    /// Creates the branches of `node`: steps every scenario with every action, groups the
    /// successors by observation and initializes the children.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] or [`Error::InvalidHeuristic`] for bad model output.
    fn expand(&mut self, node: u32) -> Result<(), Error<P::State>> {
        let scenarios = mem::take(&mut self.tree.node_mut(node).scenarios);
        let depth = self.tree.node(node).depth;
        let first = u32::try_from(self.tree.branches.len()).expect("at most u32::MAX branches");

        let mut result = Ok(());
        for position in 0..self.actions.len() {
            result = self.add_branch(node, depth, &scenarios, position);
            if result.is_err() {
                break;
            }
        }

        let entry = self.tree.node_mut(node);
        entry.scenarios = scenarios;
        if result.is_ok() {
            entry.first_branch = first;
        } else {
            self.tree.branches.truncate(first as usize);
        }

        result
    }

    /// Appends the branch of the action at `position` below `node` and creates its children.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] or [`Error::InvalidHeuristic`] for bad model output.
    fn add_branch(
        &mut self,
        node: u32,
        depth: usize,
        scenarios: &[(u32, P::State)],
        position: usize,
    ) -> Result<(), Error<P::State>> {
        let mut reward_sum = 0.0;
        let mut groups: Vec<(P::Observation, Particles<P::State>)> = Vec::new();
        for (scenario, state) in scenarios {
            let mut rng = self.stream(*scenario, depth, false);
            let step = self.pomdp.step(state, &self.actions[position], &mut rng);
            self.stats.steps += 1;
            check_reward(state, step.reward)?;
            reward_sum += step.reward;
            if step.terminal {
                continue;
            }

            match groups
                .iter_mut()
                .find(|(seen, _)| *seen == step.observation)
            {
                Some((_, group)) => group.push((*scenario, step.state)),
                None => groups.push((step.observation, alloc::vec![(*scenario, step.state)])),
            }
        }

        let mut children = Vec::with_capacity(groups.len());
        for (observation, group) in groups {
            children.push((observation, self.add_node(Some(node), depth + 1, group)?));
        }

        self.tree.branches.push(Branch {
            reward_sum,
            children,
        });

        Ok(())
    }

    /// Emits [`Event::TreeProgress`] if one is due after the current exploration.
    fn report_progress(&mut self) {
        let due = self
            .progress_interval
            .is_some_and(|interval| self.stats.simulations % interval == 0);
        if O::ENABLED && due {
            self.stats.nodes = self.tree.nodes.len() as u64;
            let root = self.tree.node(ROOT);
            let (value, gap) = (root.ell, root.mu - root.ell);
            self.observer.observe(Event::TreeProgress {
                stats: self.stats,
                value,
                gap: Some(gap),
            });
        }
    }

    /// Adds a node at `depth` with `scenarios` (never empty) and initializes its bounds
    /// (Ye et al. 2017, Section 4.2.1).
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] for a bad reward in a default policy simulation and
    /// [`Error::InvalidHeuristic`] for a NaN or infinite upper bound.
    fn add_node(
        &mut self,
        parent: Option<u32>,
        depth: usize,
        scenarios: Vec<(u32, P::State)>,
    ) -> Result<u32, Error<P::State>> {
        let default_value = self.default_value(&scenarios, depth)?;
        let mut upper_sum = 0.0;
        for (_, state) in &scenarios {
            let bound = (self.upper)(state);
            if !bound.is_finite() {
                return Err(Error::InvalidHeuristic {
                    state: state.clone(),
                });
            }

            upper_sum += bound;
        }

        let heuristic_upper = upper_sum / count_of(&scenarios);
        self.stats.depth = self.stats.depth.max((depth - self.root_depth) as u64);
        let initial =
            self.initial_bounds(depth, default_value, heuristic_upper, count_of(&scenarios));

        Ok(self.tree.push(Node {
            depth,
            parent,
            scenarios,
            heuristic_upper,
            upper: initial.upper,
            default_value,
            default_utility: initial.ell,
            mu: initial.mu,
            ell: initial.ell,
            first_branch: UNEXPANDED,
            fixed: false,
        }))
    }

    /// The average default-policy return of `scenarios` from `depth`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] for a non-finite reward.
    fn default_value(
        &mut self,
        scenarios: &[(u32, P::State)],
        depth: usize,
    ) -> Result<f64, Error<P::State>> {
        let mut sum = 0.0;
        for (scenario, state) in scenarios {
            sum += self.simulate_default(*scenario, state.clone(), depth)?;
        }

        Ok(sum / count_of(scenarios))
    }

    /// The initial bounds of a node at `depth` with `count` scenarios (Ye et al. 2017,
    /// Section 4.2.1), relative to the current root: `U` is the heuristic average raised to
    /// the default value, `ell = l0` the scaled default value, `mu` the larger of `l0` and the
    /// scaled `U` minus `lambda`.
    fn initial_bounds(
        &self,
        depth: usize,
        default_value: f64,
        heuristic_upper: f64,
        count: f64,
    ) -> Bounds {
        let upper = heuristic_upper.max(default_value);
        let relative = (depth - self.root_depth).min(self.max_depth + 1);
        let scale = count / self.scenarios * self.powers[relative];
        let default_utility = scale * default_value;

        Bounds {
            mu: default_utility.max(scale * upper - self.lambda),
            ell: default_utility,
            upper,
        }
    }

    /// `gamma^(depth - root depth)`.
    fn power(&self, depth: usize) -> f64 {
        self.powers[depth - self.root_depth]
    }

    /// Simulates the default policy along `scenario` from `state` at `depth` until the
    /// episode ends or through depth `D` (the last depth the tree steps from), and returns
    /// the return discounted from `depth`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidReward`] for a non-finite reward.
    fn simulate_default(
        &mut self,
        scenario: u32,
        mut state: P::State,
        depth: usize,
    ) -> Result<f64, Error<P::State>> {
        let mut total = 0.0;
        let mut weight = 1.0;
        for step_depth in depth..=self.root_depth + self.max_depth {
            let mut choice = self.stream(scenario, step_depth, true);
            let position = self.default.action(&state, self.actions.len(), &mut choice);
            let mut rng = self.stream(scenario, step_depth, false);
            let step = self.pomdp.step(&state, &self.actions[position], &mut rng);
            self.stats.steps += 1;
            check_reward(&state, step.reward)?;
            total += weight * step.reward;
            if step.terminal {
                break;
            }

            weight *= self.discount;
            state = step.state;
        }

        Ok(total)
    }

    /// The random stream of `scenario` at `depth`: for the model's step, or for the default
    /// policy's choice (`policy`). Independent of the action and of the order of expansions,
    /// which is what makes a scenario deterministic.
    fn stream(&self, scenario: u32, depth: usize, policy: bool) -> SplitMix64 {
        let slot = 2 * depth as u64 + u64::from(policy);

        SplitMix64::new(derive_seed(self.seed, u64::from(scenario), slot))
    }

    /// Backs up the bounds of `node` and its ancestors (Ye et al. 2017, Algorithm 5).
    fn back_up_path(&mut self, node: u32) {
        let mut current = Some(node);
        while let Some(id) = current {
            self.back_up(id);
            self.stats.backups += 1;
            current = self.tree.node(id).parent;
        }
    }

    /// Recomputes `mu`, `ell` and `U` of an expanded, unfixed node from its branches.
    fn back_up(&mut self, id: u32) {
        let node = self.tree.node(id);
        if node.fixed || node.first_branch == UNEXPANDED {
            return;
        }

        let (mut mu, mut ell, mut upper) = (
            node.default_utility,
            node.default_utility,
            f64::NEG_INFINITY,
        );
        for branch in self.tree.branches_of(id, self.actions.len()) {
            let bounds = self.branch_bounds(id, branch);
            mu = mu.max(bounds.mu);
            ell = ell.max(bounds.ell);
            upper = upper.max(bounds.upper);
        }

        let node = self.tree.node_mut(id);
        node.mu = mu;
        node.ell = ell;
        node.upper = upper.max(node.default_value);
    }

    /// The bounds of taking `branch`'s action at `node`.
    fn branch_bounds(&self, node: u32, branch: &Branch<P::Observation>) -> Bounds {
        let entry = self.tree.node(node);
        #[expect(
            clippy::cast_precision_loss,
            reason = "scenario counts beyond 2^53 are far outside any memory budget"
        )]
        let count = entry.scenarios.len() as f64;
        let rho = self.power(entry.depth) * branch.reward_sum / self.scenarios - self.lambda;
        let mut bounds = Bounds {
            mu: rho,
            ell: rho,
            upper: branch.reward_sum / count,
        };

        for &(_, child) in &branch.children {
            let child = self.tree.node(child);
            #[expect(
                clippy::cast_precision_loss,
                reason = "scenario counts beyond 2^53 are far outside any memory budget"
            )]
            let share = child.scenarios.len() as f64 / count;
            bounds.mu += child.mu;
            bounds.ell += child.ell;
            bounds.upper += self.discount * share * child.upper;
        }

        bounds
    }

    /// The position of the best action at the expanded `node` by `key` of its branch
    /// bounds, ties to the first emitted, and that bound.
    fn best_action(&self, node: u32, key: impl Fn(&Bounds) -> f64) -> (usize, f64) {
        self.tree
            .branches_of(node, self.actions.len())
            .iter()
            .enumerate()
            .map(|(position, branch)| (position, key(&self.branch_bounds(node, branch))))
            .fold((0, f64::NEG_INFINITY), |best, candidate| {
                if candidate.1 > best.1 {
                    candidate
                } else {
                    best
                }
            })
    }

    /// The recommendation (Ye et al. 2017, Algorithm 6): the root action with the best
    /// regularized lower bound, unless following the default policy is at least as good.
    fn recommend(&mut self, status: Status) -> Plan<P::Action> {
        let root = self.tree.node(ROOT);
        let value = root.ell;
        let default_utility = root.default_utility;
        let position = if root.first_branch == UNEXPANDED {
            None
        } else {
            Some(self.best_action(ROOT, |b| b.ell))
                .filter(|&(_, ell)| ell >= default_utility)
                .map(|(position, _)| position)
        };

        let position = position.unwrap_or_else(|| self.default_action());

        Plan {
            action: self.actions[position].clone(),
            value,
            status,
            stats: self.stats,
        }
    }

    /// The default policy's choice at the root, in the first scenario.
    fn default_action(&mut self) -> usize {
        let (scenario, state) = self.tree.node(ROOT).scenarios[0].clone();
        let mut choice = self.stream(scenario, self.root_depth, true);

        self.default.action(&state, self.actions.len(), &mut choice)
    }
}

/// Scenarios with their states at one node.
type Particles<S> = Vec<(u32, S)>;

/// The number of scenarios in `scenarios`, as a float.
fn count_of<S>(scenarios: &[(u32, S)]) -> f64 {
    #[expect(
        clippy::cast_precision_loss,
        reason = "scenario counts beyond 2^53 are far outside any memory budget"
    )]
    let count = scenarios.len() as f64;

    count
}

/// The bounds of one action at one node.
#[derive(Debug, Clone, Copy)]
struct Bounds {
    /// `mu(b, a)`: the regularized upper bound.
    mu: f64,
    /// `ell(b, a)`: the regularized lower bound.
    ell: f64,
    /// `U(b, a)`: the unregularized upper bound on the average return.
    upper: f64,
}

/// `gamma^d` for `d` in `0..=last`.
fn powers(gamma: f64, last: usize) -> Vec<f64> {
    let mut powers = Vec::with_capacity(last + 1);
    let mut power = 1.0;
    for _ in 0..=last {
        powers.push(power);
        power *= gamma;
    }

    powers
}

#[cfg(test)]
mod tests {
    use rand_core::Rng;

    use super::{Despot, DespotConfig, ROOT};
    use crate::pomdp::{Pomdp, Step, UniformRandom};
    use crate::rng::unit_interval;

    /// A hidden coin: peek (cost 1, correct with probability 0.9), or call heads or tails
    /// (+10 if right, -10 if wrong, ends the episode).
    struct Coin;

    impl Pomdp for Coin {
        type State = bool;
        type Action = u8;
        type Observation = Option<bool>;

        fn actions(&self, mut emit: impl FnMut(u8)) {
            emit(0);
            emit(1);
            emit(2);
        }

        fn step<R: Rng + ?Sized>(
            &self,
            heads: &bool,
            action: &u8,
            rng: &mut R,
        ) -> Step<bool, Option<bool>> {
            if *action == 0 {
                let truthful = unit_interval(rng) < 0.9;
                return Step::new(*heads, Some(*heads == truthful), -1.0);
            }

            let right = *heads == (*action == 1);

            Step::new(*heads, None, if right { 10.0 } else { -10.0 }).terminal()
        }
    }

    /// Runs `explorations` explorations by hand and checks after each that `ell <= mu`
    /// holds at every node, that the root's upper bound never rises and, without
    /// regularization, that its lower bound never falls.
    fn check_bounds(regularization: f64, explorations: usize) {
        let config = DespotConfig {
            scenarios: 50,
            max_depth: 8,
            regularization,
            ..DespotConfig::default()
        };
        // 10 bounds every return and never loosens along a step (rewards are at most 10).
        let mut search = Despot::new(
            &Coin,
            &[true, false],
            UniformRandom,
            |_: &bool| 10.0,
            config,
        )
        .expect("valid input");

        let (mut mu, mut ell) = (search.tree.node(ROOT).mu, search.tree.node(ROOT).ell);
        for _ in 0..explorations {
            let leaf = search.explore().expect("valid model");
            search.back_up_path(leaf);

            for node in &search.tree.nodes {
                assert!(node.ell <= node.mu + 1e-12, "ell above mu");
            }

            let root = search.tree.node(ROOT);
            assert!(
                root.mu <= mu + 1e-12,
                "root mu rose from {mu} to {}",
                root.mu
            );
            if regularization == 0.0 {
                assert!(
                    root.ell >= ell - 1e-12,
                    "root ell fell from {ell} to {}",
                    root.ell
                );
            }

            (mu, ell) = (root.mu, root.ell);
        }

        assert!(search.tree.nodes.len() > 1, "the tree never grew");
    }

    /// The bound invariants hold without regularization.
    #[test]
    fn bounds_stay_ordered_and_monotone() {
        check_bounds(0.0, 200);
    }

    /// The bound invariants hold with regularization and pruning.
    #[test]
    fn bounds_stay_ordered_with_regularization() {
        check_bounds(0.5, 200);
    }

    /// Checks that bounds stay ordered at every node of `search`, and that every leaf equals
    /// a node built afresh in `fresh`, a search under the same root, bit for bit.
    fn assert_leaves_match_a_fresh_build<U, V>(
        search: &Despot<'_, Coin, UniformRandom, U>,
        fresh: &mut Despot<'_, Coin, UniformRandom, V>,
    ) where
        U: FnMut(&bool) -> f64,
        V: FnMut(&bool) -> f64,
    {
        for node in &search.tree.nodes {
            assert!(node.ell <= node.mu + 1e-12, "ell above mu");
            if node.first_branch != super::UNEXPANDED {
                continue;
            }

            let id = fresh
                .add_node(None, node.depth, node.scenarios.clone())
                .expect("valid model");
            let built = fresh.tree.node(id);
            assert_eq!(built.mu.to_bits(), node.mu.to_bits());
            assert_eq!(built.ell.to_bits(), node.ell.to_bits());
            assert_eq!(built.upper.to_bits(), node.upper.to_bits());
            assert_eq!(built.default_value.to_bits(), node.default_value.to_bits());
        }
    }

    /// Checks that replaying the kept expansions of `search`, re-rooted at depth 1, on a fresh
    /// tree under the new root, in id order, rebuilds the whole kept tree: same ids,
    /// structure and bounds, bit for bit.
    fn assert_replay_rebuilds_the_kept_tree<U: FnMut(&bool) -> f64>(
        search: &Despot<'_, Coin, UniformRandom, U>,
        config: DespotConfig,
    ) {
        let scenarios = search.tree.node(ROOT).scenarios.clone();
        let mut replay =
            Despot::with_root(&Coin, scenarios, 1, UniformRandom, |_: &bool| 10.0, config)
                .expect("valid input");
        for id in 0..search.tree.nodes.len() {
            let id = u32::try_from(id).expect("small tree");
            if search.tree.node(id).first_branch != super::UNEXPANDED {
                replay.expand(id).expect("valid model");
            }
        }

        for id in (0..replay.tree.nodes.len()).rev() {
            replay.back_up(u32::try_from(id).expect("small tree"));
        }

        assert_eq!(replay.tree.nodes.len(), search.tree.nodes.len());
        for (kept, built) in search.tree.nodes.iter().zip(&replay.tree.nodes) {
            assert_eq!(kept.parent, built.parent);
            assert_eq!(kept.first_branch, built.first_branch);
            assert_eq!(kept.scenarios, built.scenarios);
            assert_eq!(kept.mu.to_bits(), built.mu.to_bits());
            assert_eq!(kept.ell.to_bits(), built.ell.to_bits());
            assert_eq!(kept.upper.to_bits(), built.upper.to_bits());
        }
    }

    /// After re-rooting, every leaf equals a node freshly built under the new root, bounds
    /// stay ordered at every node, and planning continues from the kept subtree.
    #[test]
    fn rerooted_leaves_match_a_fresh_build() {
        let config = DespotConfig {
            scenarios: 60,
            max_depth: 6,
            regularization: 0.1,
            ..DespotConfig::default()
        };
        let mut search = Despot::new(
            &Coin,
            &[true, false],
            UniformRandom,
            |_: &bool| 10.0,
            config,
        )
        .expect("valid input");
        search.plan().expect("valid model");
        search.advance(&0, &Some(true)).expect("a seen history");
        assert_eq!(search.root_depth, 1);
        assert!(search.tree_size() > 1, "the subtree is kept");

        let scenarios = search.tree.node(ROOT).scenarios.clone();
        let mut fresh =
            Despot::with_root(&Coin, scenarios, 1, UniformRandom, |_: &bool| 10.0, config)
                .expect("valid input");
        assert_leaves_match_a_fresh_build(&search, &mut fresh);
        assert_replay_rebuilds_the_kept_tree(&search, config);

        let root = search.tree.node(ROOT);
        assert!(root.parent.is_none());
        let fresh_root = fresh.tree.node(ROOT);
        assert_eq!(
            fresh_root.default_value.to_bits(),
            root.default_value.to_bits()
        );
        assert!(
            root.mu <= fresh_root.mu + 1e-12,
            "backed-up mu is at most the initial one"
        );
        assert_eq!(search.plan().expect("valid model").action, 1, "call heads");
    }

    /// A history the tree never saw is an error, and planning refuses until a reset.
    #[test]
    fn advance_to_an_unseen_history_needs_a_reset() {
        use crate::Error;

        let mut search = Despot::new(
            &Coin,
            &[true, false],
            UniformRandom,
            |_: &bool| 10.0,
            DespotConfig::default(),
        )
        .expect("valid input");
        assert_eq!(search.advance(&0, &Some(true)), Err(Error::UnseenHistory));
        assert_eq!(search.plan(), Err(Error::UnseenHistory));

        search.reset(&[true, false]).expect("valid input");
        search.plan().expect("valid model");
        assert_eq!(search.advance(&1, &Some(true)), Err(Error::UnseenHistory));
        assert_eq!(search.advance(&7, &None), Err(Error::UnseenHistory));
        assert_eq!(search.reset(&[]), Err(Error::EmptyBelief));
        search.reset(&[true]).expect("valid input");
        assert_eq!(search.tree_size(), 1);
        assert_eq!(search.plan().expect("valid model").action, 1, "call heads");
    }

    /// The same seed builds the same tree.
    #[test]
    fn same_seed_same_tree() {
        let build = || {
            let config = DespotConfig {
                scenarios: 30,
                max_depth: 6,
                ..DespotConfig::default()
            }
            .with_budget(crate::Limits {
                max_trials: Some(50),
                ..DespotConfig::DEFAULT_LIMITS
            });
            let mut search = Despot::new(
                &Coin,
                &[true, false],
                UniformRandom,
                |_: &bool| 10.0,
                config,
            )
            .expect("valid input");
            search.run().expect("valid model");

            search
                .tree
                .nodes
                .iter()
                .map(|n| {
                    (
                        n.depth,
                        n.scenarios.clone(),
                        n.mu.to_bits(),
                        n.ell.to_bits(),
                    )
                })
                .collect::<alloc::vec::Vec<_>>()
        };

        assert_eq!(build(), build());
    }
}