zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
//! Which worker should run the next task.
//!
//! Two things have to be true at once: the choice must exploit what has been
//! measured, and it must keep learning, because a mesh changes underneath the
//! estimates. Thompson sampling does both without an explore/exploit schedule
//! to tune — draw each candidate's service time from its own posterior, then
//! take the best. A worker measured a hundred times has a narrow posterior and
//! is judged on its merits; one measured twice has a wide one and is sometimes
//! sampled favourably and tried. A worker measured *never* is neither instantly
//! the best (which is what made an unmeasured worker outrank a 5 ms one) nor
//! starved.
//!
//! Only the service time is sampled. Success and trust use their posterior
//! means: they move the cost far less than latency does, and sampling a Beta
//! needs machinery this does not otherwise need.

use super::estimator::Stats;
use super::sampler::{best_of_d, AliasTable, Rng};

/// What the policy knows about one candidate worker.
#[derive(Debug, Clone)]
pub struct Candidate {
    pub stats: Stats,
    /// Requests already handed to it and not yet finished.
    pub in_flight: u32,
    /// Yen per hour, for the cost term.
    pub price_per_hour: f64,
    /// On this broker's own node, i.e. reached over loopback rather than
    /// across the mesh. Only used while a worker is unmeasured, to pick which
    /// prior it starts from -- once there are observations they already carry
    /// the transport, because what gets recorded is the whole round trip.
    pub local: bool,
}

/// How the terms trade off. Defaults optimise for completion time, with price
/// and failure as secondary.
#[derive(Debug, Clone, Copy)]
pub struct Weights {
    pub latency: f64,
    pub price: f64,
    /// What a failure costs, as a multiple of the expected service time — a
    /// failed task is the whole wait plus doing it again somewhere else.
    pub retry: f64,
    /// Assumed round trip, in ms, for a worker across the mesh that nothing is
    /// known about. It only has to be the right order of magnitude: the
    /// posterior takes over as soon as there are real observations.
    pub unmeasured_ms: f64,
    /// What reaching another node costs, in ms, before that node does any
    /// work. Added to the assumed service time of an unmeasured PEER only --
    /// a mesh hop is real and a loopback one is not, so assuming both cost
    /// the same told the policy a lie it could only correct by paying for it:
    /// on a cold broker every worker looked identical, the tie went to
    /// whoever sorted first, and `zc bench` sent 100% of a run across the
    /// network to a 262 ms peer while four workers on the same box answered
    /// in 1.4 ms.
    ///
    /// It is not added to a MEASURED worker: what gets recorded is the whole
    /// round trip, so its posterior already contains the hop.
    pub mesh_hop_ms: f64,
    /// Candidates sampled per decision (the power-of-`d`-choices `d`). Higher
    /// `d` filters harder for the same weighting, at more work per decision
    /// — still O(1) in the size of the fleet. See #264 for the sweep behind
    /// the default.
    pub candidates_per_choice: usize,
    /// Exponent on the inverse-completion-time weight used to build the
    /// sampling table (see [`table_weight`]). 1.0 is linear, 2.0 squares it.
    /// Sharper concentrates load on the fastest workers, which helps the
    /// median and hurts the tail once they start queueing. See #264 for the
    /// sweep behind the default.
    pub weighting_exponent: f64,
    /// Exponent on the queue term `(1 + in_flight)` used by both [`cost`] and
    /// [`table_weight`]. 1.0 is linear; above 1.0 is convex and pushes back
    /// harder as a worker's queue fills, which is the tail case. See #264 for
    /// the sweep behind the default.
    pub queue_convexity: f64,
    /// How much service-time evidence, in observations, a worker is topped up
    /// to from the workers like it (same side of the mesh hop) when it has
    /// less of its own: see [`with_fleet_prior`]. 0 turns the pooling off.
    pub fleet_prior_weight: f64,
    /// Probability that a decision ignores the learned weights and picks a
    /// candidate uniformly: a floor under every worker's chance of being
    /// measured again. 0 turns it off. See [`choose`] and #440.
    pub explore_floor: f64,
}

impl Default for Weights {
    fn default() -> Self {
        Weights {
            latency: 1.0,
            price: 0.0,
            retry: 2.0,
            unmeasured_ms: 250.0,
            mesh_hop_ms: 250.0,
            candidates_per_choice: 4,
            weighting_exponent: 2.0,
            queue_convexity: 1.0,
            fleet_prior_weight: FLEET_PRIOR_WEIGHT,
            explore_floor: EXPLORE_FLOOR,
        }
    }
}

/// The default [`Weights::fleet_prior_weight`]: top up to one observation,
/// enough to replace the flat prior and no more (#438).
pub const FLEET_PRIOR_WEIGHT: f64 = 1.0;

/// The default [`Weights::explore_floor`] (#440). A worker's posterior only
/// changes when it is chosen, and the policy's own sharp weighting (squared
/// table weight, Thompson draw, best of `d`) stops choosing a worker it is
/// confident is slow, so without a floor a worker that becomes fast is
/// rediscovered only if the early draws happened to leave its estimate thin.
/// 0.5 % (one decision in 200) is all it takes: a few fast replies from a
/// worker widen its posterior and the policy itself takes over. A bigger
/// floor buys nothing on rediscovery and costs the tail: at 2 % the mixed
/// 20,20,200,200 ms bench's p99 doubled, because each exploratory pick of a
/// 200 ms worker is a slow request by construction.
pub const EXPLORE_FLOOR: f64 = 0.005;

/// What to assume a worker nothing has been measured on will take.
///
/// The unknown is its service time, and that is the same unknown wherever it
/// sits, so both start from `unmeasured_ms`. What differs is the trip: a peer
/// also costs a network hop before it begins, and that part is not unknown.
/// Adding it keeps an unmeasured worker from being favoured blindly -- an
/// unmeasured local worker is assumed exactly as slow as it was before -- and
/// still breaks the tie toward this node, which is the decision that was
/// being made at random.
fn unmeasured_ms(candidate_local: bool, w: &Weights) -> f64 {
    if candidate_local {
        w.unmeasured_ms
    } else {
        w.unmeasured_ms + w.mesh_hop_ms
    }
}

