tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
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
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
//! PCG32, ported from the reference implementation.
//!
//! # What this is a port of, and why it can be exact
//!
//! The reference implementation emulates a 64-bit PCG32 using pairs of 32-bit
//! integers, because its bitwise operators are 32-bit (`Math.imul`, `>>> 0`).
//! Rust has native `u64`, so this implementation is shorter than the original
//! while producing **bit-identical** output.
//!
//! That claim is safe for a specific reason: every operation in the PCG32 core
//! is integer arithmetic. Integer arithmetic is exactly specified in both
//! languages, so "port carefully and it will match" is a guarantee here rather
//! than a hope. This is the one part of the whole engine port where that is
//! true.
//!
//! # It applies to the integer core ONLY — measured
//!
//! An earlier version of this file, and several summaries of it, described the
//! RNG port as bit-identical without qualification. That is **false for
//! `next_normal`**, and the correction is worth stating precisely because the
//! overstatement survived a passing test.
//!
//! | surface | vs Chrome |
//! |---|---|
//! | raw `u32`, uniforms, ranged ints, bools | bit-identical |
//! | `next_normal` (Box-Muller) | **1.545% of draws differ** |
//!
//! Measured across all 60,000 recorded draws in `prng-normals.json` by
//! `tests/prng_normals_full.rs`. **The first divergence is at draw 12.**
//!
//! `reference_parity_smoke.rs` checks six normals and passes — it stops six draws
//! short of the first mismatch. A test can pass because it is too small, and
//! this is what that looks like.
//!
//! The divergence is not a defect: it is the same finding as
//! the determinism notes, since Box-Muller routes through `cos` and
//! Chrome, Firefox and Safari disagree about `cos`. There is no single browser
//! answer to match. What was wrong was the claim, not the code.
//!
//! # Where it stops being true
//!
//! [`GameRng::next_normal`] is Box-Muller and calls `ln`, `sin` and `cos`.
//! Those are implementation-defined, and Phase 0 measured the consequence
//! rather than speculating about it:
//!
//! | op | Rust `std` vs V8 |
//! |---|---|
//! | `ln` | identical |
//! | `sqrt` | identical (IEEE-754 specifies it exactly) |
//! | `sin` | identical |
//! | `cos` | **differs by 1 ULP** |
//!
//! One function, one bit. But one bit is enough: normal draws feed the GARCH
//! noise term for every company on every tick, and the mispricing process is
//! non-linear with feedback, so a last-ULP difference becomes a different
//! market within a simulated year.
//!
//! # Why this crate does not use `std` for maths
//!
//! Rust's `f64::cos` delegates to the platform libm — MSVC's CRT on Windows,
//! glibc on Linux, Apple's on macOS. The `libm` crate is a pure-Rust port of
//! MUSL's, which shares fdlibm ancestry with V8's implementation, and it
//! reproduces V8 exactly on the case that failed.
//!
//! That buys two things, and the second matters more than the first:
//!
//! 1. **Parity with V8**, so the port can be verified against the reference implementation.
//! 2. **Determinism across platforms.** With `std`, the same Python wheel
//!    would produce different numbers on Linux and Windows. For a library
//!    whose entire selling point is reproducible markets, that is disqualifying
//!    on its own — this crate would need to vendor its maths even if V8 parity
//!    were not a goal.
//!
//! So: no `std` transcendentals anywhere in this crate. Everything routes
//! through [`crate::mathx`], which is enforced by a test that greps the source
//! rather than trusting anyone to remember.
//!
//! # Faithfulness over correctness
//!
//! Where the reference implementation does something odd, this reproduces the oddity rather
//! than improving on it. A port that "fixes" the source is not a port; it is a
//! second model, and two models that disagree is the outcome this entire
//! project exists to avoid. Every such case is commented with what the
//! the reference implementation does and why the Rust matches it.

use crate::mathx;

/// A draw address is `(stream, kind, index)`: the stream, whether the draw
/// was a uniform or a normal, and how many draws OF THAT KIND the stream
/// had taken since engine construction when this one was taken.
///
/// # Why normals index by normal count
///
/// `next_normal` is Box-Muller: it takes two uniforms from the generator,
/// returns one normal and caches the other as the spare, and the next call
/// returns the spare without touching the generator. Counting the
/// underlying uniforms would give every second normal no address of its
/// own and the same address to a uniform and the normal that consumed it.
/// So the two kinds are counted apart: a uniform's index is the count of
/// `next_f64` calls, a normal's index is the count of `next_normal` calls,
/// and the two uniforms Box-Muller takes internally are not on the uniform
/// index at all. Under that rule every draw the engine consumes has exactly
/// one address and the address survives the spare.
///
/// # The overlay
///
/// An overlay is a table from address to value. On every draw the generator
/// advances exactly as it would have; the value is then substituted if the
/// address is in the table. Substitute, never skip: a patched draw costs
/// the same generator step as an unpatched one, so every address after it
/// is unchanged and the draw counts are identical with and without the
/// overlay. A patched normal substitutes the value returned; the spare is
/// computed from the raw uniforms as ever, so the NEXT normal is the one
/// the generator would have produced.
///
/// # The draw log
///
/// When enabled, every draw is recorded as `(kind, index, value, day,
/// site, tag)`, the value being the one the consumer received. The site
/// names the call site; the engine sets it before each group of draws and
/// it is part of the schedule contract, pinned by a test that walks one
/// day. The log is off by default and costs one branch per draw.
///
/// # What it costs, measured
///
/// One [`DrawRecord`] is 32 bytes: `index` 8, `value` 8, `day` 8, `tag` 4,
/// `kind` 1, `site` 1, padded to the alignment of its widest field. The
/// assertion below the type fails to compile if that changes.
///
/// The draw count is a schedule quantity, so the memory follows from the
/// roster and the tick count rather than from a benchmark. At 60 names and
/// 390 ticks the market stream takes
/// `390 * (1 market factor + 12 sectors + 60 idiosyncratic normals + 60
/// stash uniforms + 240 settlement uniforms)` = 145,470 draws a day, which
/// is 4.7 MB a day and 1.17 GB over a 252-day year held in one engine. The
/// other six streams together add 313 draws a day at that roster, which is
/// four orders of magnitude smaller.
/// `test_the_market_log_length_is_the_schedule` states the derivation
/// against the log rather than pinning the number.
///
/// The time cost did not resolve. Twelve interleaved runs of three days at
/// that roster gave medians of 0.2510 s with no log, 0.2497 s logging the
/// market stream and 0.2351 s logging all seven, so the logged runs came out
/// at 0.995 and 0.937 of the unlogged one. A shared machine cannot separate
/// those, and a second measurement on the same design reported 1.043 and
/// 1.033. Read both as no measurable cost rather than as a number.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum DrawKind {
    Uniform = 0,
    Normal = 1,
}

impl DrawKind {
    pub fn name(self) -> &'static str {
        match self {
            DrawKind::Uniform => "uniform",
            DrawKind::Normal => "normal",
        }
    }
}

/// The call sites that draw, one name per site, in schedule order within
/// their stream. The engine tags the generator before each group; a draw
/// taken with no tag set records `Unset`, which the schedule test treats
/// as a failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum Site {
    Unset = 0,
    /// The market factor's one normal per tick (market/tick.rs).
    MarketFactorZ = 1,
    /// One normal per sector per tick; the tag is the sector index.
    SectorZ = 2,
    /// One normal per active company per tick (market/factors.rs); the tag
    /// is the company index.
    FactorIdioZ = 3,
    /// One uniform per active company per tick, stashed for phase 3.
    StashU = 4,
    /// Settlement's four uniforms per active company per tick.
    SettleU = 5,
    /// The market jump's uniform and normal, once per day.
    JumpMarketU = 6,
    JumpMarketZ = 7,
    /// A company's jump uniform and normal, once per company per day.
    JumpCompanyU = 8,
    JumpCompanyZ = 9,
    /// The common volume state's normal, once per day.
    VolumeZ = 10,
    /// A company's volume state normal, once per company per day.
    VolumeIdioZ = 11,
    /// A company's news uniform and normal, once per company per day.
    NewsU = 12,
    NewsZ = 13,
    /// The daily macro chain (economy/daily.rs).
    EconomyDaily = 14,
    /// The cycle transition roll (economy/cycle.rs).
    EconomyCycle = 15,
    /// The central bank's meeting and rate draws (economy/central_bank.rs).
    CentralBank = 16,
    /// The embedder's own draws on the external stream.
    External = 17,
    /// The overnight move's normals, once per day at the open: one for the
    /// market, one per sector (the tag is the sector index), one per
    /// company (the tag is the company index).
    OvernightMarketZ = 18,
    OvernightSectorZ = 19,
    OvernightIdioZ = 20,
    /// The market factor's slow variance level, one normal per day at the
    /// close on [`stream::MARKET_VOL_LEVEL`].
    MarketVolLevelZ = 21,
    /// The crisis epicentre's one uniform, taken at the open of the session
    /// that STARTS a crisis episode, on [`stream::CRISIS_EPICENTRE`]. One
    /// draw per episode, not per session, and none at all when the scenario
    /// has pinned the epicentre.
    CrisisEpicentreU = 22,
    /// The market's cycle nowcast: one uniform per session at the close, on
    /// [`stream::CYCLE_NOWCAST`], only while `cycle_nowcast_accuracy` is set.
    CycleNowcastU = 23,
    /// The night's student-t scale for the idiosyncratic draw: `nu` normals
    /// per company (the tag is the company index), squared and summed into
    /// a chi-square, on [`stream::OVERNIGHT`] after the three sites above.
    /// Taken only while `overnight_idio_df` is set on a model with a night
    /// share, so every other model's overnight schedule is the one it was.
    OvernightIdioChi2 = 24,
    /// The day's market t scale (`market_day_tail_df`): the gamma draw
    /// behind one chi-square per session, normals and uniforms by
    /// Marsaglia and Tsang (a variable count), on [`stream::OVERNIGHT`]
    /// after every other overnight site. Taken only while the dial is set.
    MarketDayTailChi2 = 25,
    /// The index futures' basis: one normal per step of the futures (each
    /// open tick and each night step), on [`stream::DERIVATIVES`], only
    /// while `futures_index_listed` is set.
    FuturesBasisZ = 26,
    /// The night's path for the index futures: one normal per night step,
    /// after the basis's, on [`stream::DERIVATIVES`], only while
    /// `night_session_steps` is set and a night is walked.
    NightBridgeZ = 27,
}

