okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-dc-learn-fix fc66df986 into the batch 16 candidate (draft-cost table learning fix)aad676f43

main
64.5 KiB957 linesraw
1// src/spec/draft_policy_test.cpp - DraftPolicy: when does a lookup window beat the MTP's?
2//
3// Simulated rounds with the costs measured on the RTX 5070 (window-cost: ~10 ms more per token) check that
4//   1. with no lookup proposal the MTP window is kept;
5//   2. lookup drafts that are mostly rejected stop being taken (their bucket's rate falls);
6//   3. lookup drafts that are always accepted are taken, and the window grows with them;
7//   4. match-length buckets learn separately (short matches failing does not stop long ones);
8//   5. the policy never proposes a window beyond its cap.
9#include "strata/spec/draft_policy.hpp"
10
11#include <cmath>
12#include <cstdint>
13#include <cstdio>
14#include <filesystem>
15#include <fstream>
16#include <string>
17#include <vector>
18
19using strata::spec::DraftPolicy;
20
21namespace {
22int g_fail = 0;
23void check(bool ok, const char* what) {
24    std::printf("  %-66s %s\n", what, ok ? "ok" : "FAIL");
25    if (!ok) ++g_fail;
26}
27double cost(int t) { return 19.0 + 10.5 * (t - 1); }   // ms per round, measured shape
28}  // namespace
29
30int main() {
31    std::printf("draft_policy_test\n");
32    {
33        DraftPolicy p(6);
34        for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4));   // MTP windows of 4: 3 tokens each
35        const DraftPolicy::Pick k = p.choose(4, 0, 0);
36        check(!k.lookup && k.t == 4, "no proposal: the MTP window");
37    }
38    {
39        DraftPolicy p(6);
40        for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4));
41        for (int t = 2; t <= 6; ++t) p.observe(false, t, 0, 0, cost(t));
42        for (int i = 0; i < 40; ++i) p.observe(true, 6, 0, 4, cost(6));      // short matches, all rejected
43        check(p.lookup_rate(4) < 0.15, "rejected short-match drafts: their rate falls below 0.15");
44        check(!p.choose(4, 5, 4).lookup, "rejected short-match drafts: no longer taken");
45        for (int i = 0; i < 40; ++i) p.observe(true, 6, 5, 30, cost(6));     // long matches, all accepted
46        check(p.lookup_rate(30) > 0.9, "accepted long-match drafts: their rate rises above 0.9");
47        const DraftPolicy::Pick k = p.choose(4, 5, 30);
48        check(k.lookup && k.t == 6, "accepted long matches: the full lookup window is taken");
49        check(!p.choose(4, 5, 4).lookup, "buckets are separate: short matches still not taken");
50        check(p.choose(4, 20, 30).t <= 6, "never beyond the window cap");
51    }
52    {
53        DraftPolicy p(8);
54        for (int i = 0; i < 50; ++i) p.observe(false, 3, 2, 0, cost(3));      // a very good MTP: 3 of 3 tokens
55        for (int t = 2; t <= 8; ++t) p.observe(false, t, t - 1, 0, cost(t));
56        for (int i = 0; i < 40; ++i) p.observe(true, 4, 2, 8, cost(4));       // lookup at q ~ 0.67
57        check(!p.choose(3, 7, 8).lookup, "a mediocre lookup does not replace a strong MTP window");
58    }
59    {
60        DraftPolicy p(6);
61        for (int i = 0; i < 50; ++i) p.observe(false, 4, 3, 0, cost(4));      // a near-perfect MTP, only size 4 seen
62        const DraftPolicy::Pick k = p.choose(4, 5, 40);
63        check(k.lookup && k.t == 6, "an unmeasured size is probed for a confident lookup");
64        for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6));   // it turns out very expensive
65        check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides");
66    }
67    {
68        // #1252: a wide size priced high in one slow stretch is measured again after a while
69        DraftPolicy p(6);
70        for (int i = 0; i < 50; ++i) p.observe(false, 4, 3, 0, cost(4));      // a strong MTP
71        for (int t = 2; t <= 6; ++t) for (int i = 0; i < 4; ++i) p.observe(false, t, t - 1, 0, cost(t));
72        for (int i = 0; i < 6; ++i) p.observe(true, 6, 5, 40, 4.0 * cost(6));  // the wide size, in a slow stretch
73        for (int i = 0; i < 30; ++i) p.observe(true, 4, 3, 40, cost(4));       // and the short window's rate is fine
74        bool saw6 = false;
75        for (int i = 0; i < 400 && !saw6; ++i) {
76            const DraftPolicy::Pick k = p.choose(4, 5, 40);
77            if (k.lookup && k.t == 6) { saw6 = true; p.observe(true, 6, 5, 40, cost(6)); }
78            else p.observe(k.lookup, k.t, k.t - 1, 40, cost(k.t));
79        }
80        check(saw6, "a stale wide size is tried again within a few hundred rounds");
81    }
82    {
83        // --lookup-chain: rows cheap (UMA-like) and the chain always accepted -> chained; rows dear or the chain
84        // always rejected -> not
85        auto cheap = [](int t) { return 40.0 + 2.0 * (t - 1); };
86        DraftPolicy p(8);
87        for (int t = 2; t <= 8; ++t)
88            for (int i = 0; i < 5; ++i) p.observe(false, t, 1, 0, cheap(t));
89        for (int i = 0; i < 30; ++i) p.observe(false, 4, 2, 0, cheap(4));
90        for (int i = 0; i < 30; ++i) p.observe_chain(4, 3, 6, 12, cheap(7));    // every chained token accepted
91        check(p.chain(4, 0.9, 3, 12) == 3, "chain: cheap rows, always accepted -> all 3 chained");
92        DraftPolicy q(8);
93        for (int t = 2; t <= 8; ++t)
94            for (int i = 0; i < 5; ++i) q.observe(false, t, 1, 0, cost(t));
95        for (int i = 0; i < 30; ++i) q.observe_chain(4, 3, 3, 4, cost(7));       // reached, never accepted
96        check(q.chain(4, 0.9, 3, 4) == 0, "chain: dear rows, never accepted -> none");
97        check(q.chain(4, 0.9, 0, 4) == 0 && q.chain(8, 1.0, 3, 40) == 0, "chain: nothing proposed / no room -> none");
98    }
99    {
100        // The stale-size check must also run when a shorter chain already pays. Synthetic costs isolate the
101        // selection policy: even a size that stays expensive is retried, but only once per stale interval.
102        DraftPolicy p(6);
103        for (int i = 0; i < 3; ++i) p.observe(false, 4, 3, 0, 40.0);
104        for (int i = 0; i < 3; ++i) p.observe_chain(4, 1, 4, 40, 42.0);
105        for (int i = 0; i < 3; ++i) p.observe_chain(4, 2, 5, 40, 1000.0);
106        check(p.chain(4, 1.0, 2, 40) == 1, "chain: the profitable shorter chain initially wins");
107        int probes = 0, last_probe = -1;
108        bool spaced = true, confident = true;
109        for (int i = 0; i < 1000; ++i) {
110            const int k = p.chain(4, 1.0, 2, 40);
111            if (k == 2) {
112                ++probes;
113                spaced &= last_probe < 0 ? i >= 300 : i - last_probe > 300;
114                last_probe = i;
115                confident &= p.chain(4, 0.5, 2, 40) < 2;
116            }
117            p.observe_chain(4, k, 3 + k, 40, k == 2 ? 1000.0 : 42.0);
118        }
119        check(probes > 0 && probes <= 3 && spaced,
120              "chain: stale full size is re-probed despite a profitable shorter chain");
121        check(probes > 0 && confident, "chain: stale re-probes retain the MTP confidence gate");
122    }
123    {
124        // Gated proposals: within one generation the policy copy learns from committed outcomes only. A size
125        // whose cost is still guessed is probed until kProbes rounds of it have run, timed or not, not every round.
126        DraftPolicy live(6);
127        for (int i = 0; i < 50; ++i) live.observe(false, 4, 3, 0, cost(4));      // a strong MTP
128        live.observe(true, 6, 5, 8, 3.0 * cost(6));                             // size 6 timed once, dear
129        DraftPolicy frozen = live, copy = live;
130        int frozen_probes = 0, copy_probes = 0;
131        for (int i = 0; i < 20; ++i) {
132            const DraftPolicy::Pick f = frozen.choose(4, 5, 8);
133            frozen_probes += f.lookup && f.t == 6;
134            const DraftPolicy::Pick c = copy.choose(4, 5, 8);
135            copy_probes += c.lookup && c.t == 6;
136            copy.observe_committed(c.lookup, c.lookup ? c.t : 4, c.lookup ? 5 : 3, 8);
137        }
138        check(frozen_probes == 20, "gated: a frozen copy probes the guessed size every round");
139        check(copy_probes == 2, "gated: committed outcomes end the probes after kProbes rounds of the size");
140        check(copy.cost_ms(6) == live.cost_ms(6), "gated: committed outcomes leave the measured costs alone");
141    }
142    {
143        // Gated proposals: a round's time reaches the generation's copy only once the committed position has passed
144        // every counter it depends on. Cheap costs from earlier text stop steering long lookups once the dear
145        // repetitive-text times are applied; a held time is not a new probe.
146        DraftPolicy live(6);
147        for (int t = 2; t <= 6; ++t) for (int i = 0; i < 5; ++i) live.observe(false, t, 1, 0, cost(t) * 0.2);   // cheap stretch
148        DraftPolicy copy = live;
149        check(copy.choose(4, 5, 40).lookup && copy.choose(4, 5, 40).t == 6, "delayed: cheap inherited costs take the full lookup");
150        const double before = copy.cost_ms(6);
151        copy.observe_committed(true, 6, 5, 40);
152        copy.defer_cost(110, 6, 40.0 * cost(6));
153        copy.apply_costs(110);
154        check(copy.cost_ms(6) == before, "delayed: a time is held while its counters can still be drawn");
155        copy.apply_costs(111);
156        check(copy.cost_ms(6) > before, "delayed: applied once the committed position passes its last counter");
157        for (int i = 0; i < 40; ++i) {
158            copy.observe_committed(true, 6, 5, 40);
159            copy.defer_cost(120 + i, 6, 40.0 * cost(6));
160            copy.apply_costs(121 + i);
161        }
162        check(copy.choose(4, 5, 40).t < 6, "delayed: dear measured times shorten the lookup window");
163        DraftPolicy fresh(6);
164        fresh.observe_committed(true, 6, 5, 40);
165        fresh.defer_cost(5, 6, 30.0);
166        fresh.apply_costs(6);
167        fresh.observe_committed(true, 6, 5, 40);
168        check(fresh.choose(4, 5, 40).lookup && fresh.choose(4, 5, 40).t == 6,
169              "delayed: a held time does not count as another probe");
170    }
171    {
172        // --lookup-max-t: only the allowed sizes are taken; a proposal between two sizes takes the smaller; a size
173        // disabled (its graph found no VRAM) is never proposed again; sizes past 8 work like the others
174        DraftPolicy p(16);
175        p.set_sizes((1u << 1) | (1u << 2) | (1u << 3) | (1u << 5) | (1u << 8) | (1u << 16));
176        for (int i = 0; i < 50; ++i) p.observe(false, 3, 2, 0, cost(3));
177        for (int i = 0; i < 40; ++i) p.observe(true, 16, 15, 40, 19.0 + 3.0 * 15);   // long windows: cheap, all accepted
178        for (int i = 0; i < 40; ++i) p.observe(true, 8, 7, 40, 19.0 + 3.0 * 7);
179        for (int i = 0; i < 40; ++i) p.observe(true, 5, 4, 40, 19.0 + 3.0 * 4);
180        const DraftPolicy::Pick a = p.choose(3, 15, 40);
181        check(a.lookup && a.t == 16, "sizes: a full 16-token lookup window when it pays");
182        const DraftPolicy::Pick b = p.choose(3, 10, 40);
183        check(b.lookup && b.t == 8, "sizes: a 10-token proposal takes the 8-token size");
184        bool ok = true;
185        for (int k = 1; k <= 15; ++k) {
186            const DraftPolicy::Pick c = p.choose(3, k, 40);
187            ok &= !c.lookup || p.allowed(c.t);
188        }
189        check(ok, "sizes: never a size outside the mask");
190        p.disable(16);
191        const DraftPolicy::Pick d = p.choose(3, 15, 40);
192        check(d.lookup && d.t == 8, "sizes: a disabled size falls back to the next one");
193        check(p.fit(7) == 5 && p.fit(16) == 8 && p.fit(1) == 1, "sizes: fit() finds the largest allowed size");
194        DraftPolicy q(16);
195        q.set_sizes((1u << 1) | (1u << 2) | (1u << 3) | (1u << 8));
196        bool cok = true;
197        for (int k = 0; k <= 13; ++k) {
198            const int n = q.chain(3, 1.0, k, 40);
199            cok &= n == 0 || q.allowed(3 + n);
200        }
201        check(cok, "sizes: a chained window's total is an allowed size");
202    }
203    {
204        // Fixed costs: measured round times never reach the costs, so two runs that see the same tokens choose the same windows
205        // whatever their timing; the same policy without a table follows the time.
206        const double table[6] = {19.0, 29.5, 40.0, 50.5, 61.0, 71.5};
207        DraftPolicy a(6), b(6), live1(6), live2(6);
208        a.set_fixed_costs(table, 6);
209        b.set_fixed_costs(table, 6);
210        check(a.fixed() && !live1.fixed(), "fixed: only the policy given a table is fixed");
211        bool same = true;
212        for (int i = 0; i < 400; ++i) {
213            const int t = 2 + i % 5;
214            const bool lk = i % 3 == 0;
215            const int acc = (i * 7) % t;
216            const int match = lk ? 12 + (i % 30) : 0;
217            a.observe(lk, t, acc, match, cost(t));
218            b.observe(lk, t, acc, match, cost(t) * (i % 4 ? 0.3 : 5.0));   // another run's times, far off and jittering
219            live1.observe(lk, t, acc, match, cost(t));
220            live2.observe(lk, t, acc, match, cost(t) * (i % 4 ? 0.3 : 5.0));
221            const DraftPolicy::Pick pa = a.choose(4, 5, 12 + i % 30), pb = b.choose(4, 5, 12 + i % 30);
222            same &= pa.lookup == pb.lookup && pa.t == pb.t;
223            same &= a.chain(4, 0.8, 3, 20) == b.chain(4, 0.8, 3, 20);
224            DraftPolicy::ChainState sa, sb;
225            same &= a.keep_draft(sa, 0, 0.7f, 6) == b.keep_draft(sb, 0, 0.7f, 6) && sa.kept == sb.kept;
226        }
227        check(same, "fixed: different round times, the same windows, chains and kept drafts");
228        check(a.cost_ms(3) == table[2] && b.cost_ms(3) == table[2], "fixed: the table is never replaced by a measurement");
229        check(live1.cost_ms(3) != live2.cost_ms(3), "no table: the measured costs follow the round times");
230        DraftPolicy f(6);                                           // held times (gated proposals) are dropped too
231        f.set_fixed_costs(table, 6);
232        f.defer_cost(5, 4, 999.0);
233        f.apply_costs(100);
234        check(f.cost_ms(4) == table[3], "fixed: defer_cost / apply_costs leave the table alone");
235        DraftPolicy g(6), h(6);                                     // only size 4 seen: the adaptive policy probes size 6, the fixed one does not
236        for (int i = 0; i < 50; ++i) { g.observe(false, 4, 3, 0, cost(4)); h.observe(false, 4, 3, 0, cost(4)); }
237        g.set_fixed_costs(nullptr, 0);                              // fixed where it stands (no table): what was measured stays
238        check(h.choose(4, 5, 40).lookup && h.choose(4, 5, 40).t == 6, "no table: the unmeasured size is probed (as before)");
239        check(!g.choose(4, 5, 40).lookup, "fixed: no first-use probe; the table decides");
240        DraftPolicy m(6);                                           // a table set after measuring replaces the EMA
241        for (int i = 0; i < 30; ++i) m.observe(false, 4, 3, 0, 80.0);
242        m.set_fixed_costs(table, 6);
243        check(m.cost_ms(4) == table[3], "fixed: set after measuring, the table replaces the measured cost");
244    }
245    {
246        // CostLearner: plain trimmed means per size, interpolation, readiness and the disturbance checks.
247        using strata::spec::CostLearner;
248        CostLearner L;
249        for (int i = 0; i < 200; ++i) {
250            L.add(0, 1, 10.0 + (i % 3));                            // 10, 11, 12: mean 11
251            L.add(0, 4, i == 7 ? 400.0 : 20.0);                     // one capture-sized outlier: trimmed away
252            if (i < 40) L.add(0, 6, 30.0);
253        }
254        const std::vector<double> t = L.table(0, 20);
255        check(t.size() == 6, "learner: the table runs to the largest size seen");
256        check(t.size() == 6 && t[0] > 10.9 && t[0] < 11.1 && t[3] == 20.0 && t[5] == 30.0, "learner: trimmed means of the measured sizes");
257        check(t.size() == 6 && t[4] == 25.0, "learner: an unseen size between two measured ones is linear in the size");
258        check(t.size() == 6 && t[1] > 11.0 && t[1] < t[3] && t[2] > t[1] && t[2] < t[3], "learner: sizes between are ordered");
259        check(L.table(1, 20).empty(), "learner: a bucket with no rounds has no table");
260        check(!L.check(1000, 20).ready && L.check(400, 20).ready, "learner: ready only after the given number of rounds");
261        check(!L.check(400, 20).disturbed, "learner: a clean stretch is not disturbed");
262        CostLearner D;                                              // the second half twice as slow: a disturbed stretch
263        for (int i = 0; i < 200; ++i) D.add(0, 4, i < 100 ? 20.0 : 40.0);
264        const CostLearner::Verdict dv = D.check(100, 20);
265        check(dv.disturbed && !dv.why.empty(), "learner: a drift between the halves is a disturbance");
266        CostLearner S;                                              // 10 % of rounds stalled at 5x
267        for (int i = 0; i < 200; ++i) S.add(0, 4, i % 10 == 3 ? 100.0 : 20.0);
268        check(S.check(100, 20).disturbed, "learner: many spikes are a disturbance");
269        CostLearner O;                                              // a wider window measured cheaper than a narrower one
270        for (int i = 0; i < 50; ++i) { O.add(0, 2, 30.0); O.add(0, 4, 20.0); }
271        check(O.check(50, 20).disturbed, "learner: a wider window cheaper than a narrower one is a disturbance");
272        DraftPolicy p(6);                                           // the policy feeds the learner only while learning
273        p.observe(false, 4, 3, 0, 20.0);
274        check(p.learner().rounds() == 0, "learning off: nothing is collected");
275        p.set_learning(true);
276        p.observe(false, 4, 3, 0, 20.0);
277        p.observe_chain(3, 1, 2, 20, 21.0);
278        p.defer_cost(5, 2, 15.0);
279        p.apply_costs(100);
280        check(p.learner().rounds() == 3 && p.learner().samples(0, 4) == 2 && p.learner().samples(0, 2) == 1,
281              "learning on: observe, observe_chain and held times are collected");
282    }
283    {
284        // The fixture of the Mac lane's fresh learning run (M5 Max, Q2_0, 30 requests of 256 tokens): sample counts and mean round ms per window size.
285        // 4 rows had 2 samples: its value comes from its neighbours, not from the two samples.
286        using strata::spec::CostLearner;
287        const auto fill = [](CostLearner& L, int t, int n, double ms, double age) {   // n samples around ms (+-1 %, mean ms)
288            for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.005 * ((i % 5) - 2)), age);
289        };
290        CostLearner M;
291        fill(M, 1, 1193, 13.50, 2.0); fill(M, 2, 894, 15.74, 2.0); fill(M, 3, 1834, 18.40, 2.0); fill(M, 4, 2, 22.62, 2.0); fill(M, 5, 83, 24.95, 2.0);
292        const std::vector<double> t = M.table(0, 20);
293        check(t.size() == 5 && std::fabs(t[0] - 13.50) < 0.05 && std::fabs(t[2] - 18.40) < 0.05 && std::fabs(t[4] - 24.95) < 0.05, "fit: the well-sampled sizes are their trimmed means");
294        check(t.size() == 5 && std::fabs(t[3] - (18.40 + 24.95) / 2.0) < 0.05, "fit: 4 rows (2 samples) lie between its neighbours, not at its own 22.62");
295        check(M.rounds() == 4006 && M.late_rounds() == 0, "fit: all 4,006 rounds of the fixture were fresh");
296        // a size above the measured ones (5 rows with 8 samples): the straight line through the two largest measured sizes
297        CostLearner E;
298        fill(E, 1, 600, 12.5, 2.0); fill(E, 2, 400, 14.2, 2.0); fill(E, 3, 700, 16.2, 2.0); fill(E, 5, 8, 99.0, 2.0);
299        const std::vector<double> e = E.table(0, 20);
300        check(e.size() == 5 && std::fabs(e[3] - (16.2 + 2.0)) < 0.05 && std::fabs(e[4] - (16.2 + 4.0)) < 0.05,
301              "fit: 4 and 5 rows above the measured sizes continue the line through 2 and 3 rows (8 samples of 5 rows are not trusted)");
302        bool mono = true;
303        for (size_t i = 1; i < e.size(); ++i) mono &= e[i] >= e[i - 1];
304        CostLearner Dn;                                                       // a size measured cheaper than the one before it (noise): the table does not fall
305        fill(Dn, 1, 100, 20.0, 2.0); fill(Dn, 2, 100, 19.0, 2.0); fill(Dn, 3, 100, 25.0, 2.0);
306        const std::vector<double> d = Dn.table(0, 20);
307        mono &= d.size() == 3 && d[1] >= d[0] && d[2] >= d[1];
308        check(mono, "fit: the table never falls from one size to the next");
309        // busy age: a fast state for the first seconds of a run, a slow and steeper one later; only the first is kept
310        CostLearner B;
311        for (int i = 0; i < 1400; ++i) {
312            B.add(0, 1, 12.5, 4.0); B.add(0, 2, 14.2, 4.0); B.add(0, 3, 16.2, 4.0);               // fresh (the first seconds of a run)
313            B.add(0, 1, 14.5, 60.0); B.add(0, 2, 17.1, 60.0); B.add(0, 3, 20.2, 60.0);            // the same machine after a minute of load
314            if (i % 25 == 0) { B.add(0, 5, 21.3, 4.0); B.add(0, 5, 27.7, 60.0); }
315        }
316        const std::vector<double> b = B.table(0, 20);
317        check(B.rounds() == 4200 + 56 && B.late_rounds() == 4200 + 56, "busy age: late rounds are counted and not kept");
318        check(b.size() == 5 && std::fabs(b[2] - 16.2) < 0.05 && std::fabs(b[4] / b[2] - 21.3 / 16.2) < 0.01,
319              "busy age: the table is the fast state (5 rows against 3 rows 1.31, not 1.37 of the late rounds)");
320        CostLearner U;                                                        // an age that is not known counts as fresh
321        U.add(0, 3, 16.0);
322        check(U.rounds() == 1 && U.late_rounds() == 0, "busy age: an unknown age (none given) is kept");
323        // readiness: a stretch that never paused ends with its first seconds after 3 x the quota; one that is mid-way is not ready
324        CostLearner Bur;
325        for (int i = 0; i < 300; ++i) { Bur.add(0, 1, 12.5, 2.0); Bur.add(0, 2, 14.2, 2.0); Bur.add(0, 3, 16.2, 2.0); }    // 900 fresh rounds
326        check(!Bur.check(1000, 20).ready, "ready: 900 fresh rounds and nothing else is not ready");
327        for (int i = 0; i < 700; ++i) Bur.add(0, 3, 20.2, 90.0);
328        check(!Bur.check(1000, 20).ready, "ready: late rounds below 3 x the quota do not end a short stretch");
329        CostLearner Bur2;                                                     // one long burst: 330 fresh rounds, then 2,700 late ones
330        for (int i = 0; i < 110; ++i) { Bur2.add(0, 1, 12.5, 2.0); Bur2.add(0, 2, 14.2, 2.0); Bur2.add(0, 3, 16.2, 2.0); }
331        for (int i = 0; i < 2000; ++i) Bur2.add(0, 3, 20.2, 90.0);
332        check(!Bur2.check(1000, 20).ready, "ready: 330 fresh + 2,000 late rounds (under 3 x the quota) is not ready");
333        for (int i = 0; i < 700; ++i) Bur2.add(0, 3, 20.2, 90.0);
334        const CostLearner::Verdict bv = Bur2.check(1000, 20);
335        const std::vector<double> bt = Bur2.table(0, 20);
336        check(bv.ready && !bv.disturbed && bt.size() == 3 && std::fabs(bt[2] - 16.2) < 0.05,
337              "ready: one burst that never paused ends after 3 x the quota, with the table of its first seconds");
338        CostLearner Few;                                                      // 150 fresh rounds only: not enough even after a very long burst
339        for (int i = 0; i < 50; ++i) { Few.add(0, 1, 12.5, 2.0); Few.add(0, 2, 14.2, 2.0); Few.add(0, 3, 16.2, 2.0); }
340        for (int i = 0; i < 5000; ++i) Few.add(0, 3, 20.2, 90.0);
341        check(!Few.check(1000, 20).ready, "ready: under a fifth of the quota kept is never ready");
342        // a machine without a state effect (the Radeon 780M: 75.5 ms for one row early, 76.0 late; windows of 1, 3 and 6 rows): every round counts, the rare sizes
343        // get all their samples (3 rows: 8 fresh + 100 late)
344        CostLearner R;
345        fill(R, 1, 80, 75.5, 2.0); fill(R, 3, 8, 111.0, 2.0); fill(R, 6, 3, 178.0, 2.0);
346        fill(R, 1, 1200, 76.0, 40.0); fill(R, 3, 100, 111.2, 40.0); fill(R, 6, 14, 178.1, 40.0);
347        const std::vector<double> rt = R.table(0, 20);
348        check(!R.state_effect(0, 20), "pooled: 0.7 % between early and late rounds is no state effect");
349        check(rt.size() == 6 && std::fabs(rt[2] - 111.1) < 0.2 && std::fabs(rt[0] - 76.0) < 0.2, "pooled: the table uses every round (3 rows from 108 samples)");
350        check(R.check(1000, 20).ready, "pooled: ready after the quota of rounds of any age");
351        check(B.state_effect(0, 20), "state effect: 16 % between early and late rounds is one");
352        // the policy hands the age to the learner, and a held (gated) time keeps the age it had
353        DraftPolicy pa(6);
354        pa.set_learning(true);
355        pa.set_busy_age(30.0);
356        pa.observe(false, 3, 1, 0, 20.0);
357        pa.set_busy_age(2.0);
358        pa.observe(false, 3, 1, 0, 16.0);
359        check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 1 && pa.learner().samples(0, 3) == 1, "policy: a round is kept by the busy age it ran at");
360        pa.set_busy_age(40.0);
361        pa.defer_cost(5, 3, 21.0);
362        pa.set_busy_age(1.0);
363        pa.apply_costs(100);
364        check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 2, "policy: a held time keeps the busy age of its round");
365    }
366    {
367        // The table file: a round trip, another key, a cut-short file, a missing file, a folder that does not exist yet.
368        namespace fs = std::filesystem;
369        using strata::spec::CostFile;
370        std::error_code ec;
371        const fs::path dir = fs::temp_directory_path(ec) / ("strata-dpt-" + std::to_string((unsigned long long) (uintptr_t) &ec));
372        const std::string path = (dir / "sub" / "t.costs").string();
373        CostFile c;
374        c.key = "card A|engine 1|model m\nspec 6";
375        c.tables[0] = {15.18, 18.55, 20.69, 23.65};
376        c.tables[2] = {16.0, 19.0};
377        std::string why;
378        check(strata::spec::write_cost_file(path, c, why), "file: written, its folder made");
379        CostFile r;
380        const bool ok = strata::spec::read_cost_file(path, c.key, r, why);
381        check(ok && r.tables[0].size() == 4 && r.tables[0][3] == 23.65 && r.tables[1].empty() && r.tables[2].size() == 2,
382              "file: read back with its key, every bucket as written");
383        check(!strata::spec::read_cost_file(path, "card B|engine 1|model m spec 6", r, why) && !why.empty(), "file: another key is not loaded");
384        check(!strata::spec::read_cost_file((dir / "none.costs").string(), c.key, r, why), "file: a missing file is not loaded");
385        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; }
386        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a cut-short file (no end line) is not loaded");
387        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,abc\nend\n"; }
388        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed table is not loaded");
389        check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why), "file: a bad file is replaced whole");
390        check(!fs::exists(fs::path(path + ".tmp"), ec), "file: no temporary file is left");
391        check(r.cpu_share < 0.0, "file: no share written, none read");
392        c.cpu_share = 0.45;
393        check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.cpu_share == 0.45,
394              "file: the CPU prompt share is stored and read back with the table");
395        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 1.7\nend\n"; }
396        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a share outside 0..1 is not loaded");
397        // the decode PCIe share PcieAuto settled on (repeatable output): stored and read back; a file written before it has none, and
398        // still loads (the engine then refines the share as before and writes it)
399        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 0.900\nend\n"; }
400        check(strata::spec::read_cost_file(path, "x", r, why) && r.cpu_share == 0.9 && r.pcie_frac < 0.0,
401              "file: a file from before the PCIe share loads, with no PCIe share");
402        c.pcie_frac = 0.15;
403        check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.pcie_frac == 0.15 &&
404                  r.cpu_share == 0.45 && r.tables[0].size() == 4,
405              "file: the PCIe share is stored and read back with the table and the prompt share");
406        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie -0.2\nend\n"; }
407        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a PCIe share outside 0..1 is not loaded");
408        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie 0.15x\nend\n"; }
409        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed PCIe share is not loaded");
410        // version 1 (learned from every round, so from the slow state of a long burst): not loaded, learned again
411        { std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nend\n"; }
412        check(!strata::spec::read_cost_file(path, "x", r, why) && why.find("format") != std::string::npos, "file: a version 1 table is not loaded (learned again)");
413        // a start closed in the middle of learning leaves no table: nothing is written before the stretch is ready, and a half-written temporary file
414        // (the process died while writing) is never read as the table
415        fs::remove(fs::path(path), ec);
416        { std::ofstream f(path + ".tmp", std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; }
417        check(!strata::spec::read_cost_file(path, "x", r, why), "file: a half-written temporary file beside a missing table is not a table");
418        check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && !fs::exists(fs::path(path + ".tmp"), ec),
419              "file: the next write replaces the leftover temporary file and the table loads");
420        fs::remove_all(dir, ec);
421    }
422    {
423        // sizes with too few samples: a rough measurement counts when it is not below the trend, a stalled handful does not, and a fill above the
424        // measured sizes never flattens the measured trend (Radeon 780M, 11-13: sizes 1 / 3 measured at 76.2 / 111.6 ms, size 4 with 6 rounds at 143)
425        using strata::spec::CostLearner;
426        const auto fill = [](CostLearner& L, int t, int n, double ms) {
427            for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.004 * ((i % 5) - 2)));
428        };
429        CostLearner R;
430        fill(R, 1, 1279, 76.2); fill(R, 2, 2, 97.0); fill(R, 3, 126, 111.6); fill(R, 4, 6, 143.0);
431        const std::vector<double> t = R.table(0, 20);
432        check(t.size() == 4 && std::fabs(t[3] - 143.0) < 0.5, "sizes: 6 rounds of 4 rows (143 ms, above the line's 129) count by their median");
433        check(t.size() == 4 && std::fabs(t[1] - (76.2 + 111.6) / 2.0) < 0.2, "sizes: 2 rounds of 2 rows are filled in linearly");
434        const std::vector<double> u = R.table(0, 20, 6);
435        bool mono = u.size() == 6;
436        for (size_t i = 1; i < u.size(); ++i) mono &= u[i] >= u[i - 1];
437        check(u.size() == 6 && mono && u[4] >= 143.0 + 0.9 * (143.0 - 111.6) && u[5] > u[4], "sizes: 5 and 6 rows continue the steeper measured slope (32 ms a row), not the first segment's 18");
438        CostLearner S;
439        fill(S, 1, 600, 12.5); fill(S, 2, 400, 14.2); fill(S, 3, 700, 16.2); fill(S, 4, 6, 99.0);
440        const std::vector<double> s = S.table(0, 20);
441        check(s.size() == 4 && std::fabs(s[3] - 18.2) < 0.05, "sizes: a handful of rounds 5x above the trend (a stall) is not a measurement");
442        CostLearner Q;                                              // costs 10 / 20 / 35: the fill goes on at 15 ms a row, not at 10
443        fill(Q, 1, 100, 10.0); fill(Q, 2, 100, 20.0); fill(Q, 3, 100, 35.0);
444        const std::vector<double> q = Q.table(0, 20, 5);
445        check(q.size() == 5 && q[3] >= 35.0 + 15.0 - 0.1 && q[4] >= 35.0 + 30.0 - 0.1, "sizes: a size above the measured ones never costs less than the last slope says");
446        check(Q.table(0, 20, 3).size() == 3 && Q.table(1, 20, 5).empty(), "sizes: upto adds nothing below the largest size seen, and an empty bucket stays empty");
447        // the learning stretch measures the sizes it has too few rounds of
448        const auto feed = [](DraftPolicy& p, int n) {
449            for (int i = 0; i < n; ++i) { p.observe(false, 1, 0, 0, 76.0); if (i % 4 == 0) p.observe(false, 3, 2, 0, 111.0); }
450        };
451        DraftPolicy y(8);
452        y.set_learning(true);
453        feed(y, 40);
454        y.choose(1, 5, 3);
455        check(y.forced_rounds() == 0, "explore: nothing is forced in the first rounds of a stretch");
456        feed(y, 300);
457        const DraftPolicy::Pick f1 = y.choose(1, 5, 3);
458        check(f1.lookup && f1.t == 2 && y.forced_rounds() == 1, "explore: after the first rounds the smallest size with few samples is taken, if a proposal reaches it");
459        const DraftPolicy::Pick f2 = y.choose(1, 1, 3);
460        check(y.forced_rounds() == 2 && f2.lookup && f2.t == 2, "explore: a proposal of one draft reaches 2 rows only");
461        DraftPolicy y16(16);                                        // the budget: 14 sizes that need 30 rounds each are more than the stretch's budget
462        y16.set_learning(true);
463        feed(y16, 400);
464        for (int i = 0; i < 1200; ++i) {
465            const DraftPolicy::Pick pk = y16.choose(1, 15, 3);
466            y16.observe(pk.lookup, pk.t, pk.t > 1 ? pk.t - 1 : 0, 3, 76.0 + 17.0 * (pk.t - 1));
467        }
468        check(y16.forced_rounds() == DraftPolicy::kExploreBudget, "explore: the forced rounds stop at the stretch's budget");
469        const int before = y16.forced_rounds();
470        for (int i = 0; i < 50; ++i) y16.choose(1, 15, 3);
471        check(y16.forced_rounds() == before, "explore: nothing is forced once the budget is spent");
472        DraftPolicy z(8);                                           // the cap per size: with a budget left over, one size is still not forced more than kExplorePerSize times
473        z.set_learning(true);
474        feed(z, 400);
475        for (int i = 0; i < 200; ++i) { const DraftPolicy::Pick pk = z.choose(1, 1, 3); z.observe(pk.lookup, pk.t, 0, 3, 0.0); }   // no time, so no sample ever arrives
476        check(z.forced_rounds() == DraftPolicy::kExplorePerSize, "explore: a size is forced at most kExplorePerSize times");
477        z.reset_learning();
478        check(z.forced_rounds() == 0 && z.learner().rounds() == 0, "explore: a new stretch starts with a new budget");
479        DraftPolicy n(8);                                           // not learning, or fixed: the policy never takes a window for its size's sake
480        feed(n, 400);
481        n.choose(1, 5, 3);
482        DraftPolicy x(8);
483        x.set_learning(true);
484        feed(x, 400);
485        const double ms[3] = {76.0, 95.0, 111.0};
486        x.set_fixed_costs(ms, 3);
487        for (int i = 0; i < 20; ++i) x.choose(1, 5, 3);
488        check(n.forced_rounds() == 0 && x.forced_rounds() == 0, "explore: not while learning is off, and not once the costs are fixed");
489        DraftPolicy w(8);                                           // a size no proposal reaches stays filled in
490        w.set_learning(true);
491        feed(w, 600);
492        for (int i = 0; i < 100; ++i) { const DraftPolicy::Pick pk = w.choose(1, 1, 3); w.observe(pk.lookup, pk.t, 1, 3, 95.0); }
493        const std::vector<double> wt = w.learner().table(0, 20, 6);
494        check(w.learner().samples(0, 4) == 0 && wt.size() == 6 && wt[3] > wt[2] && wt[5] > wt[3], "explore: a size no proposal reaches is filled in above the measured ones");
495        // the window of a round that has no proposal: any undersampled size up to the cap, but not the size it already is
496        DraftPolicy m(8);
497        m.set_learning(true);
498        feed(m, 400);
499        check(m.explore_window(3, 6) == 2 && m.forced_rounds() == 1, "window: the smallest unmeasured size is run, not the one the round already has");
500        check(m.explore_window(2, 6) == 4, "window: a size with samples (3 rows) is skipped, the next unmeasured one is run");
501        check(m.explore_window(1, 1) == 0, "window: a cap of one row leaves nothing to run");
502        DraftPolicy m0(8);
503        feed(m0, 400);
504        check(m0.explore_window(3, 6) == 0, "window: nothing while learning is off");
505        DraftPolicy lk(8);                                          // a round with no proposal at all: a lookup-type window of an unmeasured size
506        lk.set_learning(true);
507        feed(lk, 400);
508        check(lk.explore_lookup(5) == 2 && lk.explore_lookup(1) == 0 && m0.explore_lookup(5) == 0, "window: a round without a proposal can time a lookup-type size, only while learning");
509        // a late round counts only where the stretch has shown no state effect
510        DraftPolicy e1(8);                                          // fresh 76 ms, late 80 ms: a state effect
511        e1.set_learning(true);
512        e1.set_busy_age(2.0);
513        for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 76.0);
514        e1.set_busy_age(100.0);
515        for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 80.0);
516        check(e1.explore_window(3, 6) == 0, "gate: a late round is not forced when the stretch has a state effect");
517        e1.set_busy_age(2.0);
518        check(e1.explore_window(3, 6) == 2, "gate: a fresh round is");
519        DraftPolicy e2(8);                                          // fresh and late alike: no state effect
520        e2.set_learning(true);
521        e2.set_busy_age(2.0);
522        for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.0);
523        e2.set_busy_age(100.0);
524        for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.2);
525        check(e2.explore_window(3, 6) == 2, "gate: a late round is forced when the stretch shows no state effect");
526        DraftPolicy e3(8);                                          // late rounds only so far: unknown, so not forced
527        e3.set_learning(true);
528        e3.set_busy_age(100.0);
529        for (int i = 0; i < 150; ++i) e3.observe(false, 1, 0, 0, 76.0);
530        check(e3.explore_window(3, 6) == 0, "gate: a late round is not forced while the stretch cannot tell yet");
531        // a padded window: a short proposal, a size past it that has no samples, the caller allows filler rows
532        DraftPolicy g(8);
533        g.set_learning(true);
534        feed(g, 400);
535        for (int i = 0; i < 40; ++i) g.observe_forced(2, 95.0);     // size 2 measured (3 is fed already)
536        const DraftPolicy::Pick np = g.choose(1, 1, 3);
537        check(g.forced_rounds() == 0 || !np.lookup || np.pad == 0, "pad: without pad_cap a proposal of one draft never makes a longer window");
538        const DraftPolicy::Pick gp = g.choose(1, 1, 3, 7);
539        check(gp.lookup && gp.t == 4 && gp.pad == 2 && g.forced_rounds() == 1, "pad: with pad_cap the smallest unmeasured size is run, 2 filler rows past the proposal");
540        const double q0 = g.lookup_rate(3);
541        for (int i = 0; i < 30; ++i) g.observe_forced(4, 143.0);
542        check(g.lookup_rate(3) == q0 && g.learner().samples(0, 4) == 30, "pad: a forced round feeds the learner and no lookup statistic");
543        const DraftPolicy::Pick g5 = g.choose(1, 1, 3, 7);
544        check(g5.lookup && g5.t == 5 && g5.pad == 3, "pad: the next unmeasured size follows once one has its samples");
545        check(g.choose(1, 1, 3, 1).pad == 0, "pad: a pad_cap of one draft makes no filler");
546    }
547    {   // DRAFT-COSTS-5: a real price is the MEDIAN of its 16 rounds; the monotone guard repairs an inversion from the trusted side
548        namespace fs = std::filesystem;
549        using strata::spec::CalAcc;
550        using strata::spec::CostFile;
551        using strata::spec::CostLearner;
552        using Cal = std::array<std::array<CalAcc, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
553        using Rc = std::array<std::array<double, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
554        using Real = std::array<unsigned, CostLearner::kCtxBuckets>;
555        const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90};
556        const Cal cal0{};
557        const Rc rc0{};
558        {   // one cold round among 16 (the first use of a width): the real price is the median, a mean would be moved by it
559            DraftPolicy m(8);
560            m.set_fixed_costs(tab, 5, 0);
561            m.start_calibration(false, Real{}, cal0, rc0);
562            for (int i = 0; i < 15; ++i) m.observe(false, 2, 1, 0, 14.5);
563            m.observe(false, 2, 1, 0, 40.0);
564            CostFile cf;
565            std::string rep;
566            check(m.calibrate(cf, rep) && (cf.real[0] & 2u), "median: the 16th round marks the size real");
567            check(std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: one cold round among 16 does not move the real price");
568        }
569        {   // eight slow rounds in the first request, eight normal ones after: the median sits between (even count: mean of the two middle rounds)
570            DraftPolicy m(8);
571            m.set_fixed_costs(tab, 5, 0);
572            m.start_calibration(false, Real{}, cal0, rc0);
573            for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 15.0);
574            for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 14.0);
575            CostFile cf;
576            std::string rep;
577            check(m.calibrate(cf, rep) && std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: sixteen rounds of two values: the mean of the two middle ones");
578        }
579        {   // the rounds survive the file (a start collects part of them, the next start the rest) and a file line without them still loads (mean as before)
580            const fs::path dir = fs::temp_directory_path() / ("strata-dpt-med-" + std::to_string((unsigned long long) (uintptr_t) &tab));
581            const std::string path = (dir / "m.costs").string();
582            CostFile c;
583            c.key = "k";
584            c.tables[0] = {12.68, 14.30, 16.41};
585            c.cal[0][2] = CalAcc{};
586            c.cal[0][2].n = 3;
587            c.cal[0][2].sum = 43.5;
588            c.cal[0][2].nv = 3;
589            c.cal[0][2].vals = {14.5, 14.0, 15.0};
590            c.cal[0][3].n = 2;   // no rounds kept (a file of an older build): only the sum
591            c.cal[0][3].sum = 33.0;
592            std::string why;
593            check(strata::spec::write_cost_file(path, c, why), "median file: written");
594            CostFile r;
595            check(strata::spec::read_cost_file(path, c.key, r, why), "median file: read back");
596            check(r.cal[0][2].n == 3 && r.cal[0][2].nv == 3 && std::fabs((double) r.cal[0][2].vals[1] - 14.0) < 1e-6 && std::fabs(r.cal[0][2].sum - 43.5) < 1e-3,
597                  "median file: the kept rounds come back with their count and sum");
598            check(r.cal[0][3].n == 2 && r.cal[0][3].nv == 0 && std::fabs(r.cal[0][3].sum - 33.0) < 1e-3, "median file: a line without rounds keeps only n and sum (the mean decides)");
599            std::error_code ec;
600            fs::remove_all(dir, ec);
601        }
602        {   // fixture 1: the srv118 table as taken over (a real 2-row price of 20.08 ms, the sizes above it real or unreached): the outlier is lowered, 3-6 rows keep their prices
603            const double t12[12] = {7.928, 20.085, 9.577, 10.524, 12.136, 13.270, 19.223, 21.293, 23.659, 26.024, 28.390, 30.756};
604            Real real0{};
605            real0[0] = 63u;
606            Cal cal1{};
607            Rc rc1{};
608            const double rcv[7] = {0.0, 7.9276, 20.0847, 9.5771, 10.5245, 12.1355, 13.2695};
609            for (int t = 1; t <= 6; ++t) rc1[0][(size_t) t] = rcv[t];
610            DraftPolicy p(12);
611            p.set_fixed_costs(t12, 12, 0);
612            p.start_calibration(false, real0, cal1, rc1, 100);
613            bool mono = true;
614            for (int t = 2; t <= 12; ++t) mono = mono && p.cost_ms(t) >= p.cost_ms(t - 1) - 1e-12;
615            check(mono, "guard: the used table never costs less for more rows");
616            check(std::fabs(p.cost_ms(2) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(3) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(4) - 10.5245) < 1e-9 && std::fabs(p.cost_ms(6) - 13.2695) < 1e-9,
617                  "guard: the 20 ms 2-row outlier is lowered to the next real price, not raised into every larger size");
618            check(std::fabs(p.cost_ms(1) - 7.9276) < 1e-9, "guard: the 1-row price is untouched");
619        }
620        {   // fixture 2: the Q2_0 table at take-over: 4 rows an unreached live value above the real 5 rows
621            const double q[5] = {12.966, 14.482, 17.042, 21.796, 21.361};
622            Real real0{};
623            real0[0] = 23u;   // sizes 1, 2, 3, 5
624            Cal cal1{};
625            Rc rc1{};
626            rc1[0][1] = 12.9665;
627            rc1[0][2] = 14.4821;
628            rc1[0][3] = 17.0419;
629            rc1[0][5] = 21.3610;
630            DraftPolicy p(8);
631            p.set_fixed_costs(q, 5, 0);
632            p.start_calibration(false, real0, cal1, rc1, 100);
633            check(std::fabs(p.cost_ms(4) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(5) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(3) - 17.0419) < 1e-9,
634                  "guard: an unreached 4 rows above the real 5 rows is lowered to it");
635        }
636        {   // fixture 3: the IQ3_S table at take-over: 4 rows 28.31 (a live value) above the real 5 rows 25.00
637            const double q[5] = {14.734, 16.967, 20.096, 28.312, 25.005};
638            Real real0{};
639            real0[0] = 23u;
640            Cal cal1{};
641            Rc rc1{};
642            rc1[0][1] = 14.7341;
643            rc1[0][2] = 16.9669;
644            rc1[0][3] = 20.0959;
645            rc1[0][5] = 25.0046;
646            DraftPolicy p(8);
647            p.set_fixed_costs(q, 5, 0);
648            p.start_calibration(false, real0, cal1, rc1, 100);
649            check(std::fabs(p.cost_ms(4) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(5) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(2) - 16.9669) < 1e-9,
650                  "guard: IQ3_S 4 rows 28.31 is lowered to the real 5 rows 25.00");
651        }
652        {   // a real size above an unreached next size is not lowered by the guess: the guess is lifted to it
653            const double q[5] = {12.0, 14.0, 20.0, 15.0, 16.0};
654            Real real0{};
655            real0[0] = 4u;   // size 3 real at 20.0
656            Cal cal1{};
657            Rc rc1{};
658            rc1[0][3] = 20.0;
659            DraftPolicy p(8);
660            p.set_fixed_costs(q, 5, 0);
661            p.start_calibration(false, real0, cal1, rc1, 100);
662            check(std::fabs(p.cost_ms(3) - 20.0) < 1e-9 && p.cost_ms(4) >= 20.0 - 1e-9 && p.cost_ms(5) >= p.cost_ms(4) - 1e-12 && std::fabs(p.cost_ms(2) - 14.0) < 1e-9,
663                  "guard: a real price is kept against a guessed larger size, which is lifted to it");
664        }
665    }
666    {   // calibration against real rounds
667        using strata::spec::CalAcc;
668        using strata::spec::CostFile;
669        using strata::spec::CostLearner;
670        using strata::spec::read_cost_file;
671        using strata::spec::write_cost_file;
672        using Cal = std::array<std::array<CalAcc, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
673        using Rc = std::array<std::array<double, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
674        using Real = std::array<unsigned, CostLearner::kCtxBuckets>;
675        const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90};
676        const Cal cal0{};
677        const Rc rc0{};
678        DraftPolicy c(8), live(8);   // `live` has no table: a held table must decide exactly like it
679        c.set_fixed_costs(tab, 5, 0);
680        c.start_calibration(false, Real{}, cal0, rc0);
681        check(c.calibrating() && !c.calib_dirty() && c.table_held() && !c.fixed(), "calib: a table with uncalibrated sizes is held back: live costs, nothing collected yet");
682        bool same = true;
683        for (int i = 0; i < 15; ++i) {
684            const DraftPolicy::Pick pa = c.choose(i % 3 + 1, 5, 2), pb = live.choose(i % 3 + 1, 5, 2);
685            same = same && pa.lookup == pb.lookup && pa.t == pb.t && std::fabs(c.cost_ms(3) - live.cost_ms(3)) < 1e-12;
686            c.observe(false, 3, 2, 0, 16.70);
687            live.observe(false, 3, 2, 0, 16.70);
688        }
689        CostFile cf;
690        std::string rep;
691        check(same && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - live.cost_ms(4)) < 1e-12,
692              "calib: while held back, picks and costs equal those of a policy without a table (the live cost follows the rounds)");
693        check(c.calibrate(cf, rep) && rep.empty() && cf.cal[0][3].n == 15, "calib: 15 real rounds are kept, nothing replaced");
694        c.observe(false, 3, 2, 0, 16.70);
695        check(c.calibrate(cf, rep) && !rep.empty() && (cf.real[0] & 4u) && std::fabs(cf.real_cost[0][3] - 16.70) < 1e-9 && std::fabs(cf.tables[0][2] - 16.41) < 1e-9,
696              "calib: the 16th real round marks the size real; the file keeps the learned cost beside it");
697        check(c.table_held() && !c.fixed() && c.calibrating(), "calib: one real size is not enough: the table stays held back");
698        // the other four sizes get their 16 rounds: the table takes over at that request's end, at the real costs
699        const double rt[5] = {12.90, 14.60, 16.70, 19.90, 21.30};
700        for (int t = 1; t <= 5; ++t)
701            if (t != 3)
702                for (int i = 0; i < 16; ++i) c.observe(t == 4 || t == 5, t, 1, 0, rt[t - 1]);
703        check(c.calibrate(cf, rep) && c.fixed() && !c.table_held() && !c.calibrating(), "calib: with the last size calibrated the table is used");
704        check(std::fabs(c.cost_ms(1) - 12.90) < 1e-9 && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - 19.90) < 1e-9 && std::fabs(c.cost_ms(5) - 21.30) < 1e-9,
705              "calib: the real costs decide");
706        for (int i = 0; i < 40; ++i) c.observe(false, 3, 2, 0, 15.0);
707        check(!c.calib_dirty() && std::fabs(c.cost_ms(3) - 16.70) < 1e-9, "calib: a real size never changes again");
708        // a lookup size reached once per request: its rounds come across starts through the file
709        CostFile cd;
710        cd.key = "k";
711        Cal cal1 = cal0;
712        Real real1{};
713        Rc rc1 = rc0;
714        for (int start = 0; start < 16; ++start) {
715            DraftPolicy e(8);
716            e.set_fixed_costs(tab, 5, 0);
717            e.start_calibration(false, real1, cal1, rc1);
718            e.observe(true, 4, 2, 0, 18.9);
719            std::string r2;
720            check(e.calibrate(cd, r2), "calib: a start with one real round of a size writes the file");
721            cal1 = cd.cal;
722            real1 = cd.real;
723            rc1 = cd.real_cost;
724        }
725        check((cd.real[0] & 8u) != 0 && std::fabs(cd.real_cost[0][4] - 18.9) < 1e-9 && cd.cal[0][4].n == 0 && std::fabs(cd.tables[0][3] - 18.57) < 1e-9,
726              "calib: 16 starts of one round each calibrate the size");
727        DraftPolicy again(8);   // a start from that file: size 4 real, the others not: the table is held back
728        again.set_fixed_costs(tab, 5, 0);
729        again.start_calibration(false, real1, cal1, rc1);
730        check(again.table_held() && !again.fixed() && again.calibrating(), "calib: a restart with sizes still uncalibrated keeps the table held back");
731        {   // a file with every size real: the table is used from the first round, at the real costs
732            Real all{};
733            all[0] = 31u;
734            Rc rcall = rc0;
735            for (int t = 1; t <= 5; ++t) rcall[0][(size_t) t] = tab[t - 1] * 1.03;
736            DraftPolicy u(8);
737            u.set_fixed_costs(tab, 5, 0);
738            u.start_calibration(false, all, cal0, rcall);
739            check(u.fixed() && !u.table_held() && !u.calibrating() && std::fabs(u.cost_ms(4) - 18.57 * 1.03) < 1e-9 && std::fabs(u.cost_ms(1) - 12.68 * 1.03) < 1e-9,
740                  "calib: a start from a fully calibrated file uses the table at the real costs");
741        }
742        {   // sizes that real requests never reach: after kCalibReqs requests the table is used anyway, those sizes at a scaled learned cost
743            DraftPolicy bd(8);
744            bd.set_fixed_costs(tab, 5, 0);
745            bd.start_calibration(false, Real{}, cal0, rc0, 0);
746            CostFile cb;
747            std::string rb;
748            for (int i = 0; i < 16; ++i) bd.observe(false, 2, 1, 0, 14.60);
749            bd.calibrate(cb, rb);
750            for (int rq = 2; rq < DraftPolicy::kCalibReqs; ++rq) {
751                bd.observe(false, 3, 2, 0, 16.70);
752                bd.calibrate(cb, rb);
753            }
754            check(bd.table_held() && !bd.fixed() && cb.reqs == DraftPolicy::kCalibReqs - 1, "budget: held back before the last request of the budget");
755            bd.observe(false, 3, 2, 0, 16.70);
756            const bool wr = bd.calibrate(cb, rb);
757            const double rr = (14.60 / 14.30 + 16.70 / 16.41) / 2.0;
758            check(wr && bd.fixed() && !bd.table_held() && cb.reqs == DraftPolicy::kCalibReqs && bd.calibrating(), "budget: after kCalibReqs requests the table is used, calibration goes on");
759            check(std::fabs(bd.cost_ms(2) - 14.60) < 1e-9 && std::fabs(bd.cost_ms(3) - 16.70) < 1e-9 && std::fabs(bd.cost_ms(1) - 12.68) < 1e-9 &&
760                      std::fabs(bd.cost_ms(4) - 18.57 * rr) < 1e-6 && std::fabs(bd.cost_ms(5) - 20.90 * rr) < 1e-6,
761                  "budget: real sizes at their real cost, sizes not reached at learned x the mean ratio, size 1 at its learned cost");
762            DraftPolicy bs(8);   // a start from that file: used at once
763            bs.set_fixed_costs(tab, 5, 0);
764            bs.start_calibration(false, cb.real, cb.cal, cb.real_cost, cb.reqs);
765            check(bs.fixed() && !bs.table_held() && std::fabs(bs.cost_ms(4) - 18.57 * rr) < 1e-6, "budget: a start after the budget uses the table at once, same prices");
766            for (int i = 0; i < 16; ++i) bd.observe(true, 4, 2, 0, 19.90);   // a size the policy now chooses collects its own rounds while the table is in use
767            check(bd.calibrate(cb, rb) && bd.fixed() && (cb.real[0] & 8u) && std::fabs(bd.cost_ms(4) - 19.90) < 1e-9 && cb.reqs == DraftPolicy::kCalibReqs,
768                  "budget: in use, a size with its own kCalibN rounds becomes real");
769        }
770        {   // a machine with no table: built from the real rounds, no learning stretch, live costs decide until the take-over
771            CostFile c0;
772            c0.key = "k";
773            c0.fresh = true;
774            DraftPolicy p(8), lv(8);
775            p.start_passive(c0, 5);
776            check(p.passive() && p.table_held() && !p.fixed() && p.calibrating() && !p.learning(), "passive: held from the first request, no learning");
777            bool same = true;
778            for (int i = 0; i < 40; ++i) {
779                const DraftPolicy::Pick pa = p.choose(i % 3 + 1, 5, 2), pb = lv.choose(i % 3 + 1, 5, 2);
780                same = same && pa.lookup == pb.lookup && pa.t == pb.t && pa.pad == 0 && std::fabs(p.cost_ms(3) - lv.cost_ms(3)) < 1e-12;
781                p.set_busy_age(2.0);
782                p.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3));
783                lv.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3));
784            }
785            check(same && p.forced_rounds() == 0, "passive: picks and costs equal a policy without a table, no forced window");
786            CostFile cp;
787            std::string rp;
788            check(p.calibrate(cp, rp) && cp.fresh && cp.tables[0].empty() && cp.reqs == 1, "passive: the file has no table yet, one request counted");
789            // only the first seconds of a busy run are counted
790            DraftPolicy q(8);
791            q.start_passive(c0, 5);
792            q.set_busy_age(2.0);
793            for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6);
794            q.set_busy_age(50.0);
795            for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6);
796            CostFile cq;
797            q.calibrate(cq, rp);
798            check(cq.cal[0][2].n == 9 && cq.fresh, "passive: rounds late in a busy run are not counted; the first round of a size has no live cost to clamp to");
799            // the sums survive a restart: 9 + 7 more = 16 own rounds make the size real
800            cq.key = "k";
801            std::string wpath = "dp_passive_test.costs", wwhy;
802            check(write_cost_file(wpath, cq, wwhy), "passive: file written");
803            CostFile cr;
804            check(read_cost_file(wpath, "k", cr, wwhy) && cr.fresh && cr.tables[0].empty() && cr.cal[0][2].n == 9, "passive: a file with no table reads back");
805            std::remove(wpath.c_str());
806            DraftPolicy r(8);
807            r.start_passive(cr, 5);
808            r.set_busy_age(1.0);
809            for (int i = 0; i < 8; ++i) r.observe(false, 2, 1, 0, 14.6);
810            CostFile cs;
811            check(r.calibrate(cs, rp) && (cs.real[0] & 2u) && std::fabs(cs.real_cost[0][2] - 14.6) < 1e-9 && r.passive(), "passive: the size is real after 16 own rounds across a restart");
812            // take-over by every size real: the real costs, a table in the file
813            DraftPolicy a(8);
814            a.start_passive(c0, 5);
815            a.set_busy_age(1.0);
816            const double rt[5] = {12.9, 14.6, 16.7, 19.9, 21.3};
817            for (int t = 1; t <= 5; ++t)
818                for (int i = 0; i < 17; ++i) a.observe(t >= 4, t, 1, 0, rt[t - 1]);
819            CostFile ca;
820            check(a.calibrate(ca, rp) && a.fixed() && !a.passive() && !a.table_held() && !a.calibrating() && !ca.fresh && ca.tables[0].size() == 5, "passive: every size real: the table takes over, the file has a table");
821            check(std::fabs(a.cost_ms(1) - 12.9) < 1e-9 && std::fabs(a.cost_ms(4) - 19.9) < 1e-9 && std::fabs(ca.tables[0][2] - 16.7) < 1e-9, "passive: the real costs decide, the file keeps them as the table");
822            // take-over after kCalibReqs requests: a size never reached takes the live cost, a never measured one the policy's prior
823            DraftPolicy b(8), lb(8);
824            b.start_passive(c0, 5);
825            b.set_busy_age(1.0);
826            for (int i = 0; i < 17; ++i) {
827                b.observe(false, 2, 1, 0, 14.6);
828                lb.observe(false, 2, 1, 0, 14.6);
829            }
830            for (int i = 0; i < 6; ++i) {
831                b.observe(true, 4, 2, 0, 19.9);
832                lb.observe(true, 4, 2, 0, 19.9);
833            }
834            CostFile cb2;
835            for (int rq = 0; rq < DraftPolicy::kCalibReqs; ++rq) {
836                b.observe(false, 2, 1, 0, 14.6);
837                b.calibrate(cb2, rp);
838            }
839            check(b.fixed() && !b.passive() && cb2.reqs == DraftPolicy::kCalibReqs && cb2.tables[0].size() == 5, "passive: after kCalibReqs requests the table takes over");
840            check(std::fabs(cb2.tables[0][1] - 14.6) < 1e-9 && std::fabs(cb2.tables[0][3] - 19.9) < 1e-9 && std::fabs(cb2.tables[0][2] - lb.cost_ms(3)) < 0.1 && std::fabs(b.cost_ms(4) - 19.9) < 1e-9,
841                  "passive: real size 2 at its real cost, size 4 at its live cost, size 3 (never measured) at the policy's prior");
842            for (int i = 0; i < 17; ++i) b.observe(true, 4, 2, 0, 20.1);   // the unreached size keeps collecting
843            CostFile cb3 = cb2;
844            check(b.calibrate(cb3, rp) && (cb3.real[0] & 8u) && std::fabs(b.cost_ms(4) - 20.1) < 1e-9, "passive: after the take-over a size still collects and becomes real at 16 own rounds (its price the median: 5 rounds of 19.9, 11 of 20.1)");
845        }
846        // the file round trip: state, real, real cost, cal
847        CostFile w;
848        w.key = "k2";
849        w.tables[0].assign(tab, tab + 5);
850        w.state_effect = true;
851        w.reqs = 7;
852        w.real[0] = 6u;
853        w.real_cost[0][2] = 14.6;
854        w.real_cost[0][3] = 16.7;
855        w.cal[0][4] = CalAcc{7, 131.0};
856        const std::string path = "dp_calib_test.costs";
857        std::string why;
858        check(write_cost_file(path, w, why), "calib file: written");
859        CostFile r;
860        check(read_cost_file(path, "k2", r, why) && r.state_effect && r.reqs == 7 && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0 &&
861                  std::fabs(r.real_cost[0][2] - 14.6) < 1e-9 && std::fabs(r.real_cost[0][3] - 16.7) < 1e-9,
862              "calib file: state, real marks, real costs and collected rounds come back");
863        std::remove(path.c_str());
864        // a machine with a load-time effect counts only the first kFreshS seconds of a busy run
865        DraftPolicy f(8);
866        f.set_fixed_costs(tab, 5, 0);
867        f.start_calibration(true, Real{}, cal0, rc0);
868        f.set_busy_age(2.0);
869        for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 14.6);
870        f.set_busy_age(50.0);
871        for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 17.0);
872        CostFile cfz;
873        std::string rz;
874        f.calibrate(cfz, rz);
875        check(cfz.cal[0][2].n == 10, "calib: with a state effect only fresh rounds are counted");
876        // a disturbed stretch (a stalled machine) is dropped, not taken
877        DraftPolicy g(8);
878        g.set_fixed_costs(tab, 5, 0);
879        g.start_calibration(false, Real{}, cal0, rc0);
880        for (int i = 0; i < 16; ++i) g.observe(false, 2, 0, 0, 40.0);
881        CostFile cg;
882        std::string rg;
883        g.calibrate(cg, rg);
884        check(rg.empty() && g.table_held() && cg.cal[0][2].n == 0 && (cg.real[0] & 2u) == 0, "calib: rounds far above the learned cost are dropped");
885        // a size that real requests never reach, and a machine whose real sizes are all 1 row: nothing is scaled
886        DraftPolicy h(8);
887        h.set_fixed_costs(tab, 5, 0);
888        h.start_calibration(false, Real{}, cal0, rc0);
889        for (int i = 0; i < 16; ++i) h.observe(false, 1, 0, 0, 13.0);
890        CostFile ch;
891        std::string rh;
892        h.calibrate(ch, rh);
893        check((ch.real[0] & 1u) != 0 && h.table_held() && !h.fixed(), "calib: one real size does not bring the table into use");
894    }
895    {
896        // STRATA_DRAFT_COSTS_LEARN=1 keeps its one-start promise (f-dc-learn-fix): (a) a request of the learning stretch starts a new busy run; (b) the table it writes is used by the next start at once.
897        using strata::spec::CostFile;
898        using strata::spec::CostLearner;
899        namespace fs = std::filesystem;
900        static_assert(CostLearner::starts_busy_run(false, 0.0, false) && !CostLearner::starts_busy_run(true, 0.01, false) && CostLearner::starts_busy_run(true, 0.5, false),
901                      "no learning stretch: the first request and a pause of kIdleS start a busy run, a request a few ms later does not");
902        check(CostLearner::starts_busy_run(true, 0.0, true) && CostLearner::starts_busy_run(true, 0.01, true), "learn (a): a request of the learning stretch starts a new busy run, however close");
903        check(!CostLearner::starts_busy_run(true, 0.2, false) && CostLearner::starts_busy_run(true, CostLearner::kIdleS, false), "learn (a): without the learning stretch the rule is the 0.5 s pause as before");
904        // 40 requests back to back of 200 rounds each (3 window sizes, 40 / 44 / 48 ms, 5 % slower after 6 s of load): one long busy run keeps 150 fresh rounds, a busy run per request 6,000
905        const auto sim = [](bool per_request_run) {
906            CostLearner L;
907            double clock = 0.0;
908            for (int q = 0; q < 40; ++q) {
909                double req_start = per_request_run ? clock : 0.0;
910                for (int i = 0; i < 200; ++i) {
911                    const int t = 1 + i % 3;
912                    const double age = clock - req_start;
913                    const double ms = (40.0 + 4.0 * (t - 1)) * (age > CostLearner::kFreshS ? 1.05 : 1.0) * (1.0 + 0.004 * ((i % 5) - 2));
914                    L.add(0, t, ms, age);
915                    clock += ms / 1000.0;
916                }
917            }
918            return L.check(1000, 20);
919        };
920        check(!sim(false).ready, "learn (a): back to back, one busy run: fresh rounds stay at the first seconds, the stretch never finishes (the batch 15 behaviour)");
921        check(sim(true).ready && !sim(true).disturbed, "learn (a): back to back, a busy run per request: the stretch finishes");
922        // (b) the written table is marked real: read back, it is used at once and nothing rewrites it
923        CostFile c;
924        c.key = "card A|engine 1|model m";
925        c.tables[0] = {12.3456, 14.2, 16.2004, 18.5};
926        c.state_effect = true;
927        strata::spec::mark_learned_real(c);
928        check(c.real[0] == 0xFu && c.real[1] == 0u && c.real_cost[0][1] == 12.346 && c.tables[0][0] == 12.346 && c.tables[0][2] == 16.2 && c.real_cost[0][3] == 16.2,
929              "learn (b): every size of the stretch's table is marked real, its cost rounded to the file's 3 decimals");
930        const fs::path dir = fs::temp_directory_path() / ("strata-dpt-learn-" + std::to_string((unsigned long long) (uintptr_t) &c));
931        const std::string path = (dir / "t.costs").string();
932        std::string why;
933        CostFile r;
934        check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.real[0] == 0xFu && r.real_cost[0][4] == 18.5 && r.tables[0][1] == 14.2,
935              "learn (b): the marks and the costs survive the file");
936        DraftPolicy used(6);
937        used.set_fixed_costs(r.tables[0].data(), (int) r.tables[0].size(), 0);
938        used.start_calibration(r.state_effect, r.real, r.cal, r.real_cost, r.reqs);
939        check(used.fixed() && !used.table_held() && !used.calibrating(), "learn (b): the next start uses the table at once (no holding, no calibration)");
940        for (int i = 0; i < 30; ++i) used.observe(false, 2, 1, 0, 15.5);
941        CostFile again = r;
942        std::string rep;
943        check(!used.calibrate(again, rep) && rep.empty(), "learn (b): rounds of the next start never ask for the file to be rewritten");
944        // the same table WITHOUT the marks (what the stretch wrote before) is held back, as the passive path still does
945        CostFile u;
946        u.key = c.key;
947        u.tables[0] = {12.3456, 14.2, 16.2004, 18.5};
948        DraftPolicy held(6);
949        held.set_fixed_costs(u.tables[0].data(), 4, 0);
950        held.start_calibration(u.state_effect, u.real, u.cal, u.real_cost, u.reqs);
951        check(held.table_held() && held.calibrating() && !held.fixed(), "learn (b): a table without marks is still held back (the passive path is unchanged)");
952        std::error_code ec;
953        fs::remove_all(dir, ec);
954    }
955    std::printf(g_fail ? "FAIL\n" : "PASS\n");
956    return g_fail ? 1 : 0;
957}