/// A standard normal, by Box-Muller.
fn standard_normal(rng: &mut Rng) -> f64 {
    // u1 must not be 0, or ln(0) is -inf.
    let u1 = rng.next_f64().max(f64::MIN_POSITIVE);
    let u2 = rng.next_f64();
    (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}

/// Draw a plausible service time for this worker from its posterior.
///
/// With `n` observations of log service time, the posterior over the mean log
/// is Normal(μ̂, σ̂²/n): the more that has been seen, the tighter the draw sits
/// to what was measured. With nothing measured, fall back to the assumed time
/// with a wide spread, so the worker is tried but not favoured.
pub fn sample_service_ms(stats: &Stats, local: bool, w: &Weights, rng: &mut Rng) -> f64 {
    let n = stats.weight();
    match (stats.median_service_ms(), n >= 1.0) {
        (Some(median), true) => {
            let sd = stats.log_sd().unwrap_or(0.5).max(0.05);
            let spread = sd / n.sqrt();
            (median.ln() + standard_normal(rng) * spread).exp()
        }
        _ => (unmeasured_ms(local, w).ln() + standard_normal(rng) * 0.8).exp(),
    }
}

/// What handing this task to this worker is expected to cost.
///
/// Queue first: what a caller waits for is the work already in front of it
/// plus its own. Ranking on service time alone piles every task onto the same
/// "fastest" worker until it is deep in its own queue — measured on a live
/// mesh, that moved p90 from 2.07 s to 6.14 s.
pub fn cost(candidate: &Candidate, sampled_service_ms: f64, w: &Weights) -> f64 {
    let queue = (1.0 + candidate.in_flight as f64).powf(w.queue_convexity);
    let completion = sampled_service_ms * queue;
    let failure = 1.0 - candidate.stats.success_rate() * candidate.stats.trust();
    let price = candidate.price_per_hour * sampled_service_ms / 3_600_000.0;
    w.latency * completion + w.price * price + w.retry * failure * completion
}

/// Every candidate, with any shortfall below `w.fleet_prior_weight`
/// observations of service time made up from the other candidates on the same
/// side of the mesh hop (local with local, peers with peers).
///
/// The flat `unmeasured_ms` prior is right on a cold broker, where nothing is
/// known about anyone. It is wrong for a worker whose siblings have been
/// measured: four identical local workers at 4 ms, three measured and one not
/// yet, read as 4, 4, 4 and 250 ms, and an unmeasured worker 60x slower than
/// the rest on paper is never drawn, so it is never measured either. Lending
/// it its siblings' evidence -- they are the best guess for a worker of the
/// same kind on the same side of the hop -- puts it back among them until its
/// own replies say otherwise (#438). The top-up stops at one observation's
/// worth, so a worker the policy has actually measured is judged on its own
/// evidence: pulling measured slow workers toward a mixed pool cost the
/// #264 mesh nearly 2x on p99 for no gain on identical workers.
///
/// O(n) for the pool, then O(1) per candidate. With nothing measured on a
/// side, or a weight of 0, candidates are returned unchanged.
pub fn with_fleet_prior(candidates: &[Candidate], w: &Weights) -> Vec<Candidate> {
    if w.fleet_prior_weight <= 0.0 {
        return candidates.to_vec();
    }
    let mut pool = [Stats::new(), Stats::new()];
    for c in candidates {
        pool[usize::from(c.local)].merge(&c.stats);
    }
    candidates
        .iter()
        .map(|c| {
            let others = pool[usize::from(c.local)].service_without(&c.stats);
            Candidate {
                stats: c
                    .stats
                    .with_service_prior(&others, w.fleet_prior_weight - c.stats.weight()),
                ..c.clone()
            }
        })
        .collect()
}

/// Pick a worker: `d` constant-time draws, each judged on a sample from its
/// own posterior. Independent of how many workers exist.
pub fn choose(
    candidates: &[Candidate],
    table: &AliasTable,
    rng: &mut Rng,
    d: usize,
    w: &Weights,
) -> Option<usize> {
    if candidates.is_empty() || table.is_empty() {
        return None;
    }
    // The exploration floor: a small fixed share of decisions goes to a
    // uniformly chosen candidate, so no worker's chance of being measured
    // again can fall to zero however confident the estimates are (#440).
    if w.explore_floor > 0.0 && rng.next_f64() < w.explore_floor {
        let i = (rng.next_f64() * candidates.len() as f64) as usize;
        return Some(i.min(candidates.len() - 1));
    }
    // Sampled once per candidate considered, inside the cost closure, so a
    // worker drawn twice is judged on two independent samples -- from a
    // stream of its own. A clone of `rng` replays the very numbers that
    // picked the candidate, so which worker was drawn decided how extreme its
    // sample was: on four tied workers, index 0 always drew |z| > 1.66 and
    // index 3 always |z| < 0.76 (#438).
    let sampled = std::cell::RefCell::new(Rng::seeded((rng.next_f64() * u64::MAX as f64) as u64));
    let chosen = best_of_d(table, rng, d, |i| {
        let c = &candidates[i];
        let s = sample_service_ms(&c.stats, c.local, w, &mut sampled.borrow_mut());
        cost(c, s, w)
    });
    chosen.filter(|i| *i < candidates.len())
}

/// The weight a worker gets in the sampling table, rebuilt once a tick.
///
/// Inverse expected completion: a worker twice as fast is drawn twice as
/// often, before any of the per-task sampling happens. An unmeasured worker
/// gets the assumed time, so it is in the table from the start.
pub fn table_weight(candidate: &Candidate, w: &Weights) -> f64 {
    let service = candidate
        .stats
        .expected_service_ms()
        .unwrap_or_else(|| unmeasured_ms(candidate.local, w));
    let queue = (1.0 + candidate.in_flight as f64).powf(w.queue_convexity);
    let completion = service * queue;
    if completion <= 0.0 {
        return 0.0;
    }
    // Squared, not linear, by default. Linear weighting leaves too much
    // traffic on the slow end of a mixed fleet: with four workers at 254 ms
    // and nine at 1000 ms it sends 36% of draws to the slow ones, and even
    // after power-of-2 filtering that is ~13% of tasks and ~99 ms of
    // avoidable wait per task — which is exactly the steady-state regret this
    // measured before the change. Squaring cuts it to about 12 ms while
    // leaving every worker a real share, so a slow worker that becomes fast
    // is still tried. `w.weighting_exponent` makes the point on that curve a
    // parameter rather than a constant — see #264 for the sweep that picked
    // the default.
    let rate = 1.0 / completion;
    rate.powf(w.weighting_exponent)
}

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

    fn measured(median_ms: f64, n: usize, ok: bool) -> Stats {
        let mut s = Stats::new();
        for _ in 0..n {
            s.observe(median_ms, ok);
        }
        s
    }

    fn candidate(median_ms: f64, n: usize, in_flight: u32) -> Candidate {
        Candidate {
            stats: measured(median_ms, n, true),
            in_flight,
            price_per_hour: 3.6,
            local: false,
        }
    }

    /// On a cold broker nothing is measured, so the prior is the whole
    /// decision. Starting a worker on this node at the same 250 ms as one
    /// across the mesh says a loopback hop costs what a network hop costs,
    /// which is false: `zc bench` on a freshly restarted broker sent every
    /// request of a run to a 262 ms peer while four local workers answered in
    /// 1.4 ms. Unmeasured-local must sit far below unmeasured-remote.
    #[test]
    fn an_unmeasured_local_worker_is_preferred_over_an_unmeasured_peer() {
        let w = Weights::default();
        let unmeasured = |local: bool| Candidate {
            stats: Stats::new(),
            in_flight: 0,
            price_per_hour: 3.6,
            local,
        };
        let local = unmeasured(true);
        let peer = unmeasured(false);

        assert!(
            table_weight(&local, &w) > table_weight(&peer, &w),
            "an unmeasured local worker must be drawn more often than an unmeasured peer: \
             local {} vs peer {}",
            table_weight(&local, &w),
            table_weight(&peer, &w)
        );

        // The table weight is the dominant, deterministic effect: inverse
        // completion squared, so 250 ms against 500 ms is a 4x preference.
        let ratio = table_weight(&local, &w) / table_weight(&peer, &w);
        assert!(
            (3.5..4.5).contains(&ratio),
            "an unmeasured local worker should be drawn ~4x as often as an \
             unmeasured peer (inverse-completion squared), got {ratio:.2}x"
        );

        // Per-draw sampling keeps a wide spread on purpose, so the peer must
        // still win sometimes -- it just must not win as often.
        let mut rng = Rng::seeded(7);
        let mut local_wins = 0;
        for _ in 0..500 {
            let l = sample_service_ms(&local.stats, true, &w, &mut rng);
            let p = sample_service_ms(&peer.stats, false, &w, &mut rng);
            if l < p {
                local_wins += 1;
            }
        }
        assert!(
            (300..480).contains(&local_wins),
            "the local prior must win most draws but not all of them, got \
             {local_wins}/500"
        );
    }

    /// The prior must not survive contact with evidence: a peer that has been
    /// measured fast still beats an unmeasured local worker, or the policy
    /// could never use the mesh for work the mesh is better at.
    #[test]
    fn measurements_still_override_the_local_prior() {
        let w = Weights::default();
        let fast_peer = Candidate {
            stats: measured(2.0, 200, true),
            in_flight: 0,
            price_per_hour: 3.6,
            local: false,
        };
        let cold_local = Candidate {
            stats: Stats::new(),
            in_flight: 0,
            price_per_hour: 3.6,
            local: true,
        };
        assert!(
            table_weight(&fast_peer, &w) > table_weight(&cold_local, &w),
            "a peer measured at 2ms must outrank a local worker merely assumed \
             at {}ms",
            w.unmeasured_ms
        );
    }

    #[test]
    fn a_well_measured_worker_is_sampled_close_to_what_it_measured() {
        let w = Weights::default();
        let mut rng = Rng::seeded(1);
        let stats = measured(50.0, 200, true);
        let draws: Vec<f64> = (0..500)
            .map(|_| sample_service_ms(&stats, false, &w, &mut rng))
            .collect();
        let mean = draws.iter().sum::<f64>() / draws.len() as f64;
        assert!(
            (mean - 50.0).abs() < 10.0,
            "200 observations should pin it near 50 ms, got {mean:.1}"
        );
    }

    /// The exploration that makes this adaptive: a worker seen twice must be
    /// sampled over a much wider range than one seen two hundred times, so it
    /// still gets tried.
    #[test]
    fn a_barely_measured_worker_is_sampled_widely() {
        let w = Weights::default();
        let spread = |n: usize| {
            let stats = measured(50.0, n, true);
            let mut rng = Rng::seeded(7);
            let draws: Vec<f64> = (0..2000)
                .map(|_| sample_service_ms(&stats, false, &w, &mut rng))
                .collect();
            let mean = draws.iter().sum::<f64>() / draws.len() as f64;
            let var = draws.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / draws.len() as f64;
            var.sqrt()
        };
        // Both have the same observed value; only the confidence differs.
        assert!(
            spread(2) > spread(200) * 3.0,
            "little evidence must sample widely: {:.1} vs {:.1}",
            spread(2),
            spread(200)
        );
    }

    #[test]
    fn queueing_counts_against_a_worker() {
        let w = Weights::default();
        let idle = candidate(30.0, 50, 0);
        let busy = candidate(10.0, 50, 4);
        assert!(
            cost(&busy, 10.0, &w) > cost(&idle, 30.0, &w),
            "four queued at 10 ms is worse than idle at 30 ms"
        );
    }

    #[test]
    fn failure_and_price_move_the_cost_the_way_they_should() {
        let w = Weights::default();
        let mut flaky = candidate(50.0, 0, 0);
        for _ in 0..20 {
            flaky.stats.observe(50.0, false);
        }
        let solid = candidate(50.0, 20, 0);
        assert!(
            cost(&flaky, 50.0, &w) > cost(&solid, 50.0, &w),
            "a worker that keeps failing costs more than one that does not"
        );

        let priced = Weights {
            price: 1e6,
            ..Weights::default()
        };
        let cheap = Candidate {
            price_per_hour: 1.0,
            ..candidate(50.0, 20, 0)
        };
        let dear = Candidate {
            price_per_hour: 100.0,
            ..candidate(50.0, 20, 0)
        };
        assert!(cost(&dear, 50.0, &priced) > cost(&cheap, 50.0, &priced));
    }

    #[test]
    fn the_table_weights_a_fast_idle_worker_above_a_slow_busy_one() {
        let w = Weights::default();
        assert!(
            table_weight(&candidate(10.0, 20, 0), &w) > table_weight(&candidate(10.0, 20, 4), &w)
        );
        assert!(
            table_weight(&candidate(10.0, 20, 0), &w) > table_weight(&candidate(100.0, 20, 0), &w)
        );
        // A worker nothing is known about is still in the table.
        assert!(table_weight(&candidate(0.0, 0, 0), &w) > 0.0);
    }

    /// The exponent is a parameter now, not a constant baked into the
    /// formula. This pins the exact arithmetic behind the history in
    /// `table_weight`'s comment: on the mesh from #264 (four workers at
    /// 254 ms, nine at 1000 ms, all idle) linear weighting sends 36% of the
    /// table's mass to the slow end, and squaring cuts that sharply.
    #[test]
    fn weighting_exponent_controls_how_sharply_load_concentrates() {
        let slow_share = |exponent: f64| {
            let w = Weights {
                weighting_exponent: exponent,
                ..Weights::default()
            };
            let fast = candidate(254.0, 50, 0);
            let slow = candidate(1000.0, 50, 0);
            let weights: Vec<f64> = std::iter::repeat_n(&fast, 4)
                .chain(std::iter::repeat_n(&slow, 9))
                .map(|c| table_weight(c, &w))
                .collect();
            let total: f64 = weights.iter().sum();
            weights[4..].iter().sum::<f64>() / total
        };
        let linear = slow_share(1.0);
        let squared = slow_share(2.0);
        assert!(
            (linear - 0.36).abs() < 0.01,
            "linear weighting should match the measured 36% slow-end share, got {linear:.3}"
        );
        assert!(
            squared < linear,
            "a higher exponent must concentrate load more, not less: linear {linear:.3}, squared {squared:.3}"
        );
        assert!(
            squared < 0.15,
            "squared weighting should land close to the ~13% measured after squaring, got {squared:.3}"
        );
    }

    /// `queue_convexity` is the third lever from #264: above 1.0 it should
    /// punish a worker with a full queue harder than linear does, in both the
    /// per-task cost and the sampling-table weight.
    #[test]
    fn convex_queue_term_punishes_a_full_queue_harder_than_linear() {
        let linear = Weights {
            queue_convexity: 1.0,
            ..Weights::default()
        };
        let convex = Weights {
            queue_convexity: 2.0,
            ..Weights::default()
        };
        let idle = candidate(50.0, 50, 0);
        let busy = candidate(50.0, 50, 4);

        let weight_ratio = |w: &Weights| table_weight(&busy, w) / table_weight(&idle, w);
        assert!(
            weight_ratio(&convex) < weight_ratio(&linear),
            "convex queueing should shrink a busy worker's table share more: linear {:.5}, convex {:.5}",
            weight_ratio(&linear),
            weight_ratio(&convex)
        );

        let cost_ratio = |w: &Weights| cost(&busy, 50.0, w) / cost(&idle, 50.0, w);
        assert!(
            cost_ratio(&convex) > cost_ratio(&linear),
            "convex queueing should cost a busy worker relatively more: linear {:.3}, convex {:.3}",
            cost_ratio(&linear),
            cost_ratio(&convex)
        );
    }

    /// #438: an unmeasured worker among measured siblings is judged as one of
    /// them, not at the flat 250 ms guess that left it 60x behind on paper
    /// and so never drawn, never measured.
    #[test]
    fn an_unmeasured_worker_borrows_its_siblings_evidence() {
        let w = Weights::default();
        let local = |median: f64, n: usize| Candidate {
            local: true,
            ..candidate(median, n, 0)
        };
        let fleet = vec![
            local(4.0, 30),
            local(4.0, 30),
            local(4.0, 30),
            local(0.0, 0),
        ];
        let view = with_fleet_prior(&fleet, &w);

        let cold = &view[3];
        assert!(
            (cold.stats.weight() - 1.0).abs() < 1e-9,
            "topped up to one observation"
        );
        let median = cold.stats.median_service_ms().expect("now has an estimate");
        assert!(
            (median - 4.0).abs() < 1e-6,
            "reads as its siblings, got {median}"
        );
        let ratio = table_weight(&view[3], &w) / table_weight(&view[0], &w);
        assert!(
            (0.9..1.1).contains(&ratio),
            "drawn about as often as a measured sibling, got {ratio:.2}x"
        );

        // Measured workers are judged on their own evidence: a slow one is
        // not pulled toward a fast pool, and nobody's success rate moves.
        let mixed = vec![local(4.0, 30), local(400.0, 3), local(0.0, 0)];
        let view = with_fleet_prior(&mixed, &w);
        assert_eq!(view[0].stats, mixed[0].stats);
        assert_eq!(view[1].stats, mixed[1].stats);
        assert_eq!(view[2].stats.success_rate(), mixed[2].stats.success_rate());

        // Peers do not borrow from this node's workers, or the reverse: the
        // hop is part of what a peer is measured at.
        let peer = Candidate {
            local: false,
            ..candidate(0.0, 0, 0)
        };
        let view = with_fleet_prior(&[local(4.0, 30), peer.clone()], &w);
        assert_eq!(
            view[1].stats, peer.stats,
            "a peer has no peers to borrow from here"
        );

        // Nothing measured anywhere: the cold-broker priors are untouched.
        let cold_broker = vec![local(0.0, 0), peer];
        let view = with_fleet_prior(&cold_broker, &w);
        assert_eq!(view[0].stats, cold_broker[0].stats);
        assert_eq!(view[1].stats, cold_broker[1].stats);

        // And the knob turns it off.
        let off = Weights {
            fleet_prior_weight: 0.0,
            ..Weights::default()
        };
        assert_eq!(with_fleet_prior(&fleet, &off)[3].stats, fleet[3].stats);
    }
}