impl Site {
    pub fn name(self) -> &'static str {
        match self {
            Site::Unset => "unset",
            Site::MarketFactorZ => "market_factor_z",
            Site::SectorZ => "sector_z",
            Site::FactorIdioZ => "factor_idio_z",
            Site::StashU => "stash_u",
            Site::SettleU => "settle_u",
            Site::JumpMarketU => "jump_market_u",
            Site::JumpMarketZ => "jump_market_z",
            Site::JumpCompanyU => "jump_company_u",
            Site::JumpCompanyZ => "jump_company_z",
            Site::VolumeZ => "volume_z",
            Site::VolumeIdioZ => "volume_idio_z",
            Site::NewsU => "news_u",
            Site::NewsZ => "news_z",
            Site::EconomyDaily => "economy_daily",
            Site::EconomyCycle => "economy_cycle",
            Site::CentralBank => "central_bank",
            Site::External => "external",
            Site::OvernightMarketZ => "overnight_market_z",
            Site::OvernightSectorZ => "overnight_sector_z",
            Site::OvernightIdioZ => "overnight_idio_z",
            Site::MarketVolLevelZ => "market_vol_level_z",
            Site::CrisisEpicentreU => "crisis_epicentre_u",
            Site::CycleNowcastU => "cycle_nowcast_u",
            Site::OvernightIdioChi2 => "overnight_idio_chi2",
            Site::MarketDayTailChi2 => "market_day_tail_chi2",
            Site::FuturesBasisZ => "futures_basis_z",
            Site::NightBridgeZ => "night_bridge_z",
        }
    }
}

/// One recorded draw.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct DrawRecord {
    pub kind: DrawKind,
    pub index: u64,
    pub value: f64,
    pub day: i64,
    pub site: Site,
    pub tag: u32,
}

/// The log's memory is quoted per record in this module's documentation, so
/// the size is pinned where a change to the type has to meet it.
const _: () = assert!(std::mem::size_of::<DrawRecord>() == 32);

/// The per-generator table of substitutions and the optional log.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct DrawOverlay {
    pub table: std::collections::BTreeMap<(DrawKind, u64), f64>,
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DrawLog {
    pub from_day: i64,
    pub to_day: i64,
    pub records: Vec<DrawRecord>,
}

/// Named substreams of one root seed.
///
/// # Why streams exist
///
/// The reference implementation ran every consumer — market, economy,
/// microstructure, embedder — off ONE generator, so changing what any
/// consumer drew shifted every draw that every other consumer saw
/// afterwards. That coupling is what made "what would have happened if I
/// changed only this?" unanswerable: the TCA counterfactual, a
/// pinned-versus-baseline macro comparison and the cutover embedder all
/// need to vary one thing while the rest of the randomness stays put.
///
/// The 2026-08 era boundary splits the engine onto three independent
/// substreams, all derived from the same root seed. One seed still fully
/// determines the whole simulation; what changes is that perturbing one
/// domain's consumption no longer moves any other domain's sequence.
///
/// # The derivation contract
///
/// This is a CONTRACT, not an implementation detail: it is the thing a
/// reader reproduces, and changing it is an era boundary in its own right.
/// For a root seed `s` below `2^32` and a stream id `k` (one of the
/// constants below):
///
/// ```text
/// mixed    = splitmix64_mix((s as u64) << 32 | k as u64)
/// seed_k   = mixed >> 32                   // top 32 bits of the mix
/// seq_k    = STREAM_SEQUENCE_BASE + k      // = 256 + k
/// stream_k = GameRng::new(seed_k, seq_k)
/// ```
///
/// where `splitmix64_mix` is the SplitMix64 output finalizer (Stafford's
/// "Mix13", the one in Vigna's reference `splitmix64.c`):
///
/// ```text
/// z  = input + 0x9E3779B97F4A7C15
/// z ^= z >> 30;  z *= 0xBF58476D1CE4E5B9
/// z ^= z >> 27;  z *= 0x94D049BB133111EB
/// z ^= z >> 31
/// ```
///
/// # Root seeds from `2^32` to `2^64 - 1`
///
/// Until 0.8.5 the root seed was a `u32`, which left 2^32 markets per
/// roster and preset: few enough that a sealed seed could be found by
/// trying them all against a market's first prices. The root is now a
/// `u64`, and the high 32 bits enter the derivation only when they are
/// non-zero. A root below `2^32` takes the formula above, unchanged, so
/// every such seed gives the market it always gave and every known-answer
/// digest stands. A root at or above `2^32` takes a second formula:
///
/// ```text
/// key_k    = splitmix64_mix(SEED64_TAG << 32 | k)   // SEED64_TAG = "SD64"
/// seed_k   = splitmix64_mix(s ^ key_k)              // all 64 bits
/// seq_k    = SEED64_SEQUENCE_BASE + k               // = 768 + k
/// stream_k = GameRng::new(seed_k, seq_k)
/// ```
///
/// Three properties follow, each by construction rather than by sampling:
///
/// - **No truncation.** Every bit of `s` reaches `seed_k`, and all 64 bits
///   of `seed_k` reach the PCG state ([`GameRng::new`] adds the seed to the
///   state whole). Recovering a wide root from its prices means searching
///   2^64 roots, not 2^32.
/// - **No collisions.** For one `k`, `s -> seed_k` is XOR with a constant
///   followed by `splitmix64_mix`, and both are bijections on `u64`. Two
///   wide roots never start one stream from the same state.
/// - **No sharing with 32-bit roots.** `768 + k` is no sequence a 32-bit
///   root's stream or surgery uses, so a wide root's streams traverse
///   orbits that no 32-bit root's stream ever does.
///
/// The two independence properties below hold for the wide formula for
/// the same reasons: a distinct sequence per stream, and a per-stream key
/// through the finalizer so one root's streams start from unrelated states.
///
/// # Why this derivation gives independent streams
///
/// Two properties carry the independence argument, and each half of the
/// derivation supplies one:
///
/// 1. **Distinct sequences, structurally.** Each stream gets its own PCG
///    `sequence`, so its LCG increment differs from every other stream's.
///    Two PCG32 generators with different odd increments traverse
///    DIFFERENT orbits — one can never be a shifted copy of the other, the
///    failure mode where two "independent" streams eventually replay each
///    other's values. This holds by construction, not probabilistically.
///
/// 2. **Decorrelated states, by mixing.** The lazy derivation —
///    `GameRng::new(s, k)` with the root seed used raw — is exactly the one
///    this contract refuses, and the refusal has a reason: two PCG streams
///    seeded with the SAME state and different increments `c, c'` have
///    states related by the affine identity
///    `state'_n − state_n = (c' − c)(aⁿ⁻¹ + ⋯ + 1)`, a deterministic
///    cross-stream structure that the output permutation only obscures.
///    Feeding the (root, id) pair through an avalanche finalizer first
///    gives every stream an unrelated starting state — a one-bit change in
///    either the root or the id flips each output bit with probability
///    ~1/2 — so no such relation exists between any two substreams.
///
/// Every operation is integer arithmetic, exactly specified on every
/// platform: no floats, no hashing with platform-dependent behaviour, and
/// nothing for the cross-OS bit-identity claim to trip on.
///
/// The sequence base 256 keeps the derived sequences clear of every
/// sequence in historical use with RAW seeds (0 and 1 from the two
/// constructors, 21 for the universe, 99 for the reference MAIN stream) —
/// not because a collision would alias a stream (the mixed seed already
/// differs) but so that a recorded sequence number identifies its era at a
/// glance.
///
/// # What is deliberately NOT derived this way
///
/// - `random_universe` keeps its original `GameRng::new(seed, 21)`. Its
///   seed is a UNIVERSE seed, a different input domain from the simulation
///   seed, so it shares no root with the engine streams and re-deriving it
///   would churn every published universe fingerprint for no independence
///   gain.
/// - `GameRng::new(seed, sequence)` stays public and raw. It is the
///   Layer-1 API and the replay surface for pre-split recordings; the
///   contract above is about how the ENGINE seeds itself.
pub mod stream {
    /// Every draw inside `simulate_market_tick`: shared factors, per-company
    /// noise, volume, and book settlement.
    pub const MARKET: u32 = 0;
    /// The daily macro chain: `update_economy_daily`, the cycle roll, and
    /// the central bank.
    pub const ECONOMY: u32 = 1;
    /// The embedder's own draws, taken through `Engine::draw_uniform` /
    /// `draw_normal`: seed-derived and reproducible, but incapable of
    /// perturbing the market.
    pub const EXTERNAL: u32 = 2;
    /// Endogenous jumps, drawn once per name per day at the close.
    ///
    /// Its own stream, and that is the whole reason a draw-CONSUMING
    /// mechanism could be added at all. The draw-schedule rule says nothing
    /// settable may change how many draws are taken or in what order, so a
    /// jump process sharing [`MARKET`] would shift every subsequent market
    /// draw and change every preset's trajectory the moment the code
    /// landed — inert parameters or not.
    ///
    /// On a stream of its own, the jump draws happen unconditionally and
    /// perturb nothing: at zero intensity no jump fires, and `MARKET`,
    /// `ECONOMY` and `EXTERNAL` are untouched, so every shipped preset
    /// reproduces bit for bit and the known-answer digest does not move.
    pub const JUMPS: u32 = 3;
    /// The persistent volume component, drawn once per day at the close.
    ///
    /// Its own stream for the same reason [`JUMPS`] has one, and a SEPARATE
    /// one from jumps so neither mechanism's draw count can shift the
    /// other's sequence. Two mechanisms sharing a stream are coupled by
    /// their draw counts, which is a dependency nobody would choose and
    /// everybody would forget.
    pub const VOLUME: u32 = 4;

    /// Endogenous company news, drawn once per name per day at the open.
    ///
    /// Its own stream for the same reason [`JUMPS`] and [`VOLUME`] have
    /// theirs: a draw-consuming mechanism on a shared stream shifts every
    /// later draw and moves every preset's trajectory the moment it lands.
    /// A separate one from both, so no two mechanisms' draw counts couple.
    pub const NEWS: u32 = 5;

    /// Per-name volume persistence, drawn once per name per day.
    ///
    /// Separate from [`VOLUME`], which carries the COMMON component, for the
    /// reason every split here exists: the common update draws once a day
    /// and the per-name update draws once per name, so sharing a stream
    /// would make the common sequence depend on the universe size and
    /// shift every preset that sets only the common half.
    pub const VOLUME_IDIO: u32 = 6;

    /// The overnight move, drawn once at each open: one normal for the
    /// market, one per sector, one per company, in that order.
    ///
    /// Its own stream for the reason every stream here has one. It is
    /// drawn UNCONDITIONALLY, whatever `overnight_variance_ratio` reads, so
    /// the schedule cannot depend on the dial; at a ratio of zero the draws
    /// are taken and nothing is moved, and since this stream is not among
    /// the three `draws_consumed` counts, every preset before the dial
    /// reproduces bit for bit and the known-answer digests do not move.
    pub const OVERNIGHT: u32 = 7;