/// Does the policy actually beat what the broker does today, and does it
/// recover when the mesh changes underneath it? These simulate a fleet with
/// known true service times and compare cumulative waiting against an oracle
/// that knows them.
#[cfg(test)]
mod regret_tests {
    use super::*;

    /// A fleet whose true service times we know, so regret can be measured.
    ///
    /// Every reply here is representative -- no start-up cost is modelled --
    /// so every one is timed. The broker's warm-up exclusion (#438) is
    /// modelled where the start-up cost is, in [`QueueingFleet`].
    struct Fleet {
        truth_ms: Vec<f64>,
        stats: Vec<Stats>,
        in_flight: Vec<u32>,
    }

    impl Fleet {
        fn new(truth_ms: Vec<f64>) -> Self {
            let n = truth_ms.len();
            Fleet {
                truth_ms,
                stats: vec![Stats::new(); n],
                in_flight: vec![0; n],
            }
        }

        fn candidates(&self) -> Vec<Candidate> {
            (0..self.truth_ms.len())
                .map(|i| Candidate {
                    stats: self.stats[i],
                    in_flight: self.in_flight[i],
                    price_per_hour: 3.6,
                    local: false,
                })
                .collect()
        }

        /// Run one task on `i`, with a little noise, and learn from it.
        fn run(&mut self, i: usize, rng: &mut Rng) -> f64 {
            let noise = 0.75 + rng.next_f64() * 0.5;
            let took = self.truth_ms[i] * noise;
            self.stats[i].decay(0.98);
            self.stats[i].observe(took, true);
            took
        }