    /// The market factor's slow stochastic variance LEVEL, drawn once per
    /// day at the close.
    ///
    /// Its own stream for the reason every stream after [`MARKET`] has one,
    /// and the reason is sharper here than anywhere else. The level is a
    /// mechanism whose whole purpose is to be compared against itself at
    /// `market_vol_level_sigma` 0.0: if its draw came off [`MARKET`] the
    /// zero arm and the live arm would differ by a RESHUFFLE of every
    /// subsequent tick draw as well as by the level, and the two could not
    /// be told apart on one seed. On a stream of its own the normal is
    /// drawn UNCONDITIONALLY, whatever the dial reads, so the schedule
    /// cannot depend on a settable; at sigma 0.0 the draw is taken, the
    /// log-level stays exactly 0.0, the multiplier is exactly 1.0 and a
    /// preset that leaves the dial there reproduces bit for bit with its
    /// known-answer digest unmoved -- every preset through pt-v18, where
    /// `market_vol_level_sigma` is 0.0. pt-v19 is not one of them and its
    /// digest is the live level's; this sentence read "every preset"
    /// without that qualifier until 2026-09-18.
    pub const MARKET_VOL_LEVEL: u32 = 8;

    /// The crisis epicentre: which sector carries a crisis, one uniform per
    /// EPISODE, taken at the open of the session the episode starts on.
    ///
    /// Its own stream for the reason every stream after [`MARKET`] has one,
    /// and with one difference worth stating because it is the opposite of
    /// [`MARKET_VOL_LEVEL`]'s discipline. This draw is CONDITIONAL: it
    /// happens only when `crisis_epicentre_extra` is non-zero, only on the
    /// session an episode begins, and not at all when the scenario has
    /// pinned the epicentre. A conditional draw is normally forbidden
    /// because a settable would move the schedule -- but the schedule it
    /// could move is this stream's own, and nothing else reads it. `MARKET`,
    /// `ECONOMY`, `EXTERNAL` and the six mechanism streams are untouched at
    /// every setting, so every shipped preset reproduces bit for bit and the
    /// known-answer digest does not move. The alternative, a uniform drawn
    /// every session whether an episode starts or not, would buy nothing
    /// here: there is no zero-arm comparison to protect, because the zero
    /// arm takes no draw on any stream a price reads.
    pub const CRISIS_EPICENTRE: u32 = 9;

    /// The opening mispricing: one normal per name, taken once when the
    /// engine is built and only when `opening_mispricing_sigma` is non-zero.
    ///
    /// A ONE-SHOT stream, and that is why it sits outside [`COUNT`]: the
    /// engine derives it, takes its draws into a vector and drops it, so
    /// there is no position to snapshot, restore or mark, and no array
    /// indexed by stream id needs a slot for it. Every other stream is
    /// untouched at every setting, so every shipped preset reproduces bit
    /// for bit.
    pub const OPENING: u32 = 10;

    /// The market's cycle nowcast: the one uniform a session that names the
    /// phase the market's news reports (`cycle_nowcast_accuracy`). Outside
    /// [`COUNT`] like [`OPENING`], so no array indexed by stream id grows and
    /// every engine with the dial at 0.0 is the engine it was; its generator
    /// is carried in the snapshot and the state hash only while the dial is
    /// set. Conditional, for [`CRISIS_EPICENTRE`]'s reason: nothing else reads
    /// this stream.
    pub const CYCLE_NOWCAST: u32 = 11;

    /// The arrival order of a cohort's orders at the shared book, under
    /// `book_arrival_shuffle`. Not a generator at all: the id only keys
    /// [`super::arrival_priority`], a counter-based function of the seed,
    /// the day, the step and the label, so there is no position to
    /// snapshot, restore or mark and it sits outside [`COUNT`] as
    /// [`OPENING`] does. No stream's draws move at any setting. It is 12,
    /// not the 11 sim/real-arrival-order chose, because [`CYCLE_NOWCAST`]
    /// took 11 in sim/r13.
    pub const ARRIVAL: u32 = 12;

    /// The earnings calendar's key: two raw outputs, taken once when the
    /// engine is built, form the 64-bit key every earnings draw is derived
    /// from ([`GameRng::keyed`](crate::rng::GameRng::keyed)). A ONE-SHOT stream like [`OPENING`], outside
    /// [`COUNT`]: nothing holds a position on it, and every other stream is
    /// untouched at every setting.
    ///
    /// The calendar's draws are KEYED rather than streamed: the name's
    /// offset into the quarter, each quarter's jitter and each report's
    /// surprise are functions of (key, company id, quarter, slot), so the
    /// dates ahead can be listed without drawing anything, a report's draws
    /// do not depend on how many names reported before it, and a roster
    /// change does not reshuffle any other name's calendar. It is 13, not
    /// the 11 sim/real-earnings-gaps chose, because [`CYCLE_NOWCAST`] took 11
    /// in sim/r13 and [`ARRIVAL`] 12.
    pub const EARNINGS: u32 = 13;

    /// The derivatives' own draws: the index futures' basis, one normal per
    /// futures step, and the night's path, one normal per night step
    /// (`futures_index_listed`, `night_session_steps`). Outside [`COUNT`]
    /// like [`CYCLE_NOWCAST`], so no array indexed by stream id grows and
    /// every engine with the switches at 0.0 is the engine it was; its
    /// generator is carried in the snapshot and the state hash only while
    /// `futures_index_listed` is set. Nothing else reads it, and a futures
    /// price feeds nothing a stock price reads, so no other stream moves at
    /// any setting.
    pub const DERIVATIVES: u32 = 14;

    /// How many streams there are. Every array indexed by stream id, the
    /// snapshot's generator and count vectors, the day mark's positions
    /// and the loops that enable, clear or stamp every stream are sized
    /// from this rather than written out: the eighth stream was met in
    /// four places that had written seven, each found by a box.
    pub const COUNT: usize = 10;

    /// Derived streams live at `256 + id`. See the module docs for why the
    /// offset exists.
    pub const STREAM_SEQUENCE_BASE: u32 = 256;
    /// The sequence base for surgery generators (`GameRng::surgery`):
    /// clear of the stream sequences at `256 + k` and of every raw
    /// sequence in historical use, so a re-randomised window traverses
    /// an orbit no stream does.
    pub const SURGERY_SEQUENCE_BASE: u32 = 512;
    /// The tag mixed into a surgery input, ASCII "SURG", so the input
    /// of a surgery of stream `k` under surgery seed `g` is never the
    /// input of a stream.
    pub const SURGERY_TAG: u32 = 0x5355_5247;
    /// The sequence base for streams derived from a root seed at or above
    /// `2^32`. Clear of `256 + k` and `512 + k`, so a stream of a wide root
    /// traverses an orbit that no stream of a 32-bit root, and no surgery
    /// of one, ever does: the two seed ranges cannot share a generator,
    /// whatever the mixed states happen to be.
    pub const SEED64_SEQUENCE_BASE: u32 = 768;
    /// The sequence base for a surgery generator when the root seed or the
    /// surgery seed is at or above `2^32`, for the same reason.
    pub const SEED64_SURGERY_SEQUENCE_BASE: u32 = 1024;
    /// The tag in a wide root's per-stream key, ASCII "SD64".
    pub const SEED64_TAG: u32 = 0x5344_3634;
    /// The sequence of every keyed generator ([`GameRng::keyed`](crate::rng::GameRng::keyed)): clear of
    /// the stream, surgery and wide-root sequences above.
    pub const KEYED_SEQUENCE: u32 = 1280;
}