        /// What the router decides on: the candidates, with the fleet prior.
        fn decision_view(&self) -> Vec<Candidate> {
            with_fleet_prior(&self.candidates(), &Weights::default())
        }
    }

    fn run_policy(truth: Vec<f64>, tasks: usize, seed: u64, d: usize) -> f64 {
        let mut fleet = Fleet::new(truth);
        let mut rng = Rng::seeded(seed);
        let w = Weights::default();
        let mut total = 0.0;
        for t in 0..tasks {
            let cands = fleet.decision_view();
            let weights: Vec<f64> = cands.iter().map(|c| table_weight(c, &w)).collect();
            let table = AliasTable::build(&weights).expect("a fleet");
            let i = choose(&cands, &table, &mut rng, d, &w).expect("a choice");
            total += fleet.run(i, &mut rng);
            // Rebuild the table every tick, not every task.
            let _ = t;
        }
        total
    }

    fn run_round_robin(truth: Vec<f64>, tasks: usize, seed: u64) -> f64 {
        let mut fleet = Fleet::new(truth);
        let mut rng = Rng::seeded(seed);
        let n = fleet.truth_ms.len();
        (0..tasks).map(|t| fleet.run(t % n, &mut rng)).sum()
    }

    fn run_oracle(truth: Vec<f64>, tasks: usize, seed: u64) -> f64 {
        let best = truth
            .iter()
            .enumerate()
            .min_by(|a, b| a.1.partial_cmp(b.1).unwrap())
            .map(|(i, _)| i)
            .unwrap();
        let mut fleet = Fleet::new(truth);
        let mut rng = Rng::seeded(seed);
        (0..tasks).map(|_| fleet.run(best, &mut rng)).sum()
    }

    /// The mesh this was measured on: a few fast local workers and a lot of
    /// slow remote ones.
    fn mesh() -> Vec<f64> {
        let mut t = vec![254.0; 4];
        t.extend(std::iter::repeat_n(1000.0, 9));
        t
    }

    /// The mesh from #264's own report: not four *tied* fast workers but
    /// four close-but-distinct ones (200-300 ms, centred on the 254 ms the
    /// issue quotes) and nine slow ones at 1000 ms. Sharper weighting does
    /// not split load evenly across a tied group — alias-table sampling
    /// already does that — it concentrates on whichever one is a hair
    /// fastest, which is what "share on the fastest node: 92%" in the issue
    /// describes and what `mesh()`'s exactly-tied fast group cannot
    /// reproduce.
    fn queueing_mesh() -> Vec<f64> {
        let mut t = vec![150.0, 280.0, 290.0, 300.0];
        t.extend(std::iter::repeat_n(1000.0, 9));
        t
    }

    /// One request finishing at `at`, having taken `service` ms of actual
    /// work on `worker`. `client` is which of the `concurrency` closed-loop
    /// clients it belongs to, so the next request from that client can be
    /// issued the instant this one lands.
    struct Completion {
        at: f64,
        worker: usize,
        client: usize,
        service: f64,
        /// What the broker records for it, per the fleet's [`Observation`].
        observed: f64,
    }

    /// What a completed request teaches the policy.
    #[derive(Debug, Clone, Copy, PartialEq)]
    enum Observation {
        /// The worker's own service time. What these simulations used to
        /// observe, and not what the broker can see.
        Service,
        /// Dispatch to reply, queueing on the worker included: what
        /// `record_request` was handed before #438.
        RoundTrip,
        /// The round trip divided by `1 + requests ahead of it at dispatch`,
        /// i.e. the per-slot service time the cost model multiplies by
        /// `1 + in_flight` (#438).
        PerSlot,
    }