/// The SplitMix64 output finalizer. Integer-only, exact on every platform.
///
/// The constants are load-bearing and pinned by `substream_derivation_is_the_documented_formula`
/// below: this is Stafford's Mix13 with SplitMix64's golden-ratio increment,
/// as published in Vigna's reference implementation.
fn splitmix64_mix(input: u64) -> u64 {
    let mut z = input.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// The tag in the business cycle's publication draws, ASCII "PUBL"
/// (`cycle_publication_lag_draw`).
pub const PUBLICATION_TAG: u32 = 0x5055_424C;

/// The key of a root seed's publication draws (`cycle_publication_lag_draw`):
/// `splitmix64_mix(root ^ (PUBLICATION_TAG << 32 | 0xFFFF_FFFF))`. A
/// bijection on `u64` for a fixed tag, and its input is never the input of a
/// draw below (whose low half is a turn index, never all ones in practice).
/// The engine keeps the key rather than the root.
/// The tag of the market's prehistory (`market_prehistory_sessions`), ASCII
/// "PREH": the surgery seed its stream generators are derived under, and the
/// word its counter keys are mixed with.
pub const PREHISTORY_TAG: u64 = 0x5052_4548;

/// A counter key of the market's prehistory (the earnings calendar's, the
/// cycle publication's): the run's own key mixed with [`PREHISTORY_TAG`], so
/// the sessions played before day zero draw no reaction or publication
/// uniform the run's own sessions draw.
pub fn prehistory_key(key: u64) -> u64 {
    splitmix64_mix(key ^ (PREHISTORY_TAG << 32 | PREHISTORY_TAG))
}

/// The tag of the economy's long run for the forecast's cycle
/// (`oil_forecast_cycle_growth`), ASCII "AGEL": the surgery seed its stream
/// generators are derived under, and the word its counter keys are mixed
/// with, so that run draws nothing the run's own sessions draw.
pub const AGE_LAW_TAG: u64 = 0x4147_454C;

/// A counter key of the economy's long run (`oil_forecast_cycle_growth`):
/// the run's own key mixed with [`AGE_LAW_TAG`], as [`prehistory_key`].
pub fn age_law_key(key: u64) -> u64 {
    splitmix64_mix(key ^ (AGE_LAW_TAG << 32 | AGE_LAW_TAG))
}

/// The tag of the oil price's long factor (`oil_target_drift_sd`), ASCII
/// "OILD".
pub const OIL_DRIFT_TAG: u32 = 0x4F49_4C44;

/// The key of a root seed's oil long-factor draws: as [`publication_key`]
/// under [`OIL_DRIFT_TAG`]. Each session's normal is the first of
/// `GameRng::keyed(key, OIL_DRIFT_TAG, session)`, so it takes nothing from
/// any stream and moves no other draw.
pub fn oil_drift_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((OIL_DRIFT_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The tag of core inflation's slow trend (`core_trend_sd`), ASCII "CTRD".
pub const CORE_TREND_TAG: u32 = 0x4354_5244;

/// The key of a root seed's core-trend draws: as [`publication_key`] under
/// [`CORE_TREND_TAG`]. Each month's normal is the first of
/// `GameRng::keyed(key, CORE_TREND_TAG, month)`, and the opening's the first
/// of `GameRng::keyed(key, CORE_TREND_TAG, u64::MAX)`, so it takes nothing
/// from any stream.
pub fn core_trend_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((CORE_TREND_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The tag of credit's own state (`corporate_spread_noise_sd`), ASCII
/// "CSPN".
pub const SPREAD_NOISE_TAG: u32 = 0x4353_504E;

/// The key of a root seed's credit-state draws: as [`publication_key`] under
/// [`SPREAD_NOISE_TAG`]. Each session's normal is the first of
/// `GameRng::keyed(key, SPREAD_NOISE_TAG, day)`, and the opening's the first
/// of `GameRng::keyed(key, SPREAD_NOISE_TAG, u64::MAX)`, so it takes nothing
/// from any stream.
pub fn spread_noise_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((SPREAD_NOISE_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The tag of the 10-year's own term premium (`treasury_term_premium_sd`),
/// ASCII "TTPM".
pub const TERM_PREMIUM_TAG: u32 = 0x5454_504D;

/// The key of a root seed's term-premium draws: as [`publication_key`] under
/// [`TERM_PREMIUM_TAG`]. A run's session `day` takes the first normal of
/// `GameRng::keyed(key, TERM_PREMIUM_TAG, day)`, a burn-in day the first of
/// `GameRng::keyed(key, TERM_PREMIUM_TAG, day | 1 << 40)` (the burn-in counts
/// its own days from 1 as the run does), and the opening the first of
/// `GameRng::keyed(key, TERM_PREMIUM_TAG << 32, 0)`, so it takes nothing from
/// any stream.
pub fn term_premium_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((TERM_PREMIUM_TAG as u64) << 32) | 0xFFFF_FFFF))
}

pub fn publication_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((PUBLICATION_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The tag of the skew premium's own noise (`surface_skew_noise_sd`), ASCII
/// "SKWN".
pub const SKEW_NOISE_TAG: u32 = 0x534B_574E;

/// The key of a root seed's skew-noise draws: as [`publication_key`] under
/// [`SKEW_NOISE_TAG`]. Each session's normal is the first of
/// `GameRng::keyed(key, SKEW_NOISE_TAG, session)`, and the opening's the
/// first of `GameRng::keyed(key, SKEW_NOISE_TAG << 32, 0)`, so it takes
/// nothing from any stream and moves no other draw.
pub fn skew_noise_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((SKEW_NOISE_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The tag of the guidance's signal noise (`policy_guidance_signal_sd`),
/// ASCII "GSIG".
pub const GUIDANCE_SIGNAL_TAG: u32 = 0x4753_4947;

/// The key of a root seed's guidance signals: as [`publication_key`] under
/// [`GUIDANCE_SIGNAL_TAG`]. The signal of the meeting held at the close whose
/// day count is `meeting` takes the first normal of
/// `GameRng::keyed(key, GUIDANCE_SIGNAL_TAG, meeting)`, one for every close
/// that forecasts that meeting, so it takes nothing from any stream and
/// moves no other draw.
pub fn guidance_signal_key(root_seed: u64) -> u64 {
    splitmix64_mix(root_seed ^ (((GUIDANCE_SIGNAL_TAG as u64) << 32) | 0xFFFF_FFFF))
}

/// The `k`-th publication uniform in [0, 1) of a key:
/// `splitmix64_mix(key ^ splitmix64_mix(PUBLICATION_TAG << 32 | k)) >> 11`
/// times `2^-53`. Stateless and integer-only up to the one exact scaling:
/// it takes nothing from any stream, so drawing it moves no other draw.
pub fn publication_uniform(key: u64, k: u64) -> f64 {
    let z = splitmix64_mix(key ^ splitmix64_mix(((PUBLICATION_TAG as u64) << 32) | (k & 0xFFFF_FFFF)));
    (z >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
}

/// The input the stream derivation mixes, for a root seed of either width.
///
/// Below `2^32` it is `s << 32 | k`, the 32-bit contract's input, bit for
/// bit. At or above `2^32` the root no longer fits beside the id, so the
/// whole root is XORed with a per-stream key instead:
/// `s ^ splitmix64_mix(SEED64_TAG << 32 | k)`. For one stream id that is a
/// bijection on `u64` (XOR with a constant), so two different wide roots
/// never give one stream the same input, and the key differs per stream,
/// so one root's streams start from unrelated states. The high 32 bits of
/// the root therefore enter the derivation only when they are non-zero.
fn stream_mix(root_seed: u64, stream_id: u32) -> u64 {
    if root_seed >> 32 == 0 {
        (root_seed << 32) | stream_id as u64
    } else {
        root_seed ^ splitmix64_mix(((stream::SEED64_TAG as u64) << 32) | stream_id as u64)
    }
}

/// FNV-1a over bytes, 64-bit. Integer-only; keys a label for
/// [`arrival_priority`].
fn fnv1a64(bytes: &[u8]) -> u64 {
    let mut h: u64 = 0xCBF2_9CE4_8422_2325;
    for &b in bytes {
        h = (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01B3);
    }
    h
}

/// A label's priority at the book on one step, under
/// `book_arrival_shuffle`: the step's arrival order is the labels sorted by
/// `(priority, label)`, lowest first.
///
/// ```text
/// base = splitmix64_mix(stream_mix(seed, ARRIVAL))
/// key  = splitmix64_mix(splitmix64_mix(base ^ day) ^ step_of_day)
/// prio = splitmix64_mix(key ^ fnv1a64(utf8(label)))
/// ```
///
/// Counter-based, so it consumes no draw and holds no state. Each label's
/// priority depends on nothing but its own name, so the relative order of
/// two labels is the same whichever other labels are present: removing,
/// freezing or adding an agent never reorders the rest. `stream_mix` is the
/// stream derivation's own, so a seed at or above `2^32` keys it whole.
pub fn arrival_priority(seed: u64, day: u64, step_of_day: u64, label: &str) -> u64 {
    let base = splitmix64_mix(stream_mix(seed, stream::ARRIVAL));
    let key = splitmix64_mix(splitmix64_mix(base ^ day) ^ step_of_day);
    splitmix64_mix(key ^ fnv1a64(label.as_bytes()))
}

/// The draw interface the engine modules consume.
///
/// Exists so that a caller can supply RECORDED draws instead of generated
/// ones. That is not a testing convenience, it is what makes the higher
/// layers gateable at all: `next_normal` is Box-Muller and therefore routes
/// through `cos`, which diverges from V8 on **1.545%** of draws (see the
/// module header). Any module that consumes normals inherits that rate, so a
/// long trajectory driven by a generated stream diverges within a handful of
/// steps for a reason that belongs to `cos` and not to the module under test.
///
/// Feeding recorded draws separates the two failures: the arithmetic is held
/// to bit-parity, while the generator's divergence stays measured in one
/// place — here — instead of being rediscovered, blurred into a tolerance, at
/// every layer above.
pub trait Rng {
    fn next_f64(&mut self) -> f64;
    fn next_normal(&mut self) -> f64;
    /// Name the call site of the draws that follow, for the draw log. A
    /// no-op by default and for every source that is not a logged
    /// generator, so a tag costs nothing on the market path.
    fn site(&mut self, _site: Site, _tag: u32) {}
}

impl Rng for GameRng {
    fn next_f64(&mut self) -> f64 {
        GameRng::next_f64(self)
    }
    fn next_normal(&mut self) -> f64 {
        GameRng::next_normal(self)
    }
    fn site(&mut self, site: Site, tag: u32) {
        self.site = site;
        self.tag = tag;
    }
}

/// JavaScript's `ToUint32` coercion, as applied by `>>> 0`.
///
/// The reference implementation's constructor does `seed >>> 0` and
/// `sequence << 1`, which
/// means a seed of `2^32` becomes `0` and a seed of `-1` becomes `4294967295`.
/// Callers reaching this crate from Python or Rust will not naturally apply
/// that, so it is applied here — otherwise the same nominal seed would produce
/// different streams in the simulation and in the library, which is precisely the
/// class of divergence this port must not introduce.
pub fn to_uint32(value: f64) -> u32 {
    if !value.is_finite() {
        return 0;
    }
    let truncated = value.trunc();
    let modulo = truncated.rem_euclid(4294967296.0);
    modulo as u32
}

/// A generator's complete state, as plain numbers.
///
/// Exists so a simulation can be checkpointed without replaying it. The
/// alternative -- recording a draw COUNT and fast-forwarding -- cannot express
/// the cached Box-Muller spare, and would restore a generator that agreed on
/// uniforms and disagreed on normals.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RngState {
    pub state: u64,
    pub increment: u64,
    pub spare: Option<f64>,
    /// The draw counts, so an address keeps its meaning across a restore.
    /// A state from before draw addressing carries zeros, and the restored
    /// generator's addresses start from zero at the restore.
    pub uniforms: u64,
    pub normals: u64,
}

impl RngState {
    /// The state as [`RNG_STREAM_WIDTH`](crate::RNG_STREAM_WIDTH) numbers,
    /// for a host that saves it in a flat array: the LCG state and
    /// increment as the raw bits of an `f64` (`f64::from_bits`), the spare
    /// (NaN when there is none), then the uniform and normal draw counts.
    ///
    /// The first two words are bit patterns, not quantities, and some of
    /// them are NaNs. Store and copy them as bits. JavaScript may rewrite a
    /// NaN's bits when one passes through a number, and JSON has no NaN, so
    /// a host that crosses either should move the words as bytes.
    /// A rewritten NaN comes back with an even increment, and
    /// [`RngState::from_words`] refuses one.
    pub fn to_words(&self) -> [f64; crate::widths::RNG_STREAM_WIDTH] {
        [
            f64::from_bits(self.state),
            f64::from_bits(self.increment),
            self.spare.unwrap_or(f64::NAN),
            self.uniforms as f64,
            self.normals as f64,
        ]
    }

    /// Read back what [`RngState::to_words`] wrote. Refuses a slice of the
    /// wrong length, an even increment (every PCG increment is odd), an
    /// infinite spare, and a draw count that is not a whole number from 0
    /// to 2^53.
    pub fn from_words(words: &[f64]) -> Result<Self, String> {
        const W: usize = crate::widths::RNG_STREAM_WIDTH;
        let words: &[f64; W] = words.try_into().map_err(|_| {
            format!(
                "an RNG stream state is {W} numbers (state, increment, spare, \
                 uniforms, normals), got {}",
                words.len()
            )
        })?;
        let increment = words[1].to_bits();
        if increment & 1 == 0 {
            return Err(format!(
                "the increment word holds the bits {increment:#018x}, which is \
                 even. Every PCG increment is odd, so the word was changed on \
                 the way: a NaN whose bits were rewritten is the usual cause."
            ));
        }
        let spare = if words[2].is_nan() {
            None
        } else if words[2].is_finite() {
            Some(words[2])
        } else {
            return Err(format!(
                "the spare word is {}; a spare is finite, or NaN for none.",
                words[2]
            ));
        };
        let count = |name: &str, v: f64| -> Result<u64, String> {
            if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v <= 9_007_199_254_740_992.0 {
                Ok(v as u64)
            } else {
                Err(format!("the {name} word holds {v}; a draw count is a whole number from 0."))
            }
        };
        Ok(RngState {
            state: words[0].to_bits(),
            increment,
            spare,
            uniforms: count("uniforms", words[3])?,
            normals: count("normals", words[4])?,
        })
    }
}

/// PCG-XSH-RR with 64-bit state and 32-bit output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pcg32 {
    state: u64,
    inc: u64,
}

/// `6364136223846793005`, split as `0x5851F42D_4C957F2D` in the reference implementation.
const PCG_MULTIPLIER: u64 = 0x5851_F42D_4C95_7F2D;

impl Pcg32 {
    /// Mirrors the reference implementation's constructor exactly:
    ///
    /// ```text
    /// inc   = (sequence << 1) | 1     // 32-bit shift, so the top bit lands in incHi
    /// state = 0; step(); state += seed; step();
    /// ```
    ///
    /// The reference implementation builds `inc` from `incHi = sequence >>> 31` and
    /// `incLo = (sequence << 1) | 1`, which together are exactly
    /// `((sequence as u64) << 1) | 1` — the high half is the bit that `<< 1`
    /// pushes out of 32 bits. Verified rather than assumed, because getting
    /// this wrong produces a plausible-looking stream that is simply a
    /// different one.
    ///
    /// # A 64-bit seed
    ///
    /// The seed is a `u64` and is added to the 64-bit state whole, which is
    /// PCG's own `pcg32_srandom_r(initstate, initseq)`. The reference
    /// implementation took a 32-bit seed, and every seed below `2^32` enters
    /// exactly as it did: `seed as u64` was the widening it always applied,
    /// so for those seeds this is the same arithmetic on the same values.
    /// Above `2^32` the high bits land in the high half of the state instead
    /// of being refused. Adding a constant is a bijection on `u64`, so two
    /// different seeds on one sequence always start from different states.
    pub fn new(seed: u64, sequence: u32) -> Self {
        let mut rng = Self {
            state: 0,
            inc: ((sequence as u64) << 1) | 1,
        };
        rng.step();
        rng.state = rng.state.wrapping_add(seed);
        rng.step();
        rng
    }

    /// Advance the state and return the XSH-RR permutation of the OLD state.
    ///
    /// The reference implementation computes the permutation from `oldHi`/`oldLo` captured
    /// before the multiply-add, which is standard PCG and is what makes the
    /// output independent of the next state. Ordering matters: permuting the
    /// new state would produce a valid-looking but different generator.
    fn step(&mut self) -> u32 {
        let old = self.state;
        self.state = old.wrapping_mul(PCG_MULTIPLIER).wrapping_add(self.inc);

        // xorshifted = (uint32)(((old >> 18) ^ old) >> 27)
        let xorshifted = (((old >> 18) ^ old) >> 27) as u32;
        // rot = old >> 59 — the top 5 bits
        let rot = (old >> 59) as u32;

        // The reference implementation writes this as `(xs >>> rot) | (xs << ((-rot) & 31))`.
        // The `(-rot) & 31` exists to make a rotation of 0 shift by 0 rather
        // than by 32, which would be undefined. `rotate_right` has that
        // behaviour natively.
        xorshifted.rotate_right(rot)
    }

    /// Next raw 32-bit output.
    pub fn next_u32(&mut self) -> u32 {
        self.step()
    }

    /// Uniform float in `[0, 1)`.
    ///
    /// The reference implementation divides by `4294967296` (2^32). Division of an exactly
    /// representable integer by a power of two is exact in IEEE-754, so this
    /// is one of the float operations that carries no parity risk at all.
    pub fn next_f64(&mut self) -> f64 {
        self.next_u32() as f64 / 4294967296.0
    }
}

/// The simulation-facing RNG: uniform, normal, ranged-int and boolean draws.
///
/// `PartialEq` compares STREAM POSITION, including the Box-Muller spare.
/// Tests use it to assert how many draws a function consumed, which for a
/// single shared stream is as load-bearing as what the function returned:
/// a call that draws one time too many silently reshuffles every later
/// consumer on the same tick.
#[derive(Debug, Clone)]
pub struct GameRng {
    pcg: Pcg32,
    spare: Option<f64>,
    /// Draw counts since construction, one per kind: the address index.
    uniforms: u64,
    normals: u64,
    /// The overlay and the log, both absent unless installed. Boxed so the
    /// generator stays small on the path that never uses them.
    overlay: Option<Box<DrawOverlay>>,
    log: Option<Box<DrawLog>>,
    /// The current site tag and day, written by the engine, read by the log.
    site: Site,
    tag: u32,
    day: i64,
}

/// Equality is STREAM POSITION, the spare included, as it was before draw
/// addressing: the counts, the overlay and the log describe the same
/// position and are excluded, so a test asserting that two generators sit
/// at the same point keeps its meaning.
impl PartialEq for GameRng {
    fn eq(&self, other: &Self) -> bool {
        self.pcg == other.pcg && self.spare == other.spare
    }
}

impl GameRng {
    /// A raw generator on `(seed, sequence)`. `seed` is any `u64`; see
    /// [`Pcg32::new`] for why every seed below `2^32` gives the stream it
    /// always gave.
    pub fn new(seed: u64, sequence: u32) -> Self {
        Self {
            pcg: Pcg32::new(seed, sequence),
            spare: None,
            uniforms: 0,
            normals: 0,
            overlay: None,
            log: None,
            site: Site::Unset,
            tag: 0,
            day: 0,
        }
    }

    // ── Draw addressing ────────────────────────────────────────────────

    /// The address the next uniform and the next normal would take.
    pub fn positions(&self) -> (u64, u64) {
        (self.uniforms, self.normals)
    }

    /// Install one substitution. The generator still advances at that
    /// address; only the value the consumer receives changes.
    pub fn patch(&mut self, kind: DrawKind, index: u64, value: f64) {
        self.overlay
            .get_or_insert_with(Default::default)
            .table
            .insert((kind, index), value);
    }

    pub fn overlay(&self) -> Option<&DrawOverlay> {
        self.overlay.as_deref()
    }

    pub fn set_overlay(&mut self, overlay: Option<DrawOverlay>) {
        self.overlay = overlay.filter(|o| !o.table.is_empty()).map(Box::new);
    }

    /// Log the draws taken on days `from_day..=to_day`.
    ///
    /// A second call widens the range to cover both and keeps what was
    /// recorded, so a caller tracing a window on top of an earlier trace
    /// loses nothing; the log is one range, so the days between two
    /// disjoint requests are logged too.
    pub fn enable_log(&mut self, from_day: i64, to_day: i64) {
        match self.log.as_deref_mut() {
            Some(log) => {
                // Spelled as comparisons: the parity scan keeps `.min`/`.max`
                // inside mathx even on integers, and a day is an integer.
                if from_day < log.from_day {
                    log.from_day = from_day;
                }
                if to_day > log.to_day {
                    log.to_day = to_day;
                }
            }
            None => {
                self.log = Some(Box::new(DrawLog { from_day, to_day, records: Vec::new() }));
            }
        }
    }

    pub fn log(&self) -> Option<&DrawLog> {
        self.log.as_deref()
    }

    /// Drop the entries the log holds, and keep the range it covers.
    ///
    /// For a copy that will never be asked what it recorded. The log is
    /// a recording buffer: nothing in this generator reads it, the draw
    /// counters and the range are untouched, and the next draw inside
    /// the range records as it would have. So a generator whose entries
    /// are dropped delivers the same values in the same order as one
    /// whose entries are kept, and the schedule and the derivation
    /// contract this file states are unaffected.
    ///
    /// The explanation store is what needs it. It copies the engine at
    /// each kept day's open, and a copy carries the log as it stood on
    /// that day, so N kept days held N squared over two days of it. At
    /// forty names over thirty days that was 1.6 GB of a store whose own
    /// documentation called itself one copy per day without the tape.
    pub fn clear_log_records(&mut self) {
        if let Some(log) = self.log.as_deref_mut() {
            log.records.clear();
            log.records.shrink_to_fit();
        }
    }

    pub fn set_day(&mut self, day: i64) {
        self.day = day;
    }

    #[inline]
    fn deliver(&mut self, kind: DrawKind, index: u64, raw: f64) -> f64 {
        let value = match &self.overlay {
            Some(o) => o.table.get(&(kind, index)).copied().unwrap_or(raw),
            None => raw,
        };
        if let Some(log) = &mut self.log {
            if log.from_day <= self.day && self.day <= log.to_day {
                log.records.push(DrawRecord {
                    kind,
                    index,
                    value,
                    day: self.day,
                    site: self.site,
                    tag: self.tag,
                });
            }
        }
        value
    }

    /// `createGameRng(seed)` in the reference implementation — note it uses sequence **0**,
    /// while the `GameRng` constructor defaults to **1**. That asymmetry is in
    /// the original and is load-bearing: the two entry points produce
    /// different streams from the same seed.
    pub fn from_seed(seed: u64) -> Self {
        Self::new(seed, 0)
    }

    /// A named substream of `root_seed`, per the derivation contract in
    /// [`stream`]'s module docs.
    ///
    /// One root seed, several independent generators: the engine seeds its
    /// market, economy and external streams through here, so perturbing what
    /// one domain draws cannot shift any other domain's sequence. The
    /// derivation is integer-only and documented as a formula a reader can
    /// reproduce; it is pinned by a golden test rather than trusted.
    ///
    /// A root seed below `2^32` takes the 32-bit derivation unchanged; one
    /// at or above it takes the 64-bit one. [`stream`]'s module docs state
    /// both and why the first is untouched.
    pub fn substream(root_seed: u64, stream_id: u32) -> Self {
        if root_seed >> 32 == 0 {
            let mixed = splitmix64_mix(stream_mix(root_seed, stream_id));
            Self::new(mixed >> 32, stream::STREAM_SEQUENCE_BASE + stream_id)
        } else {
            Self::new(
                splitmix64_mix(stream_mix(root_seed, stream_id)),
                stream::SEED64_SEQUENCE_BASE + stream_id,
            )
        }
    }

    /// The earnings calendar's key for `root_seed`: the first two raw
    /// outputs of the one-shot [`stream::EARNINGS`], high word first.
    pub fn earnings_key(root_seed: u64) -> u64 {
        let mut g = Self::substream(root_seed, stream::EARNINGS);
        let hi = g.pcg.next_u32() as u64;
        let lo = g.pcg.next_u32() as u64;
        (hi << 32) | lo
    }

    /// A KEYED generator: a fresh generator for one (key, a, b), where the
    /// earnings calendar passes its key, a company id's hash and a
    /// (quarter, slot) word. Integer-only, like every derivation here:
    ///
    /// ```text
    /// seed  = splitmix64_mix(key ^ splitmix64_mix(a ^ splitmix64_mix(b)))
    /// keyed = GameRng::new(seed, KEYED_SEQUENCE)            // = 1280
    /// ```
    ///
    /// No position, no log and no overlay: nothing holds it beyond the one
    /// report it prices, so there is nothing to snapshot but the key.
    pub fn keyed(key: u64, a: u64, b: u64) -> Self {
        let seed = splitmix64_mix(key ^ splitmix64_mix(a ^ splitmix64_mix(b)));
        Self::new(seed, stream::KEYED_SEQUENCE)
    }

    /// A surgery generator: the source of a re-randomised window of one
    /// stream, per the surgery derivation contract.
    ///
    /// # The surgery derivation contract
    ///
    /// A contract in the sense of the stream derivation in [`stream`]: a
    /// formula a reader reproduces, pinned by a golden test, and an era
    /// boundary if it changes. For a root seed `s`, a stream id `k` and a
    /// surgery seed `g`, both below `2^32`:
    ///
    /// ```text
    /// inner    = splitmix64_mix((s as u64) << 32 | k as u64)        // the stream's own mix
    /// mixed    = splitmix64_mix(inner ^ ((g as u64) << 32 | SURGERY_TAG as u64))
    /// seed_g   = mixed >> 32                                        // top 32 bits
    /// seq_g    = SURGERY_SEQUENCE_BASE + k                          // = 512 + k
    /// surgery  = GameRng::new(seed_g, seq_g)
    /// ```
    ///
    /// `splitmix64_mix` is the finalizer the stream contract names, and
    /// `SURGERY_TAG` is `0x5355_5247`. The same two properties carry the
    /// independence argument. Structurally, `512 + k` is no stream's
    /// sequence, so a surgery generator traverses an orbit no stream
    /// does and a re-randomised window can never be a shifted copy of
    /// the stream it replaces or of any other. By mixing, the second
    /// finalizer over the stream's own mix and the surgery seed gives
    /// each `(s, k, g)` an unrelated starting state, so two surgeries of
    /// one stream, or one surgery seed over two streams, share nothing
    /// but the formula.
    ///
    /// What the generator delivers is the caller's schedule: it draws
    /// uniforms and normals from it in the order of the addresses it
    /// replaces. `Engine.surgery_draws` on the Python side is that
    /// caller, and `World.window` is what asks.
    ///
    /// # Above `2^32`
    ///
    /// When the root seed and the surgery seed are both below `2^32` the
    /// formula above is the whole derivation, unchanged. When either is at
    /// or above it:
    ///
    /// ```text
    /// inner    = splitmix64_mix(stream_mix(s, k))    // the stream's own mix, either width
    /// mixed    = splitmix64_mix(inner ^ splitmix64_mix(g ^ (SURGERY_TAG << 32 | SEED64_TAG)))
    /// seed_g   = mixed                               // all 64 bits
    /// seq_g    = SEED64_SURGERY_SEQUENCE_BASE + k    // = 1024 + k
    /// ```
    ///
    /// For one root and stream, `g -> seed_g` is a composition of
    /// bijections on `u64`, so two surgery seeds never share a generator.
    pub fn surgery(root_seed: u64, stream_id: u32, surgery_seed: u64) -> Self {
        let inner = splitmix64_mix(stream_mix(root_seed, stream_id));
        if (root_seed | surgery_seed) >> 32 == 0 {
            let mixed = splitmix64_mix(
                inner ^ ((surgery_seed << 32) | stream::SURGERY_TAG as u64),
            );
            Self::new(mixed >> 32, stream::SURGERY_SEQUENCE_BASE + stream_id)
        } else {
            let key = ((stream::SURGERY_TAG as u64) << 32) | stream::SEED64_TAG as u64;
            let mixed = splitmix64_mix(inner ^ splitmix64_mix(surgery_seed ^ key));
            Self::new(mixed, stream::SEED64_SURGERY_SEQUENCE_BASE + stream_id)
        }
    }

    pub fn next_f64(&mut self) -> f64 {
        let raw = self.pcg.next_f64();
        let index = self.uniforms;
        self.uniforms += 1;
        self.deliver(DrawKind::Uniform, index, raw)
    }

    /// The generator's complete observable state.
    ///
    /// Three numbers: the LCG state, its increment, and the cached Box-Muller
    /// spare. That is ALL of it -- restore these and the next draw, and every
    /// draw after it, is the one that would have come next.
    ///
    /// The spare is the part that is easy to forget and fatal to omit.
    /// `next_normal` consumes two LCG steps and returns one value, keeping the
    /// other; a snapshot of the LCG alone would restore a generator that
    /// produces the right uniforms and the wrong normals, diverging on the
    /// first `next_normal` and looking correct until then.
    ///
    /// It also means "advance by N draws" is not a well-defined restore
    /// operation on this generator, which is why this is a state snapshot
    /// rather than a jump-ahead: N draws map to N or N+1 LCG steps depending
    /// on how the normals fell.
    pub fn snapshot(&self) -> RngState {
        RngState {
            state: self.pcg.state,
            increment: self.pcg.inc,
            spare: self.spare,
            uniforms: self.uniforms,
            normals: self.normals,
        }
    }

    /// Restore a generator to a snapshot. Exact, and O(1). The overlay and
    /// the log are not part of the position; the engine restores an
    /// overlay separately.
    pub fn restore(state: RngState) -> Self {
        Self {
            pcg: Pcg32 {
                state: state.state,
                inc: state.increment,
            },
            spare: state.spare,
            uniforms: state.uniforms,
            normals: state.normals,
            overlay: None,
            log: None,
            site: Site::Unset,
            tag: 0,
            day: 0,
        }
    }

    /// Box-Muller, caching the spare.
    ///
    /// Uses `libm` rather than `std` for `ln`, `sin` and `cos`. Phase 0 found
    /// that `std`'s `cos` differs from V8's by 1 ULP on real inputs while
    /// `libm`'s matches exactly — see the module docs. `sqrt` stays on `std`
    /// because IEEE-754 specifies it exactly, so every implementation agrees.
    ///
    /// Two faithfulness details, both easy to "improve" and both wrong to:
    ///
    /// 1. The reference implementation writes `const u = this.nextFloat() || 1e-10`. That is
    ///    a truthiness guard, not a comparison: it substitutes `1e-10` when
    ///    `nextFloat()` returns exactly `0.0`, which would otherwise make
    ///    `ln(0) = -inf`. It fires on exactly one of 2^32 outcomes. Reproduced
    ///    literally, including the specific constant.
    /// 2. The spare is `r * sin(...)` and the returned value is `r * cos(...)`
    ///    — in that order, with `sin` computed first. Swapping them would still
    ///    be valid Box-Muller and would still be a different sequence.
    pub fn next_normal(&mut self) -> f64 {
        let index = self.normals;
        self.normals += 1;
        let raw = self.next_normal_raw();
        self.deliver(DrawKind::Normal, index, raw)
    }

    /// Box-Muller on the generator directly. The two uniforms it takes are
    /// `pcg` steps, not addressable uniform draws (see the address contract
    /// at the top of this file), so a patched or logged normal never
    /// disturbs the uniform index.
    fn next_normal_raw(&mut self) -> f64 {
        if let Some(spare) = self.spare.take() {
            return spare;
        }
        let raw = self.pcg.next_f64();
        let u = if raw == 0.0 { 1e-10 } else { raw };
        let v = self.pcg.next_f64();
        let r = mathx::sqrt(-2.0 * mathx::log(u));
        self.spare = Some(r * mathx::sin(2.0 * std::f64::consts::PI * v));
        r * mathx::cos(2.0 * std::f64::consts::PI * v)
    }

    /// Integer in `[min, max]` inclusive.
    ///
    /// The reference implementation is `min + (this.pcg.next() % range)`, where `next()` is
    /// an unsigned 32-bit value held in a JS double, so `%` is exact integer
    /// remainder. Both languages truncate toward zero and both operands are
    /// non-negative, so the result matches.
    ///
    /// This is a modulo-biased draw — values below `2^32 % range` are very
    /// slightly more likely. That bias is in the original and is reproduced
    /// deliberately: removing it would change every stream in the simulation.
    pub fn next_int(&mut self, min: i64, max: i64) -> i64 {
        let range = max - min + 1;
        if range <= 0 {
            // JS would produce NaN or Infinity here and poison downstream
            // arithmetic silently. Returning `min` is a deliberate divergence
            // from a case the reference implementation never exercises; if a golden vector
            // ever hits it, this must be revisited rather than papered over.
            return min;
        }
        min + (self.pcg.next_u32() as i64 % range)
    }

    /// True with probability `p`.
    pub fn next_bool(&mut self, p: f64) -> bool {
        self.next_f64() < p
    }
}

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

    /// The publication draws (`cycle_publication_lag_draw`): the documented
    /// formula, in [0, 1), reproducible, distinct over turns and seeds.
    #[test]
    fn publication_draws_are_the_documented_stateless_formula() {
        let key = publication_key(7);
        assert_eq!(key, splitmix64_mix(7 ^ ((0x5055_424Cu64 << 32) | 0xFFFF_FFFF)));
        for k in 0..2000u64 {
            let u = publication_uniform(key, k);
            assert!((0.0..1.0).contains(&u), "{u}");
            let z = splitmix64_mix(key ^ splitmix64_mix((0x5055_424Cu64 << 32) | k));
            assert_eq!(u, (z >> 11) as f64 / (1u64 << 53) as f64);
            assert_eq!(u, publication_uniform(key, k));
        }
        assert_ne!(publication_uniform(key, 0), publication_uniform(key, 1));
        assert_ne!(publication_key(7), publication_key(8));
        assert_ne!(publication_key(7), publication_key(7 | (1 << 40)));
        let mean: f64 = (0..10_000u64).map(|k| publication_uniform(key, k)).sum::<f64>() / 10_000.0;
        assert!((mean - 0.5).abs() < 0.01, "{mean}");
    }

    /// The state after construction is not something the reference implementation exposes,
    /// so this pins the internal sequence instead: the first outputs must be
    /// stable across refactors of this file.
    #[test]
    fn is_deterministic_for_a_given_seed() {
        let mut a = GameRng::from_seed(42);
        let mut b = GameRng::from_seed(42);
        for _ in 0..1000 {
            assert_eq!(a.next_f64().to_bits(), b.next_f64().to_bits());
        }
    }

    #[test]
    fn different_seeds_diverge() {
        let mut a = GameRng::from_seed(42);
        let mut b = GameRng::from_seed(43);
        let differs = (0..100).any(|_| a.next_f64() != b.next_f64());
        assert!(differs, "seeds 42 and 43 produced identical prefixes");
    }

    /// `createGameRng` uses sequence 0 and the bare constructor defaults to 1.
    /// If someone "tidies" that away, this fails.
    #[test]
    fn sequence_zero_and_one_are_different_streams() {
        let mut a = GameRng::new(42, 0);
        let mut b = GameRng::new(42, 1);
        let differs = (0..100).any(|_| a.next_f64() != b.next_f64());
        assert!(differs, "sequence 0 and 1 produced the same stream");
    }

    #[test]
    fn floats_are_in_unit_interval() {
        let mut rng = GameRng::from_seed(7);
        for _ in 0..100_000 {
            let x = rng.next_f64();
            assert!((0.0..1.0).contains(&x), "out of range: {x}");
        }
    }

    /// The spare must be returned on the very next call, unmodified — the
    /// caching is observable in the output sequence, not an implementation
    /// detail.
    #[test]
    fn normal_spare_is_returned_next_and_unchanged() {
        let mut probe = GameRng::from_seed(11);
        let _first = probe.next_normal();
        let cached = probe.spare;
        assert!(cached.is_some(), "first next_normal did not cache a spare");

        let second = probe.next_normal();
        assert_eq!(second.to_bits(), cached.unwrap().to_bits());
        assert!(probe.spare.is_none(), "spare was not consumed");
    }

    #[test]
    fn next_int_stays_within_bounds() {
        let mut rng = GameRng::from_seed(3);
        for _ in 0..100_000 {
            let v = rng.next_int(-5, 5);
            assert!((-5..=5).contains(&v), "out of range: {v}");
        }
    }

    #[test]
    fn to_uint32_matches_javascript_coercion() {
        // The cases that actually differ between a naive `as u32` and JS.
        assert_eq!(to_uint32(0.0), 0);
        assert_eq!(to_uint32(42.0), 42);
        assert_eq!(to_uint32(4294967296.0), 0, "2^32 wraps to 0");
        assert_eq!(to_uint32(-1.0), 4294967295, "-1 wraps to u32::MAX");
        assert_eq!(to_uint32(4294967297.0), 1, "2^32 + 1 wraps to 1");
        assert_eq!(to_uint32(2147483648.0), 2147483648, "2^31 is unchanged");
        assert_eq!(to_uint32(1.9), 1, "truncates toward zero");
        assert_eq!(to_uint32(-1.9), 4294967295, "truncates, then wraps");
        assert_eq!(to_uint32(f64::NAN), 0);
        assert_eq!(to_uint32(f64::INFINITY), 0);
    }
}

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

    /// A patch substitutes the value and leaves the generator's position,
    /// every later draw and both counts exactly as they were.
    #[test]
    fn a_patch_substitutes_without_moving_the_stream() {
        let mut plain = GameRng::new(42, 7);
        let mut patched = GameRng::new(42, 7);
        patched.patch(DrawKind::Uniform, 3, 0.25);
        patched.patch(DrawKind::Normal, 2, -1.5);
        for i in 0..12u64 {
            let (a, b) = (plain.next_f64(), patched.next_f64());
            if i == 3 {
                assert_eq!(b, 0.25);
            } else {
                assert_eq!(a.to_bits(), b.to_bits());
            }
            let (c, d) = (plain.next_normal(), patched.next_normal());
            if i == 2 {
                assert_eq!(d, -1.5);
            } else {
                assert_eq!(c.to_bits(), d.to_bits());
            }
        }
        assert_eq!(plain, patched, "the positions diverged");
        assert_eq!(plain.positions(), patched.positions());
    }

    /// Normals index by normal count: the spare has an address of its own
    /// and Box-Muller's inner uniforms never touch the uniform index.
    #[test]
    fn normals_index_by_normal_count_and_uniforms_by_uniform_count() {
        let mut rng = GameRng::new(3, 3);
        rng.next_normal();
        rng.next_normal();
        rng.next_f64();
        assert_eq!(rng.positions(), (1, 2));
        let mut other = GameRng::new(3, 3);
        other.patch(DrawKind::Normal, 1, 9.0);
        other.next_normal();
        assert_eq!(other.next_normal(), 9.0, "the spare's address is normal 1");
        // The patch never moved the generator: the first uniform after two
        // normals is the same on a patched and an unpatched generator.
        let mut plain = GameRng::new(3, 3);
        plain.next_normal();
        plain.next_normal();
        assert_eq!(other.next_f64().to_bits(), plain.next_f64().to_bits());
        assert_eq!(other.positions(), (1, 2));
    }

    #[test]
    fn the_log_records_what_the_consumer_received() {
        let mut rng = GameRng::new(5, 5);
        rng.patch(DrawKind::Uniform, 1, 0.5);
        rng.enable_log(0, 0);
        rng.set_day(0);
        rng.site(Site::External, 7);
        let first = rng.next_f64();
        let second = rng.next_f64();
        let z = rng.next_normal();
        let log = rng.log().unwrap();
        assert_eq!(log.records.len(), 3);
        assert_eq!(log.records[0].value, first);
        assert_eq!((log.records[1].kind, log.records[1].index, log.records[1].value), (DrawKind::Uniform, 1, 0.5));
        assert_eq!(second, 0.5);
        assert_eq!((log.records[2].kind, log.records[2].index, log.records[2].value, log.records[2].site, log.records[2].tag),
                   (DrawKind::Normal, 0, z, Site::External, 7));
        rng.set_day(1);
        rng.next_f64();
        assert_eq!(rng.log().unwrap().records.len(), 3, "a day outside the range is not logged");
    }

    #[test]
    fn a_restored_generator_keeps_its_addresses() {
        let mut rng = GameRng::new(9, 9);
        for _ in 0..5 {
            rng.next_f64();
            rng.next_normal();
        }
        let restored = GameRng::restore(rng.snapshot());
        assert_eq!(restored.positions(), (5, 5));
        assert_eq!(restored, rng);
    }
}

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

    /// The derivation is a documented contract, so it is pinned to the
    /// formula's hand-computed values rather than to "whatever the code
    /// does". If this fails, either the formula in the [`stream`] docs or
    /// this test is wrong — and a silent re-derivation would strand every
    /// recorded result of the era, so failing loudly is the point.
    #[test]
    fn substream_derivation_is_the_documented_formula() {
        // splitmix64_mix(42 << 32 | k), top 32 bits, computed independently.
        for (id, seed) in [
            (stream::MARKET, 0xEA67_E2F1_u64),
            (stream::ECONOMY, 0x6997_3300),
            (stream::EXTERNAL, 0x4B07_4493),
        ] {
            let mut derived = GameRng::substream(42, id);
            let mut expected = GameRng::new(seed, stream::STREAM_SEQUENCE_BASE + id);
            for _ in 0..64 {
                assert_eq!(
                    derived.next_f64().to_bits(),
                    expected.next_f64().to_bits(),
                    "stream {id} does not match the documented derivation"
                );
            }
        }
    }

    /// The surgery derivation, pinned to hand-computed values of the
    /// documented formula for the reason the stream derivation is: a
    /// silent re-derivation would move every recorded window.
    #[test]
    fn surgery_derivation_is_the_documented_formula() {
        // splitmix64_mix(splitmix64_mix(s << 32 | k) ^ (g << 32 | 0x53555247)),
        // top 32 bits, computed independently.
        for (root, id, surgery, seed) in [
            (42_u64, stream::JUMPS, 7_u64, 0x493A_2503_u64),
            (42, stream::MARKET, 1, 0xF382_1A83),
            (7, stream::VOLUME_IDIO, 0, 0x3D21_372F),
        ] {
            let mut derived = GameRng::surgery(root, id, surgery);
            let mut expected = GameRng::new(seed, stream::SURGERY_SEQUENCE_BASE + id);
            for _ in 0..64 {
                assert_eq!(
                    derived.next_f64().to_bits(),
                    expected.next_f64().to_bits(),
                    "surgery ({root}, {id}, {surgery}) does not match the documented derivation"
                );
            }
        }
    }

    #[test]
    fn a_surgery_differs_from_its_stream_and_from_other_surgeries() {
        let mut own = GameRng::substream(42, stream::JUMPS);
        let mut a = GameRng::surgery(42, stream::JUMPS, 7);
        assert!((0..64).any(|_| own.next_f64() != a.next_f64()));
        let mut a = GameRng::surgery(42, stream::JUMPS, 7);
        let mut b = GameRng::surgery(42, stream::JUMPS, 8);
        assert!((0..64).any(|_| a.next_f64() != b.next_f64()));
        let mut a = GameRng::surgery(42, stream::JUMPS, 7);
        let mut c = GameRng::surgery(42, stream::MARKET, 7);
        assert!((0..64).any(|_| a.next_f64() != c.next_f64()));
        let mut a = GameRng::surgery(42, stream::JUMPS, 7);
        let mut d = GameRng::surgery(43, stream::JUMPS, 7);
        assert!((0..64).any(|_| a.next_f64() != d.next_f64()));
    }

    #[test]
    fn substreams_of_one_root_differ_from_each_other() {
        let ids = [stream::MARKET, stream::ECONOMY, stream::EXTERNAL];
        for a in ids {
            for b in ids {
                if a == b {
                    continue;
                }
                let mut x = GameRng::substream(7, a);
                let mut y = GameRng::substream(7, b);
                assert!(
                    (0..64).any(|_| x.next_f64() != y.next_f64()),
                    "streams {a} and {b} agree on a 64-draw prefix"
                );
            }
        }
    }

    #[test]
    fn substreams_differ_across_roots() {
        let mut x = GameRng::substream(1, stream::MARKET);
        let mut y = GameRng::substream(2, stream::MARKET);
        assert!((0..64).any(|_| x.next_f64() != y.next_f64()));
    }

    /// The failure the distinct-sequence half of the contract rules out:
    /// one substream must never be a time-shifted copy of another. Checked
    /// over a window rather than proved — the proof is that different odd
    /// increments give different LCG orbits, which holds by construction —
    /// so this is the tripwire for someone replacing the derivation with
    /// one that reuses an increment.
    #[test]
    fn no_substream_is_a_shifted_copy_of_another() {
        let ids = [stream::MARKET, stream::ECONOMY, stream::EXTERNAL];
        for a in ids {
            for b in ids {
                if a == b {
                    continue;
                }
                let reference: Vec<u32> = {
                    let mut rng = GameRng::substream(2026, a);
                    (0..64).map(|_| rng.pcg.next_u32()).collect()
                };
                let window: Vec<u32> = {
                    let mut rng = GameRng::substream(2026, b);
                    (0..1024).map(|_| rng.pcg.next_u32()).collect()
                };
                assert!(
                    !window
                        .windows(reference.len())
                        .any(|w| w == reference.as_slice()),
                    "stream {b} replays stream {a}'s prefix at an offset"
                );
            }
        }
    }

    /// The substreams must also stay clear of every stream in historical
    /// use with the same nominal seed — a consumer holding root seed 42
    /// must not find the engine's market stream replaying `GameRng::new(42, 99)`.
    #[test]
    fn substreams_do_not_replay_the_legacy_streams() {
        for legacy_sequence in [0, 1, 21, 99] {
            for id in [stream::MARKET, stream::ECONOMY, stream::EXTERNAL] {
                let mut legacy = GameRng::new(42, legacy_sequence);
                let mut derived = GameRng::substream(42, id);
                assert!(
                    (0..64).any(|_| derived.next_f64() != legacy.next_f64()),
                    "substream {id} replays legacy sequence {legacy_sequence}"
                );
            }
        }
    }
}

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

    #[test]
    fn a_restored_generator_continues_the_same_stream() {
        let mut original = GameRng::new(42, 7);
        for _ in 0..37 {
            original.next_f64();
        }
        let mark = original.snapshot();
        let expected: Vec<f64> = (0..20).map(|_| original.next_f64()).collect();

        let mut restored = GameRng::restore(mark);
        let actual: Vec<f64> = (0..20).map(|_| restored.next_f64()).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn the_cached_spare_is_part_of_the_state() {
        // The field a snapshot is most likely to omit, and the one that makes
        // omission invisible: uniforms would still match, and only the first
        // normal after the restore would differ.
        let mut original = GameRng::new(11, 3);
        // An ODD number of normals, so a spare is left cached.
        original.next_normal();
        assert!(original.snapshot().spare.is_some(), "expected a cached spare");

        let mark = original.snapshot();
        let expected = original.next_normal();
        assert_eq!(GameRng::restore(mark).next_normal(), expected);

        // And a snapshot that dropped the spare would diverge here -- shown
        // rather than asserted about, so the test proves the field matters.
        let mut without_spare = GameRng::restore(RngState {
            spare: None,
            ..mark
        });
        assert_ne!(without_spare.next_normal(), expected);
    }

    #[test]
    fn a_snapshot_survives_a_mixed_stream() {
        // Uniforms and normals interleaved is the real usage shape: the tick
        // draws both, so a snapshot taken mid-tick must restore either kind.
        let mut original = GameRng::new(5, 99);
        for i in 0..25 {
            if i % 3 == 0 {
                original.next_normal();
            } else {
                original.next_f64();
            }
        }
        let mark = original.snapshot();
        let expected: Vec<f64> = (0..30)
            .map(|i| {
                if i % 2 == 0 {
                    original.next_normal()
                } else {
                    original.next_f64()
                }
            })
            .collect();

        let mut restored = GameRng::restore(mark);
        let actual: Vec<f64> = (0..30)
            .map(|i| {
                if i % 2 == 0 {
                    restored.next_normal()
                } else {
                    restored.next_f64()
                }
            })
            .collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn two_different_positions_do_not_snapshot_alike() {
        // Otherwise every test above passes on a snapshot that captures
        // nothing.
        let mut rng = GameRng::new(1, 1);
        let first = rng.snapshot();
        rng.next_f64();
        assert_ne!(first, rng.snapshot());
    }
}

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

    const WIDE: u64 = (1 << 63) + 12345;

    fn same_prefix(a: &mut GameRng, b: &mut GameRng) -> bool {
        (0..64).all(|_| a.next_f64().to_bits() == b.next_f64().to_bits())
    }

    /// The wide derivation, pinned to hand-computed values of the formula
    /// in [`stream`]'s docs, for the reason the 32-bit one is pinned: a
    /// silent re-derivation would move every recorded wide-seed market.
    #[test]
    fn wide_substream_derivation_is_the_documented_formula() {
        // splitmix64_mix(s ^ splitmix64_mix(0x53443634 << 32 | k)), all 64
        // bits, computed independently.
        for (root, id, seed) in [
            (1_u64 << 32, stream::MARKET, 0x7547_BEE2_B588_1CEC_u64),
            (WIDE, stream::ECONOMY, 0xF98D_6EE9_28B9_562B),
            (u64::MAX, stream::EXTERNAL, 0x58C7_9E4C_21E1_08AB),
            (0xDEAD_BEEF_0000_0001, stream::NEWS, 0x85B0_9E41_94B4_8998),
        ] {
            let mut derived = GameRng::substream(root, id);
            let mut expected = GameRng::new(seed, stream::SEED64_SEQUENCE_BASE + id);
            assert!(same_prefix(&mut derived, &mut expected),
                    "wide root {root:#x}, stream {id} does not match the documented formula");
        }
    }

    #[test]
    fn wide_surgery_derivation_is_the_documented_formula() {
        for (root, id, surgery, seed) in [
            (42_u64, stream::JUMPS, 1_u64 << 32, 0x619E_7212_72AA_47E0_u64),
            (WIDE, stream::JUMPS, 7, 0xE96A_D364_3F0A_0013),
            (u64::MAX, stream::MARKET, u64::MAX, 0xA2CB_0D15_ABB5_23B0),
        ] {
            let mut derived = GameRng::surgery(root, id, surgery);
            let mut expected =
                GameRng::new(seed, stream::SEED64_SURGERY_SEQUENCE_BASE + id);
            assert!(same_prefix(&mut derived, &mut expected),
                    "surgery ({root:#x}, {id}, {surgery:#x}) does not match the documented formula");
        }
    }

    /// The last 32-bit root and the first wide one sit either side of the
    /// switch. The first must still be the old formula, and the second
    /// must not be root 0 with its high bit dropped, which is what a
    /// truncating derivation would give.
    #[test]
    fn the_boundary_is_at_two_to_the_thirty_two() {
        let top = (1_u64 << 32) - 1;
        let old = splitmix64_mix((top << 32) | stream::MARKET as u64) >> 32;
        let mut a = GameRng::substream(top, stream::MARKET);
        let mut b = GameRng::new(old, stream::STREAM_SEQUENCE_BASE + stream::MARKET);
        assert!(same_prefix(&mut a, &mut b));
        assert_eq!(a.snapshot().increment, b.snapshot().increment);

        let mut wide = GameRng::substream(1 << 32, stream::MARKET);
        let mut zero = GameRng::substream(0, stream::MARKET);
        assert!(!same_prefix(&mut wide, &mut zero));
        assert_ne!(GameRng::substream(1 << 32, stream::MARKET).snapshot().increment,
                   GameRng::substream(0, stream::MARKET).snapshot().increment);
    }

    #[test]
    fn roots_differing_only_in_the_high_bits_are_different_markets() {
        for low in [0_u64, 5, 0xFFFF_FFFF] {
            for high in [1_u64, 2, 0x8000_0000, 0xFFFF_FFFF] {
                for id in 0..stream::COUNT as u32 {
                    let mut a = GameRng::substream(low, id);
                    let mut b = GameRng::substream(low | (high << 32), id);
                    assert!(!same_prefix(&mut a, &mut b),
                            "root {low:#x} and {:#x} share stream {id}", low | (high << 32));
                }
                let mut a = GameRng::surgery(low, stream::JUMPS, 3);
                let mut b = GameRng::surgery(low | (high << 32), stream::JUMPS, 3);
                assert!(!same_prefix(&mut a, &mut b));
                let mut a = GameRng::surgery(7, stream::JUMPS, low);
                let mut b = GameRng::surgery(7, stream::JUMPS, low | (high << 32));
                assert!(!same_prefix(&mut a, &mut b));
            }
        }
    }

    /// No two wide roots start a stream from the same state. A bijection
    /// by construction; this is the tripwire on a sample that includes
    /// roots differing only in their high half and only in their low half.
    #[test]
    fn no_two_wide_roots_on_a_sample_share_a_starting_state() {
        use std::collections::HashSet;
        for id in [stream::MARKET, stream::ECONOMY, stream::NEWS] {
            let mut states = HashSet::new();
            let mut roots = 0;
            for high in 1_u64..=128 {
                for low in 0_u64..128 {
                    let root = (high << 32) | low;
                    assert!(states.insert(GameRng::substream(root, id).snapshot().state),
                            "root {root:#x} repeats a starting state on stream {id}");
                    roots += 1;
                }
            }
            // And the far end of the range.
            for offset in 0_u64..1024 {
                assert!(states.insert(GameRng::substream(u64::MAX - offset, id).snapshot().state));
                roots += 1;
            }
            assert_eq!(states.len(), roots);
        }
    }

    /// Every stream of a wide root is on a sequence no 32-bit root uses,
    /// stream or surgery, so the two ranges never share an orbit.
    #[test]
    fn wide_roots_use_sequences_no_narrow_root_does() {
        let narrow: std::collections::HashSet<u64> = (0..=stream::OPENING)
            .flat_map(|id| {
                [GameRng::substream(42, id).snapshot().increment,
                 GameRng::surgery(42, id, 1).snapshot().increment]
            })
            .collect();
        for id in 0..=stream::OPENING {
            assert!(!narrow.contains(&GameRng::substream(WIDE, id).snapshot().increment));
            assert!(!narrow.contains(&GameRng::surgery(WIDE, id, 1).snapshot().increment));
            assert!(!narrow.contains(&GameRng::surgery(42, id, 1 << 40).snapshot().increment));
        }
    }

    /// The arrival priority is the documented formula, pinned by golden
    /// values that `tests/test_arrival_order.py` computes independently in
    /// Python.
    #[test]
    fn arrival_priority_is_the_documented_formula() {
        assert_eq!(arrival_priority(201, 0, 0, "a"), 0x09f6_9160_e6ea_96dc);
        assert_eq!(arrival_priority(201, 3, 1, "b"), 0x3bc1_d0a9_9543_6b68);
        assert_eq!(arrival_priority((1 << 40) + 7, 5, 2, "claude"), 0x32c6_8be7_c13f_fe3b);
        // order(201, 3, 1, [a, b]) is [b, a].
        assert!(arrival_priority(201, 3, 1, "b") < arrival_priority(201, 3, 1, "a"));
        assert_eq!(fnv1a64(b""), 0xCBF2_9CE4_8422_2325);
        assert_eq!(fnv1a64(b"a"), 0xAF63_DC4C_8601_EC8C);
    }

    /// The raw generator takes the seed whole: below `2^32` it is the
    /// arithmetic it always was, and above it the high half reaches the
    /// state rather than being dropped.
    #[test]
    fn the_raw_generator_takes_all_sixty_four_bits() {
        let mut a = GameRng::new(0xFFFF_FFFF, 21);
        let mut b = GameRng::new(u32::MAX as u64, 21);
        assert!(same_prefix(&mut a, &mut b));
        let mut wide = GameRng::new(1 << 32, 21);
        let mut zero = GameRng::new(0, 21);
        assert!(!same_prefix(&mut wide, &mut zero));
        let mut top = GameRng::new(u64::MAX, 21);
        let mut other = GameRng::new(u64::MAX - (1 << 32), 21);
        assert!(!same_prefix(&mut top, &mut other));
    }
}