    impl PartialEq for Completion {
        fn eq(&self, other: &Self) -> bool {
            self.at == other.at
        }
    }
    impl Eq for Completion {}
    impl PartialOrd for Completion {
        fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
            Some(self.cmp(other))
        }
    }
    impl Ord for Completion {
        fn cmp(&self, other: &Self) -> std::cmp::Ordering {
            // `BinaryHeap` is a max-heap; reversed so the earliest completion
            // pops first.
            other.at.partial_cmp(&self.at).unwrap()
        }
    }

    /// A fleet where each worker is a single-threaded FIFO queue: a task
    /// dispatched to a busy worker waits behind whatever it is already
    /// running, instead of completing instantly.
    ///
    /// `run_policy`/`Fleet` above never has `in_flight` above zero — every
    /// task starts and finishes before the next is dispatched — so it can
    /// measure whether the policy learns the right service times, but it
    /// cannot reproduce the tail regression from #264, which is entirely a
    /// queueing effect. This can.
    struct QueueingFleet {
        truth_ms: Vec<f64>,
        stats: Vec<Stats>,
        in_flight: Vec<u32>,
        /// What the router can currently see, as opposed to `in_flight`
        /// (ground truth). Equal to `in_flight` whenever `staleness == 0`;
        /// otherwise refreshed only once every `staleness + 1` dispatch
        /// decisions, so a burst of decisions inside that window is made
        /// against the same snapshot. See [`Self::with_staleness`].
        visible_in_flight: Vec<u32>,
        available_at: Vec<f64>,
        /// How many dispatch decisions the visible snapshot may lag the
        /// truth by. 0 means perfect, synchronous visibility.
        staleness: usize,
        decisions_since_refresh: usize,
        /// Extra time the FIRST task on each worker takes, as a freshly
        /// started Python worker importing what the payload needs (#438).
        cold_ms: f64,
        observation: Observation,
        /// Tasks dispatched to each worker, for the split.
        served: Vec<usize>,
        completed: Vec<usize>,
        /// Requests dispatched to each worker before its first completion.
        warming: Vec<usize>,
        /// Leave each worker's first completion out of its posterior, as the
        /// broker does (#438): that one paid `cold_ms`.
        skip_first_observation: bool,
        /// Ignore the policy and rotate, as static routing does on a fleet
        /// it cannot tell apart: the baseline adaptive must not lose to.
        round_robin: bool,
    }

    impl QueueingFleet {
        fn new(truth_ms: Vec<f64>) -> Self {
            Self::with_staleness(truth_ms, 0)
        }

        /// A fleet where the router's view of `in_flight` can lag reality by
        /// up to `staleness` dispatch decisions, modelling a broker that
        /// learns a worker's true load only from periodic heartbeats
        /// (`HEARTBEAT_INTERVAL` in `src/serve.rs`, 15s in production)
        /// rather than from its own dispatches. At realistic request rates
        /// (100 ms - 1 s service times, this mesh) many decisions land
        /// inside a single heartbeat window, so several of them see the
        /// same last-reported `in_flight` even though the true value is
        /// changing underneath them — exactly the race `worker.rs`'s
        /// `heartbeat()` creates when it overwrites the locally-tracked
        /// count with the worker's self-reported one.
        fn with_staleness(truth_ms: Vec<f64>, staleness: usize) -> Self {
            let n = truth_ms.len();
            QueueingFleet {
                truth_ms,
                stats: vec![Stats::new(); n],
                in_flight: vec![0; n],
                visible_in_flight: vec![0; n],
                available_at: vec![0.0; n],
                staleness,
                decisions_since_refresh: 0,
                cold_ms: 0.0,
                observation: Observation::Service,
                served: vec![0; n],
                completed: vec![0; n],
                warming: vec![0; n],
                round_robin: false,
                skip_first_observation: true,
            }
        }

        fn candidates(&self) -> Vec<Candidate> {
            (0..self.truth_ms.len())
                .map(|i| Candidate {
                    stats: self.stats[i],
                    in_flight: self.visible_in_flight[i],
                    price_per_hour: 3.6,
                    local: false,
                })
                .collect()
        }

        /// Refresh the visible snapshot on the first decision of each
        /// staleness window, and leave it untouched for the rest of the
        /// window so those decisions share it — the condition under which a
        /// burst piles onto a worker the router still believes is idle.
        fn refresh_visibility(&mut self) {
            if self.decisions_since_refresh == 0 {
                self.visible_in_flight.copy_from_slice(&self.in_flight);
            }
            self.decisions_since_refresh += 1;
            if self.decisions_since_refresh > self.staleness {
                self.decisions_since_refresh = 0;
            }
        }

        /// Choose a worker for a task submitted at `now` and enqueue it: it
        /// starts when the worker is free (or immediately, if idle) and
        /// completes `service` ms later.
        fn dispatch(
            &mut self,
            now: f64,
            client: usize,
            rng: &mut Rng,
            d: usize,
            w: &Weights,
        ) -> Completion {
            self.refresh_visibility();
            let cands = with_fleet_prior(&self.candidates(), w);
            let weights: Vec<f64> = cands.iter().map(|c| table_weight(c, w)).collect();
            let table = AliasTable::build(&weights).expect("a fleet");
            let i = match self.round_robin {
                true => self.served.iter().sum::<usize>() % self.truth_ms.len(),
                false => choose(&cands, &table, rng, d, w).expect("a choice"),
            };
            let ahead = self.in_flight[i];
            self.in_flight[i] += 1;
            if self.completed[i] == 0 {
                self.warming[i] += 1;
            }
            let noise = 0.75 + rng.next_f64() * 0.5;
            let cold = if self.served[i] == 0 {
                self.cold_ms
            } else {
                0.0
            };
            self.served[i] += 1;
            let service = self.truth_ms[i] * noise + cold;
            let start = self.available_at[i].max(now);
            let at = start + service;
            self.available_at[i] = at;
            let observed = match self.observation {
                Observation::Service => service,
                Observation::RoundTrip => at - now,
                Observation::PerSlot => (at - now) / (1.0 + ahead as f64),
            };
            Completion {
                at,
                worker: i,
                client,
                service,
                observed,
            }
        }

        /// A dispatched task has landed: stop counting it as in flight and
        /// learn from what it actually took.
        fn complete(&mut self, c: &Completion) {
            self.in_flight[c.worker] = self.in_flight[c.worker].saturating_sub(1);
            self.completed[c.worker] += 1;
            if self.skip_first_observation && self.warming[c.worker] > 0 {
                self.warming[c.worker] -= 1;
                self.stats[c.worker].observe_outcome(true);
                return;
            }
            self.stats[c.worker].decay(0.98);
            self.stats[c.worker].observe(c.observed, true);
        }
    }

    /// Simulate a closed-loop bench: `concurrency` clients each hold one
    /// request in flight, submitting the next the instant the previous
    /// completes — the same shape as the mesh bench in #264 (120 requests at
    /// concurrency 4). Returns each request's end-to-end latency (queueing
    /// wait plus service), in submission order of completion, which is what
    /// p50/p90/p99/max should be computed over — not the mean service cost
    /// `run_policy` reports.
    fn run_policy_concurrent(
        truth: Vec<f64>,
        requests: usize,
        concurrency: usize,
        seed: u64,
        d: usize,
        w: &Weights,
    ) -> Vec<f64> {
        run_policy_concurrent_with_staleness(truth, requests, concurrency, seed, d, w, 0)
    }

    /// As [`run_policy_concurrent`], but the router's view of `in_flight` can
    /// lag the truth by `staleness` dispatch decisions. See
    /// `QueueingFleet::with_staleness`.
    #[allow(clippy::too_many_arguments)]
    fn run_policy_concurrent_with_staleness(
        truth: Vec<f64>,
        requests: usize,
        concurrency: usize,
        seed: u64,
        d: usize,
        w: &Weights,
        staleness: usize,
    ) -> Vec<f64> {
        let fleet = QueueingFleet::with_staleness(truth, staleness);
        run_fleet(fleet, requests, concurrency, seed, d, w).0
    }

    /// The closed loop behind every concurrent run: `concurrency` clients on
    /// `fleet`, until `requests` have been dispatched. Returns each request's
    /// end-to-end latency and how many tasks each worker was handed.
    fn run_fleet(
        mut fleet: QueueingFleet,
        requests: usize,
        concurrency: usize,
        seed: u64,
        d: usize,
        w: &Weights,
    ) -> (Vec<f64>, Vec<usize>) {
        use std::collections::BinaryHeap;

        let mut rng = Rng::seeded(seed);
        let mut heap: BinaryHeap<Completion> = BinaryHeap::new();
        let mut latencies = Vec::with_capacity(requests);
        let mut submitted_at = vec![0.0f64; concurrency];
        let mut dispatched = 0usize;

        let clients = concurrency.min(requests);
        for client in 0..clients {
            heap.push(fleet.dispatch(0.0, client, &mut rng, d, w));
            dispatched += 1;
        }

        while let Some(c) = heap.pop() {
            fleet.complete(&c);
            latencies.push(c.at - submitted_at[c.client]);
            if dispatched < requests {
                submitted_at[c.client] = c.at;
                heap.push(fleet.dispatch(c.at, c.client, &mut rng, d, w));
                dispatched += 1;
            }
        }
        (latencies, fleet.served)
    }

    /// The concurrent closed-loop baseline for an oracle that always sends
    /// every request to the single fastest worker. Even an oracle queues
    /// under concurrency, since one worker is a single-threaded FIFO queue —
    /// this is the honest floor `run_policy_concurrent`'s tail should be
    /// judged against, not a queue-free `truth_ms[best] * 1.25`.
    fn run_oracle_concurrent(
        truth: Vec<f64>,
        requests: usize,
        concurrency: usize,
        seed: u64,
    ) -> Vec<f64> {
        let best_ms = truth.iter().cloned().fold(f64::INFINITY, f64::min);
        let mut rng = Rng::seeded(seed);
        let mut latencies = Vec::with_capacity(requests);
        let mut submitted_at = vec![0.0f64; concurrency];
        let mut available_at = 0.0f64;
        let mut dispatched = 0usize;

        let mut completions: std::collections::BinaryHeap<Completion> =
            std::collections::BinaryHeap::new();
        let mut dispatch_to_best = |now: f64, client: usize, rng: &mut Rng| -> Completion {
            let noise = 0.75 + rng.next_f64() * 0.5;
            let service = best_ms * noise;
            let start = available_at.max(now);
            let at = start + service;
            available_at = at;
            Completion {
                at,
                worker: 0,
                client,
                service,
                observed: service,
            }
        };
        let clients = concurrency.min(requests);
        for client in 0..clients {
            completions.push(dispatch_to_best(0.0, client, &mut rng));
            dispatched += 1;
        }
        while let Some(c) = completions.pop() {
            latencies.push(c.at - submitted_at[c.client]);
            if dispatched < requests {
                submitted_at[c.client] = c.at;
                completions.push(dispatch_to_best(c.at, c.client, &mut rng));
                dispatched += 1;
            }
        }
        latencies
    }

    /// p50/p90/p99/max/mean of a set of per-task costs or latencies.
    #[derive(Debug, Clone, Copy, PartialEq)]
    struct TailStats {
        mean: f64,
        p50: f64,
        p90: f64,
        p99: f64,
        max: f64,
    }

    impl std::fmt::Display for TailStats {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "mean {:.0} p50 {:.0} p90 {:.0} p99 {:.0} max {:.0}",
                self.mean, self.p50, self.p90, self.p99, self.max
            )
        }
    }

    /// Nearest-rank percentile: sorts a copy, so the caller's ordering is
    /// untouched.
    fn tail_stats(values: &[f64]) -> TailStats {
        assert!(!values.is_empty(), "no samples to summarise");
        let mut sorted = values.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let n = sorted.len();
        let at = |p: f64| {
            let rank = ((p * n as f64).ceil() as usize).clamp(1, n);
            sorted[rank - 1]
        };
        TailStats {
            mean: sorted.iter().sum::<f64>() / n as f64,
            p50: at(0.50),
            p90: at(0.90),
            p99: at(0.99),
            max: sorted[n - 1],
        }
    }

    #[test]
    fn the_policy_beats_round_robin_by_a_wide_margin() {
        let tasks = 3_000;
        let policy = run_policy(mesh(), tasks, 11, 2);
        let rr = run_round_robin(mesh(), tasks, 11);
        let oracle = run_oracle(mesh(), tasks, 11);

        let policy_regret = policy - oracle;
        let rr_regret = rr - oracle;
        println!(
            "  per task: oracle {:.0} ms, policy {:.0} ms, round-robin {:.0} ms",
            oracle / tasks as f64,
            policy / tasks as f64,
            rr / tasks as f64
        );
        assert!(
            policy_regret * 3.0 < rr_regret,
            "policy regret {policy_regret:.0} ms vs round-robin {rr_regret:.0} ms"
        );
    }

    /// Regret must grow more slowly than the number of tasks: the cost of
    /// learning is paid once, not per task, or the policy never converges.
    #[test]
    fn regret_per_task_shrinks_as_it_learns() {
        let oracle_per_task = |tasks: usize| run_oracle(mesh(), tasks, 3) / tasks as f64;
        let policy_per_task = |tasks: usize| run_policy(mesh(), tasks, 3, 2) / tasks as f64;

        let early = policy_per_task(300) - oracle_per_task(300);
        let late = policy_per_task(6_000) - oracle_per_task(6_000);
        println!("  regret per task: early {early:.1} ms, late {late:.1} ms");
        assert!(
            late < early * 0.6,
            "should keep improving: early {early:.1} ms, late {late:.1} ms"
        );
    }

    /// The harder direction, and the risk that comes with weighting sharply:
    /// a worker the policy has learned to avoid is drawn rarely. Evidence only
    /// ages when a worker is chosen, so decay does not rescue it -- what does
    /// is the exploration floor ([`Weights::explore_floor`], #440): a few
    /// replies from the improved worker widen its posterior, and the policy
    /// itself takes over from there.
    ///
    /// Returns the share of 300 decisions that went to worker 12 before and
    /// after it became the fastest on the mesh, `after_decisions` decisions
    /// later.
    fn rediscovery(seed: u64, w: &Weights, after_decisions: usize) -> (usize, usize) {
        let mut fleet = Fleet::new(mesh());
        let mut rng = Rng::seeded(seed);

        let dispatch = |fleet: &mut Fleet, rng: &mut Rng| -> usize {
            let cands = fleet.decision_view();
            let weights: Vec<f64> = cands.iter().map(|c| table_weight(c, w)).collect();
            let table = AliasTable::build(&weights).expect("a fleet");
            let i = choose(&cands, &table, rng, 2, w).expect("a choice");
            fleet.run(i, rng);
            i
        };

        // Learn that workers 4.. are the slow ones.
        for _ in 0..1_500 {
            dispatch(&mut fleet, &mut rng);
        }
        let before: usize = (0..300)
            .map(|_| usize::from(dispatch(&mut fleet, &mut rng) == 12))
            .sum();

        // Worker 12 becomes by far the best on the mesh.
        fleet.truth_ms[12] = 20.0;
        for _ in 0..after_decisions {
            dispatch(&mut fleet, &mut rng);
        }
        let after: usize = (0..300)
            .map(|_| usize::from(dispatch(&mut fleet, &mut rng) == 12))
            .sum();
        (before, after)
    }

    /// The claim, checked across seeds rather than on one lucky one: within
    /// 4,000 decisions of becoming the fastest worker, a worker the policy had
    /// learned to avoid gets more than half the traffic, from at least 39 of
    /// 40 seeds. Without the floor it missed on about 1 seed in 20 at this
    /// horizon (#440); across 200 other seeds the floor missed none.
    #[test]
    fn it_notices_a_slow_worker_that_becomes_fast() {
        let w = Weights::default();
        let mut failed = Vec::new();
        for seed in 1..=40u64 {
            let (before, after) = rediscovery(seed, &w, 4_000);
            if !(before < 30 && after > 150) {
                failed.push((seed, before, after));
            }
        }
        println!("  seeds that failed: {failed:?}");
        assert!(
            failed.len() <= 1,
            "it must find a worker that improves, not write it off: (seed, before, after) {failed:?}"
        );
    }

    /// The point of discounting: when the fast workers go slow, the policy has
    /// to notice and move, not keep sending work where it used to be good.
    #[test]
    fn it_follows_the_mesh_when_conditions_change() {
        let mut fleet = Fleet::new(mesh());
        let mut rng = Rng::seeded(21);
        let w = Weights::default();

        let dispatch = |fleet: &mut Fleet, rng: &mut Rng| -> usize {
            let cands = fleet.decision_view();
            let weights: Vec<f64> = cands.iter().map(|c| table_weight(c, &w)).collect();
            let table = AliasTable::build(&weights).expect("a fleet");
            let i = choose(&cands, &table, rng, 2, &w).expect("a choice");
            fleet.run(i, rng);
            i
        };

        // Learn the fleet as it is.
        for _ in 0..1_500 {
            dispatch(&mut fleet, &mut rng);
        }
        let before: usize = (0..300)
            .map(|_| usize::from(dispatch(&mut fleet, &mut rng) < 4))
            .sum();

        // The local workers become the slow ones.
        for i in 0..4 {
            fleet.truth_ms[i] = 2_000.0;
        }
        for _ in 0..1_500 {
            dispatch(&mut fleet, &mut rng);
        }
        let after: usize = (0..300)
            .map(|_| usize::from(dispatch(&mut fleet, &mut rng) < 4))
            .sum();

        println!("  share on the formerly-fast workers: {before}/300 → {after}/300");
        assert!(before > 200, "it found the fast ones: {before}/300");
        assert!(
            after < 90,
            "it moved off them once they slowed: {after}/300"
        );
    }

    #[test]
    fn tail_stats_uses_nearest_rank_percentiles() {
        // 1..=100 ms: p50 is the 50th smallest (50), p90 the 90th (90), p99
        // the 99th (99), independent of input order.
        let values: Vec<f64> = (1..=100).rev().map(|v| v as f64).collect();
        let s = tail_stats(&values);
        assert_eq!(s.p50, 50.0);
        assert_eq!(s.p90, 90.0);
        assert_eq!(s.p99, 99.0);
        assert_eq!(s.max, 100.0);
        assert!((s.mean - 50.5).abs() < 1e-9);
    }

    /// The staleness knob from #264's second half: with two equally fast,
    /// well-measured workers, the only reason a fresh-visibility router
    /// spreads a back-to-back burst across both is the queue term noticing
    /// `in_flight` rise after the first dispatch. A router whose view is
    /// stale for the whole burst never sees that rise, so it keeps sampling
    /// both workers as if idle and piles up on whichever one wins the
    /// initial draw — reproducing "several concurrent decisions made
    /// against the same stale snapshot" from the live regression, entirely
    /// inside the simulator.
    #[test]
    fn stale_visibility_lets_a_burst_pile_onto_one_worker() {
        // The queue term is the variable under study: a uniform exploratory
        // pick ignores it by design and would blur the fresh/stale contrast.
        let w = Weights {
            explore_floor: 0.0,
            ..Weights::default()
        };
        let burst = 8;
        let seeds = 30u64;

        let max_share = |staleness: usize| -> f64 {
            let mut total = 0.0;
            for seed in 0..seeds {
                let mut fleet = QueueingFleet::with_staleness(vec![100.0, 100.0], staleness);
                // Tightly measured and tied, so the queue term (not service
                // sampling noise) decides where the burst goes.
                for i in 0..2 {
                    for _ in 0..50 {
                        fleet.stats[i].observe(100.0, true);
                    }
                }
                let mut rng = Rng::seeded(seed);
                let mut landed = [0usize; 2];
                for _ in 0..burst {
                    // Nothing completes mid-burst: this is the closed
                    // window a real heartbeat interval creates.
                    let c = fleet.dispatch(0.0, 0, &mut rng, 4, &w);
                    landed[c.worker] += 1;
                }
                total += *landed.iter().max().unwrap() as f64 / burst as f64;
            }
            total / seeds as f64
        };

        let fresh = max_share(0);
        let stale = max_share(burst);
        println!("  max share on one worker: fresh {fresh:.2}, stale {stale:.2}");
        assert!(
            stale > fresh + 0.1,
            "a stale-for-the-whole-burst router should concentrate load more: fresh {fresh:.2}, stale {stale:.2}"
        );
    }

    /// Pins the queueing regression #264 is about: at the mesh's chosen
    /// operating point, the tail of a concurrent, closed-loop run must not
    /// run away relative to the oracle the way `d = 2`, exponent 2.0, linear
    /// queueing did when measured live (p99 1.86 s → 2.36 s off vs. on,
    /// oracle-normalised the policy's own regret roughly doubled at p99).
    /// 20,000 requests at concurrency 4 (the bench's concurrency, a sample
    /// size the live 120-request bench could not give p99 on) across five
    /// seeds, so this is one CPU-bound simulation, not a live mesh run.
    #[test]
    fn adaptive_routing_keeps_the_tail_within_bounds_of_the_oracle() {
        let requests = 20_000;
        let concurrency = 4;
        let w = Weights::default();
        let mut latencies = Vec::new();
        let mut oracle = Vec::new();
        for seed in [1u64, 2, 3, 4, 5] {
            latencies.extend(run_policy_concurrent(
                queueing_mesh(),
                requests,
                concurrency,
                seed,
                w.candidates_per_choice,
                &w,
            ));
            oracle.extend(run_oracle_concurrent(
                queueing_mesh(),
                requests,
                concurrency,
                seed,
            ));
        }
        let stats = tail_stats(&latencies);
        // The oracle's own tail under the same closed-loop concurrency: even
        // it queues, since it always sends work to one worker and that
        // worker is a single-threaded FIFO queue. This is the honest floor,
        // not `truth_ms[best] * 1.25`.
        let o = tail_stats(&oracle);
        println!("  chosen point tail: {stats}, oracle: {o}");
        assert!(
            stats.p99 < o.p99 * 2.5,
            "p99 should stay within 2.5x the oracle's, got {:.0} vs oracle {:.0}",
            stats.p99,
            o.p99
        );
        assert!(
            stats.max < o.max * 3.5,
            "max should not run away either, got {:.0} vs oracle {:.0}",
            stats.max,
            o.max
        );
    }

    /// Pins the ruling from the second half of #264: on a harness with
    /// perfect, synchronous visibility (staleness 0), exponent 3.0 and a
    /// convex queue term look like clear wins over the shipped defaults
    /// (exponent 2.0, linear) — see `sweep_d_exponent_and_queue_convexity`.
    /// Once the router's view of `in_flight` can lag reality by as little as
    /// 8 dispatch decisions — well within a single heartbeat window at these
    /// service times — both reversals disappear: neither the sharper
    /// exponent nor the convex term still beats the default's p99. This is
    /// why the defaults are *not* being sharpened by this issue: the sweep
    /// that argued for it depended on visibility the harness now knows is
    /// unrealistic. If a future change makes either lever win here, that is
    /// new evidence the levers deserve on its own, not a reason to reach for
    /// the staleness-free sweep again.
    #[test]
    fn sharper_weighting_does_not_regain_its_edge_under_realistic_staleness() {
        let requests = 20_000;
        let concurrency = 4;
        let d = 4;
        let staleness = 8;
        let seeds = [1u64, 2, 3, 4, 5];

        let run = |w: &Weights| -> TailStats {
            let mut latencies = Vec::new();
            for &seed in &seeds {
                latencies.extend(run_policy_concurrent_with_staleness(
                    queueing_mesh(),
                    requests,
                    concurrency,
                    seed,
                    d,
                    w,
                    staleness,
                ));
            }
            tail_stats(&latencies)
        };

        let default = run(&Weights::default());
        let sharper = run(&Weights {
            weighting_exponent: 3.0,
            ..Weights::default()
        });
        let convex = run(&Weights {
            queue_convexity: 2.0,
            ..Weights::default()
        });

        println!(
            "  under staleness={staleness}: default {default}, sharper-exponent {sharper}, convex-queue {convex}"
        );
        assert!(
            sharper.p99 >= default.p99 * 0.95,
            "exponent 3.0 should no longer clearly beat the default under staleness: default p99 {:.0}, sharper p99 {:.0}",
            default.p99,
            sharper.p99
        );
        assert!(
            convex.p99 >= default.p99 * 0.95,
            "convex queueing should no longer clearly beat the default under staleness: default p99 {:.0}, convex p99 {:.0}",
            default.p99,
            convex.p99
        );
    }

    /// Documents the operating point #264's sweep picked, so a future change
    /// to a default has to update this deliberately rather than by accident.
    /// `d = 4` (up from 2) is the one change the sweep supports: mean, p50,
    /// p90, p99 and max all improved monotonically from `d = 2` to `d = 4`
    /// at every exponent and queue-term combination tried, with no downside
    /// observed. The weighting exponent (2.0, squared) and the queue term
    /// (1.0, linear) are unchanged — see the commit message for why the
    /// sweep's apparent case for going sharper still isn't trusted.
    #[test]
    fn defaults_document_the_chosen_operating_point() {
        let w = Weights::default();
        assert_eq!(w.candidates_per_choice, 4);
        assert!((w.weighting_exponent - 2.0).abs() < f64::EPSILON);
        assert!((w.queue_convexity - 1.0).abs() < f64::EPSILON);
        assert!((w.explore_floor - 0.005).abs() < f64::EPSILON);
    }

    /// #438's acceptance: N identical workers under at least N concurrent
    /// requests get an even share, within 5 points of 1/N, from every seed.
    ///
    /// This is the staging A/B's shape -- fresh workers whose first request
    /// pays a 500 ms start-up, replies timed as the broker times them (queue
    /// included) -- which split 30/10/40/20 and 38/14/17/31 there. The second
    /// half pins the cause: with the two #438 changes switched off (no fleet
    /// prior, warm-up replies timed like any other) the same runs starve a
    /// worker, so this test fails if either is lost.
    #[test]
    fn identical_workers_under_concurrency_get_an_even_split() {
        let cases: [(f64, usize, usize, usize); 3] = [
            (4.0, 4, 6, 600),   // light: 4 ms, 6 concurrent
            (120.0, 4, 8, 240), // heavy: 120 ms, 8 concurrent
            (20.0, 8, 8, 800),  // a wider fleet at exactly N concurrent
        ];
        let split =
            |service: f64, n: usize, conc: usize, requests: usize, seed: u64, fixed: bool| {
                let mut fleet = fleet_of(vec![service; n], 500.0, Observation::RoundTrip);
                fleet.skip_first_observation = fixed;
                let w = Weights {
                    fleet_prior_weight: if fixed { FLEET_PRIOR_WEIGHT } else { 0.0 },
                    ..Weights::default()
                };
                let (_, served) =
                    run_fleet(fleet, requests, conc, seed, w.candidates_per_choice, &w);
                let total = served.iter().sum::<usize>() as f64;
                served
                    .iter()
                    .map(|&x| x as f64 / total)
                    .collect::<Vec<f64>>()
            };
        let worst = |shares: &[f64]| {
            shares
                .iter()
                .map(|x| (x - 1.0 / shares.len() as f64).abs())
                .fold(0.0, f64::max)
        };
        let mut starved_before = 0;
        for (service, n, conc, requests) in cases {
            for seed in 1..=8u64 {
                let now = split(service, n, conc, requests, seed, true);
                assert!(
                    worst(&now) <= 0.05,
                    "{n} identical {service} ms workers at concurrency {conc}, seed {seed}: \
                     split {now:.3?} is more than 5 points off uniform"
                );
                if worst(&split(service, n, conc, requests, seed, false)) > 0.05 {
                    starved_before += 1;
                }
            }
        }
        assert!(
            starved_before > 0,
            "without the fleet prior and the warm-up exclusion these runs should \
             reproduce the uneven staging split; if they no longer do, this test \
             has stopped testing #438"
        );
    }

    /// A fleet of `truth`, as the broker sees it after #438's staging A/B:
    /// fresh workers whose first task pays `cold_ms`, observed by `obs`.
    fn fleet_of(truth: Vec<f64>, cold_ms: f64, obs: Observation) -> QueueingFleet {
        let mut f = QueueingFleet::new(truth);
        f.cold_ms = cold_ms;
        f.observation = obs;
        f
    }

    /// Latencies and per-worker split over `seeds`, `requests` each.
    fn run_many(
        make: impl Fn() -> QueueingFleet,
        requests: usize,
        concurrency: usize,
        seeds: &[u64],
        w: &Weights,
    ) -> (TailStats, Vec<f64>) {
        let mut lat = Vec::new();
        let mut served: Vec<usize> = Vec::new();
        for &seed in seeds {
            let (l, s) = run_fleet(
                make(),
                requests,
                concurrency,
                seed,
                w.candidates_per_choice,
                w,
            );
            lat.extend(l);
            if served.is_empty() {
                served = vec![0; s.len()];
            }
            for (a, b) in served.iter_mut().zip(s) {
                *a += b;
            }
        }
        let total = served.iter().sum::<usize>().max(1) as f64;
        (
            tail_stats(&lat),
            served.iter().map(|&x| x as f64 / total).collect(),
        )
    }

    /// #438's measurement: round-robin (what static routing does on workers
    /// it cannot tell apart) against the policy before #438, with each of its
    /// two changes alone, and with both, on the staging A/B's homogeneous
    /// fleets and on the heterogeneous mesh the policy exists for. `cold` is
    /// the start-up the first request on each fresh worker pays. Prints
    /// latency and the worst worker's distance from an even split.
    ///   cargo test --bin zc -- broker::policy::regret_tests::sweep_homogeneous_concentration --ignored --nocapture
    #[test]
    #[ignore = "measurement, not a regression: run manually, see doc comment"]
    fn sweep_homogeneous_concentration() {
        let seeds = [1u64, 2, 3, 4, 5, 6, 7, 8];
        let cases: [(&str, Vec<f64>, usize, usize); 4] = [
            ("light: 4 x 4 ms, c=6", vec![4.0; 4], 6, 600),
            ("heavy: 4 x 120 ms, c=8", vec![120.0; 4], 8, 240),
            ("mixed: queueing_mesh, c=4", queueing_mesh(), 4, 2_000),
            (
                "mixed: queueing_mesh, c=4, long",
                queueing_mesh(),
                4,
                20_000,
            ),
        ];
        let variants = [
            ("before #438", false, 0.0),
            ("fleet prior only", false, FLEET_PRIOR_WEIGHT),
            ("warm-up skip only", true, 0.0),
            ("#438", true, FLEET_PRIOR_WEIGHT),
        ];
        for (label, truth, conc, requests) in cases {
            println!("\n  {label}");
            for cold in [0.0, 500.0] {
                let make = |round_robin: bool, skip: bool| {
                    let mut f = fleet_of(truth.clone(), cold, Observation::RoundTrip);
                    f.round_robin = round_robin;
                    f.skip_first_observation = skip;
                    f
                };
                let (rr, _) = run_many(
                    || make(true, false),
                    requests,
                    conc,
                    &seeds,
                    &Weights::default(),
                );
                println!("    cold {cold:>3} {:<18} {rr}", "round-robin");
                for (name, skip, prior) in variants {
                    let w = Weights {
                        fleet_prior_weight: prior,
                        ..Weights::default()
                    };
                    let (st, split) = run_many(|| make(false, skip), requests, conc, &seeds, &w);
                    let dev = split
                        .iter()
                        .map(|x| (x - 1.0 / split.len() as f64).abs())
                        .fold(0.0, f64::max);
                    println!("    cold {cold:>3} {name:<18} {st}  split off by {dev:.3}");
                }
            }
        }
    }

    /// Sweep `d`, the weighting exponent, and the queue-term convexity from
    /// #264 against p50/p90/p99/max, on the same closed-loop concurrent
    /// simulation as `adaptive_routing_keeps_the_tail_within_bounds_of_the_oracle`.
    /// This is measurement, not a permanent regression: it takes tens of
    /// seconds and its purpose is the printed table, not an assertion. Run
    /// with:
    ///   cargo test --release --bin zc -- broker::policy::regret_tests::sweep_d_exponent_and_queue_convexity --ignored --nocapture
    #[test]
    #[ignore = "measurement, not a regression: run manually, see doc comment"]
    fn sweep_d_exponent_and_queue_convexity() {
        let requests = 20_000;
        let concurrency = 4;
        let seeds = [1u64, 2, 3, 4, 5];

        let mut oracle = Vec::new();
        for &seed in &seeds {
            oracle.extend(run_oracle_concurrent(
                queueing_mesh(),
                requests,
                concurrency,
                seed,
            ));
        }
        let o = tail_stats(&oracle);
        println!("\n  oracle (always the fastest worker, still queued): {o}");

        println!(
            "\n  {:>2} | {:>4} | {:>6} | {:>6} | {:>6} | {:>6} | {:>6} | {:>6}",
            "d", "exp", "queue", "mean", "p50", "p90", "p99", "max"
        );
        for &d in &[2usize, 3, 4, 8] {
            for &exponent in &[1.0f64, 1.5, 2.0, 3.0] {
                for &queue_convexity in &[1.0f64, 2.0] {
                    let w = Weights {
                        weighting_exponent: exponent,
                        queue_convexity,
                        ..Weights::default()
                    };
                    let mut latencies = Vec::new();
                    for &seed in &seeds {
                        latencies.extend(run_policy_concurrent(
                            queueing_mesh(),
                            requests,
                            concurrency,
                            seed,
                            d,
                            &w,
                        ));
                    }
                    let s = tail_stats(&latencies);
                    let queue_label = if queue_convexity == 1.0 {
                        "linear"
                    } else {
                        "convex"
                    };
                    println!(
                        "  {:>2} | {:>4} | {:>6} | {:>6.0} | {:>6.0} | {:>6.0} | {:>6.0} | {:>6.0}",
                        d, exponent, queue_label, s.mean, s.p50, s.p90, s.p99, s.max
                    );
                }
            }
        }
    }

    /// The second half of #264: sweep staleness against the exponent and the
    /// queue term, at the now-default `d = 4`, to find out whether the
    /// sharper exponent (3.0) and the convex queue term the first sweep
    /// favoured on a perfectly-visible harness still win once the harness can
    /// lie about `in_flight` the way a real broker's heartbeat does.
    ///
    /// `staleness = 0` reproduces #280's harness exactly (perfect,
    /// synchronous visibility) so this table's `0` row is the sanity check
    /// that this harness still agrees with #280 where it should. The rest of
    /// the range (1, 2, 4, 8, 16) brackets realistic staleness: concurrency
    /// here is 4, so at most 4 decisions can ever be genuinely concurrent,
    /// but a real heartbeat interval (15s, `HEARTBEAT_INTERVAL` in
    /// `src/serve.rs`) covers far more than 4 decisions at these service
    /// times (100 ms - 1 s) once many closed-loop clients share a worker, so
    /// the upper end of the range is deliberately past the concurrency
    /// figure.
    ///
    /// Measurement, not a regression: run with
    ///   cargo test --release --bin zc -- broker::policy::regret_tests::sweep_staleness_against_exponent_and_queue_convexity --ignored --nocapture
    #[test]
    #[ignore = "measurement, not a regression: run manually, see doc comment"]
    fn sweep_staleness_against_exponent_and_queue_convexity() {
        let requests = 20_000;
        let concurrency = 4;
        let d = 4; // the now-default from #280
        let seeds = [1u64, 2, 3, 4, 5];

        let mut oracle = Vec::new();
        for &seed in &seeds {
            oracle.extend(run_oracle_concurrent(
                queueing_mesh(),
                requests,
                concurrency,
                seed,
            ));
        }
        let o = tail_stats(&oracle);
        println!("\n  oracle (always the fastest worker, still queued): {o}");

        println!(
            "\n  {:>5} | {:>4} | {:>6} | {:>6} | {:>6} | {:>6} | {:>6} | {:>6}",
            "stale", "exp", "queue", "mean", "p50", "p90", "p99", "max"
        );
        for &staleness in &[0usize, 1, 2, 4, 8, 16] {
            for &exponent in &[1.0f64, 1.5, 2.0, 3.0] {
                for &queue_convexity in &[1.0f64, 2.0] {
                    let w = Weights {
                        weighting_exponent: exponent,
                        queue_convexity,
                        ..Weights::default()
                    };
                    let mut latencies = Vec::new();
                    for &seed in &seeds {
                        latencies.extend(run_policy_concurrent_with_staleness(
                            queueing_mesh(),
                            requests,
                            concurrency,
                            seed,
                            d,
                            &w,
                            staleness,
                        ));
                    }
                    let s = tail_stats(&latencies);
                    let queue_label = if queue_convexity == 1.0 {
                        "linear"
                    } else {
                        "convex"
                    };
                    println!(
                        "  {:>5} | {:>4} | {:>6} | {:>6.0} | {:>6.0} | {:>6.0} | {:>6.0} | {:>6.0}",
                        staleness, exponent, queue_label, s.mean, s.p50, s.p90, s.p99, s.max
                    );
                }
            }
        }
    }
}