turbospark-runtime 0.3.0

The raw-completion prefill+decode loop: wires a LogitProducer, the tokenizer, and the selection sampler into one token generation loop.
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
//! The hard-fail / warn split, which is the whole contract of
//! `--speculative`. Pure, so it needs no install: the two inputs are "does
//! this install carry a head" and "is this run deterministic", and every
//! interesting combination is reachable as a pair of booleans.
//!
//! Moved here with the policy itself, from `crates/cli`. They were the CLI's
//! only coverage of these decisions and the server was about to need the same
//! decisions; leaving the tests behind would have left the second caller
//! untested by construction.

use super::{
    resolve_drafter, resolve_speculation, DrafterChoice, Speculation, SpeculationPlan,
    SpeculativeDrafter,
};
use crate::families::qwen::{
    install_has_dflash, install_has_mtp_head, DFLASH_SERVING_BLOCK, MOE_SPECULATION_BLOCKER_MARKER,
    VISION_SPECULATION_BLOCKER_MARKER,
};
use crate::speculative::DEFAULT_SPECULATION_BLOCK;

/// `auto` takes its block from the drafter's OWN default.
///
/// What this pins is the MAPPING. It does NOT cover the CALL SITE, which
/// needs a runner -- and the call site is exactly where this went wrong for
/// one build: `open_session` passed the unresolved `Auto` and the CLI printed
/// "dflash2 (block drafter), block 2", a shape neither drafter was measured
/// at. Only a real-model run catches that one.
#[test]
fn auto_takes_each_drafters_own_block() {
    let block_of = |d| match resolve_speculation(Speculation::Auto, d, None, true) {
        Ok(SpeculationPlan::Enabled { block }) => block,
        other => panic!("expected an enabled plan, got {other:?}"),
    };
    assert_eq!(block_of(SpeculativeDrafter::Mtp), DEFAULT_SPECULATION_BLOCK);
    assert_eq!(block_of(SpeculativeDrafter::Dflash), DFLASH_SERVING_BLOCK);
    // THE TWO SERVING DEFAULTS AGREE AT 2, independently measured: the MTP
    // head's optimum (`docs/MTP.md`) and DFlash2's three-workload sweep
    // (`DFLASH_SERVING_BLOCK`) landed on the same number, because what decides
    // both is this engine's rollback cost rather than either drafter. So this
    // test pins the MAPPING and can NO LONGER see an unresolved drafter by its
    // block alone; `resolve_drafter` below covers that, and only a real-model
    // run covers the call site. Asserted as an equality so the day they
    // diverge is the day the discriminating check can come back, rather than a
    // day nobody notices.
    assert_eq!(
        DEFAULT_SPECULATION_BLOCK, DFLASH_SERVING_BLOCK,
        "the serving defaults diverged; restore a discriminating assertion here"
    );
}

/// An EXPLICIT drafter is passed through untouched, because it is a promise
/// the caller made to themselves: `--speculative-drafter mtp` on a DFlash2
/// install must reach the MTP blocker and hard-fail there, never be silently
/// rerouted to the drafter that happens to be present. It also carries no
/// note -- a note is `auto` explaining a choice it made, and here it made
/// none.
#[test]
fn an_explicit_drafter_is_never_re_resolved() {
    let missing = std::path::Path::new("/nonexistent/turbospark/install");
    for named in [SpeculativeDrafter::Mtp, SpeculativeDrafter::Dflash] {
        let choice = resolve_drafter(named, missing);
        assert_eq!(choice.drafter, named);
        assert_eq!(choice.note, None, "an explicit ask needs no explanation");
    }
}

/// **NOT RE-RESOLVING THE DRAFTER IS NOT THE SAME AS NOT LOOKING AT THE
/// INSTALL, and conflating the two is what left `--speculative-drafter mtp
/// --speculative 2` reporting the wrong obstacle.** The drafter is passed
/// through untouched -- that is the test above -- while
/// `install_has_mtp_head` is recorded either way, because `draft_policies`
/// needs it to avoid asking the open for a head that is not there.
///
/// The fixture is dflash-only, so it is headless, so `Some(false)` is the
/// answer and `None` (the old behaviour on this path, which read the index
/// for nobody) is distinguishable from it.
#[test]
fn an_explicit_drafter_still_records_whether_the_install_has_a_head() {
    let dir = std::env::temp_dir().join(format!(
        "turbospark-explicit-head-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    turbospark_repack::build_synthetic_qwen_gdn_dense_install_with_dflash(
        &dir,
        512,
        4,
        "drafter-toy-explicit",
        4,
    )
    .expect("synthetic dflash install");

    for named in [SpeculativeDrafter::Mtp, SpeculativeDrafter::Dflash] {
        let choice = resolve_drafter(named, &dir);
        assert_eq!(choice.drafter, named, "the ask is still honoured");
        assert_eq!(
            choice.install_has_mtp_head,
            Some(false),
            "an explicit ask must still read the index"
        );
        // BOTH flags, and the fixture answers them differently, which is what
        // makes the pair worth asserting: a single `index.is_some()` masquerading
        // as either would pass one of these and fail the other.
        assert_eq!(
            choice.install_has_dflash,
            Some(true),
            "the dflash-only fixture carries one"
        );
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// An install whose index cannot be read resolves to `Mtp` rather than
/// failing: this function picks a drafter, and `open` is entitled to be the
/// one that refuses a broken install. No note either, so the message such a
/// caller sees is the engine's own.
#[test]
fn an_unreadable_index_resolves_to_the_pre_existing_default() {
    let choice = resolve_drafter(
        SpeculativeDrafter::Auto,
        std::path::Path::new("/nonexistent/turbospark/install"),
    );
    assert_eq!(choice.drafter, SpeculativeDrafter::Mtp);
    assert_eq!(choice.note, None);
    // UNKNOWN, not "no head". `draft_policies` keys BOTH headless arms on
    // `Some(false)` precisely so this case keeps asking the open for the
    // drafter and failing there, with the engine's message about the broken
    // install rather than a guess about its contents.
    assert_eq!(choice.install_has_mtp_head, None);
    assert_eq!(choice.install_has_dflash, None);
}

/// **DFLASH2 IS DETECTED AND DELIBERATELY NOT ENABLED**, which is the
/// asymmetry this whole function exists for. Through the shipped loop it
/// reads 0.90x throughput on prose against 1.33-1.47x on code and math, and
/// +17.4% J/token in its own power arm, so `auto` must not
/// switch it on; but silence would be the bug the feature was built to end,
/// so the note names the flag that would.
///
/// The fixture is a real synthetic install carrying `dflash.*` and no `mtp.*`,
/// because the whole decision is a read of the resident index and a hand-made
/// directory would not exercise it.
#[test]
fn auto_detects_dflash_but_leaves_it_off() {
    let dir = std::env::temp_dir().join(format!(
        "turbospark-drafter-choice-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    // Small and shallow on purpose: this reads the resident INDEX and never
    // runs a forward pass, so the fixture only has to carry the tensor NAMES.
    turbospark_repack::build_synthetic_qwen_gdn_dense_install_with_dflash(
        &dir,
        512,
        4,
        "drafter-toy",
        4,
    )
    .expect("synthetic dflash install");

    let index = model_io::load_resident_index(&dir.join("model_weights.bin"))
        .expect("the fixture's resident index");
    // ASSERT THE FIXTURE DISCRIMINATES before believing the case: an install
    // carrying BOTH drafters, or neither, resolves to `Mtp` with no note by
    // other branches, so a fixture that was not dflash-only-shaped would pass
    // this test against any of them.
    assert!(
        install_has_dflash(&index) && !install_has_mtp_head(&index),
        "the fixture must be dflash-only or it cannot see this branch"
    );

    let choice = resolve_drafter(SpeculativeDrafter::Auto, &dir);
    assert_eq!(
        choice.drafter,
        SpeculativeDrafter::Mtp,
        "auto must not enable dflash: it is 0.96x on prose"
    );
    assert_eq!(choice.install_has_mtp_head, Some(false));
    let note = choice.note.expect("a detected drafter must be reported");
    // BOTH spellings, one per kind of front end. `crates/ffi` has no
    // command line, so a note naming only the flag is an instruction a GUI
    // caller cannot act on.
    assert!(
        note.contains("--speculative-drafter dflash"),
        "the note must name the flag that runs it, got: {note}"
    );
    assert!(
        note.contains("speculativeDrafter"),
        "the note must name the C ABI option too, got: {note}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

/// An install carrying BOTH drafters takes the MTP head SILENTLY, and that
/// silence is the assertion.
///
/// This is the only input on which "no MTP head AND a DFlash2 one" and the
/// weaker "a DFlash2 one" differ, so it is the only fixture that can see the
/// first clause -- dropping it leaves every dflash-only case green (verified:
/// that mutation survived until this test existed). The consequence of
/// dropping it is not cosmetic either: the note OUTRANKS the engine's
/// blocker, so a spurious note would report speculation off on an install
/// whose MTP head works, silently giving up 1.44-1.66x.
#[test]
fn an_install_with_both_drafters_keeps_the_mtp_head_and_says_nothing() {
    let dir = std::env::temp_dir().join(format!(
        "turbospark-drafter-both-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    turbospark_repack::build_synthetic_qwen_gdn_dense_install_with_both_drafters(
        &dir,
        512,
        4,
        "drafter-toy-both",
        4,
    )
    .expect("synthetic install with both drafters");

    let index = model_io::load_resident_index(&dir.join("model_weights.bin"))
        .expect("the fixture's resident index");
    assert!(
        install_has_dflash(&index) && install_has_mtp_head(&index),
        "the fixture must carry BOTH or it cannot see this branch"
    );

    let choice = resolve_drafter(SpeculativeDrafter::Auto, &dir);
    assert_eq!(choice.drafter, SpeculativeDrafter::Mtp);
    assert_eq!(
        choice.note, None,
        "the MTP head is being used, so there is nothing to explain"
    );
    // The one fixture here that reads `Some(true)`, which is what keeps the
    // headless arm from being satisfiable by every install at once.
    assert_eq!(choice.install_has_mtp_head, Some(true));

    let _ = std::fs::remove_dir_all(&dir);
}

// Verbatim shapes of what `RealForwardRunner::speculation_blocker` returns.
// This module does not construct these -- it forwards whatever the engine
// says -- so what these fixtures pin is the ROUTING, not the text.
const NO_HEAD: &str = "this install carries no multi-token-prediction head \
                       (mtp.fc.weight is not in the resident index); the mlx conversion \
                       drops mtp.*, so stream an install that adds the official \
                       checkpoint's last shard (docs/MTP.md)";
const NOT_BATCHED_DTYPE: &str = "the batched verify covers INT4-affine (4) and the \
    1-bit (15) / 2-bit (16) affine pair, and this install's ...q_proj.weight is dtype 5";
// The MoE one is a `fn` rather than a `const` so it can INTERPOLATE
// `MOE_SPECULATION_BLOCKER_MARKER` instead of repeating its text. That is the
// whole reason the marker exists: the previous shared substring was
// `"dense-only"`, spelled out here and in two other files, and it went stale
// in all three at once when `5640c3f` gave the routed pair a batched kernel.
fn moe() -> String {
    format!(
        "{MOE_SPECULATION_BLOCKER_MARKER}: this install routes to 128 experts, and no \
         published MoE conversion of this architecture ships a drafter this port can \
         ingest (every mlx conversion drops mtp.*). The batched routed verify itself \
         runs, so this is a checkpoint gap and not a missing kernel"
    )
}

// The vision one, interpolating its marker for `moe()`'s reason: the marker
// is the shared prefix the guards match on, and a hand-copied sentence here
// is how a message and its guards drift apart.
fn vision() -> String {
    format!(
        "{VISION_SPECULATION_BLOCKER_MARKER}: this runner has a vision tower, and the \
         batched verify embeds every row from the token table and rotates at the raw \
         position, so a speculative round past an image would attend and rotate by \
         the wrong values; run text-only or disable speculation (docs/VISION.md)"
    )
}

/// A vision-active engine blocker routes exactly like every other blocker:
/// hard fail under a named block, warn-and-disable under `auto`. The string
/// is what the real blockers now produce, so this pins the ROUTING of the
/// vision reason without an install that combines a tower and a drafter --
/// which is exactly why the blocker arm exists rather than a vision-aware
/// verify pass no artifact could test.
#[test]
fn a_vision_blocker_fails_hard_under_a_named_block_and_warns_under_auto() {
    let err = resolve_speculation(
        Speculation::Block(2),
        SpeculativeDrafter::Mtp,
        Some(vision()),
        true,
    )
    .expect_err("a named block on a vision-active runner must fail");
    assert!(
        err.contains(VISION_SPECULATION_BLOCKER_MARKER),
        "got: {err}"
    );

    let plan = resolve_speculation(
        Speculation::Auto,
        SpeculativeDrafter::Mtp,
        Some(vision()),
        true,
    )
    .expect("auto degrades to disabled rather than failing");
    match plan {
        SpeculationPlan::Disabled {
            reason: Some(reason),
        } => assert!(
            reason.contains(VISION_SPECULATION_BLOCKER_MARKER),
            "got: {reason}"
        ),
        other => panic!("expected disabled-with-reason, got {other:?}"),
    }
}

#[test]
fn a_named_block_fails_hard_when_it_cannot_be_served() {
    // No head. The caller named a block, so this is an ERROR: they are
    // measuring or have chosen deliberately, and a run that quietly did not
    // speculate would be recorded as the speculative number.
    let err = resolve_speculation(
        Speculation::Block(2),
        SpeculativeDrafter::Mtp,
        Some(NO_HEAD.to_string()),
        true,
    )
    .expect_err("a named block on a headless install must fail");
    assert!(err.contains("no multi-token-prediction head"), "got: {err}");

    // Sampled under the BLOCK drafter. Still refused rather than downgraded:
    // DFlash2's selection has no distribution to ratio against, so exact
    // rejection sampling is undefined for it (the step drafter serves any
    // temperature now, so the refusal is keyed on the drafter kind).
    let err = resolve_speculation(
        Speculation::Block(2),
        SpeculativeDrafter::Dflash,
        None,
        false,
    )
    .expect_err("a named block on a sampled block-drafter run must fail");
    assert!(err.contains("not a distribution"), "got: {err}");

    // Sampled under the STEP drafter is SERVED now (rejection sampling), so
    // this arm must not refuse -- asserting the flip explicitly, because a
    // refusal that forgot which drafter it was about would silently send
    // every sampled request back to the sequential loop.
    let plan = resolve_speculation(Speculation::Block(2), SpeculativeDrafter::Mtp, None, false)
        .expect("the step drafter serves sampled runs");
    assert_eq!(plan, SpeculationPlan::Enabled { block: 2 });
}

#[test]
fn auto_warns_and_continues_where_a_named_block_fails() {
    let cases = [
        (Some(NO_HEAD.to_string()), true, SpeculativeDrafter::Mtp),
        (
            Some(NOT_BATCHED_DTYPE.to_string()),
            true,
            SpeculativeDrafter::Mtp,
        ),
        (Some(moe()), false, SpeculativeDrafter::Mtp),
        // Sampled + BLOCK drafter: auto declines with the same reason a
        // named block fails on. The sampled + MTP case moved OUT of this
        // table when rejection sampling landed -- it is Enabled now.
        (None, false, SpeculativeDrafter::Dflash),
    ];
    for (blocker, deterministic, drafter) in cases {
        let plan = resolve_speculation(Speculation::Auto, drafter, blocker, deterministic)
            .expect("auto never fails; it declines");
        match plan {
            SpeculationPlan::Disabled { reason: Some(_) } => {}
            other => panic!("auto must warn and continue, got {other:?}"),
        }
    }
}

#[test]
fn auto_speculates_when_the_install_and_the_settings_allow_it() {
    let plan = resolve_speculation(Speculation::Auto, SpeculativeDrafter::Mtp, None, true)
        .expect("serviceable");
    assert_eq!(
        plan,
        SpeculationPlan::Enabled {
            block: DEFAULT_SPECULATION_BLOCK
        }
    );
}

#[test]
fn off_is_silent_even_where_speculation_would_have_worked() {
    // No warning: the caller asked for off and got off. A warning here would
    // train people to ignore the one that matters.
    //
    // THE UNSERVICEABLE CASES ARE THE DISCRIMINATING ONES. With a head present
    // and a deterministic run there is no reason to leak in the first place,
    // so a fixture built only from that combination passes against an `Off`
    // arm that forwards whatever reason it was handed.
    for (blocker, deterministic) in [
        (None, true),
        (Some(NO_HEAD.to_string()), true),
        (None, false),
        (Some(NOT_BATCHED_DTYPE.to_string()), false),
    ] {
        let plan = resolve_speculation(
            Speculation::Off,
            SpeculativeDrafter::Mtp,
            blocker.clone(),
            deterministic,
        )
        .expect("off never fails");
        assert_eq!(
            plan,
            SpeculationPlan::Disabled { reason: None },
            "off must stay silent at blocker={blocker:?} deterministic={deterministic}"
        );
    }
}

#[test]
fn a_named_block_is_honoured_rather_than_replaced_by_the_default() {
    let plan = resolve_speculation(Speculation::Block(7), SpeculativeDrafter::Mtp, None, true)
        .expect("serviceable");
    assert_eq!(plan, SpeculationPlan::Enabled { block: 7 });
}

/// **THE `note` ARM PINS `MtpDraftPolicy::Off`, AND THAT IS NOT COSMETIC.**
/// A DFlash2-only install under `auto` must OPEN successfully so
/// `resolve_speculation` can refuse with the note that names the flag;
/// without this arm the open itself fails, telling someone holding a working
/// drafter to go and download a different one.
///
/// This is the one decision in this module that had no test at all while it
/// lived in the CLI -- `draft_policies` was an inline `match` inside
/// `open_session`, reachable only with a 14 GB install in hand.
#[test]
fn a_noted_dflash_install_opens_with_both_drafters_off() {
    use crate::families::qwen::{DflashDraftPolicy, MtpDraftPolicy};

    let noted = DrafterChoice {
        drafter: SpeculativeDrafter::Mtp,
        // A dflash-only install: no head, which is ALSO what the headless arm
        // keys on. The two conditions agree here and part company below,
        // which is why the plain contrast case sets `Some(true)`.
        install_has_mtp_head: Some(false),
        install_has_dflash: Some(true),
        note: Some("carries a DFlash2 drafter".to_string()),
    };
    for asked in [Speculation::Auto, Speculation::Block(2)] {
        let policies = super::draft_policies(&noted, asked);
        assert_eq!(
            policies.mtp,
            MtpDraftPolicy::Off,
            "a noted install must not ask the open for a head it has not got"
        );
    }

    // The contrast that makes the arm above discriminating: the SAME drafter
    // with no note does ask for the head, so a mutation deleting the note
    // clause changes this pair rather than nothing.
    //
    // It has to carry a HEAD (`Some(true)`) to be that contrast now. With
    // `Some(false)` the headless arm would produce `Off` too and the pair
    // would pass with the note clause deleted -- the fixture-must-discriminate
    // rule (AGENTS.md Gotchas 48, 50, 51) applying to a second condition on
    // the same match.
    let plain = DrafterChoice {
        drafter: SpeculativeDrafter::Mtp,
        install_has_mtp_head: Some(true),
        install_has_dflash: Some(false),
        note: None,
    };
    assert_eq!(
        super::draft_policies(&plain, Speculation::Block(2)).mtp,
        MtpDraftPolicy::Fixed(2)
    );
    assert_eq!(
        super::draft_policies(&plain, Speculation::Auto).mtp,
        MtpDraftPolicy::Auto
    );

    // And the DFlash2 arm pins the MTP head off in every case, so an install
    // carrying both never opens both drafters' state.
    let dflash = DrafterChoice {
        drafter: SpeculativeDrafter::Dflash,
        install_has_mtp_head: Some(false),
        // `Some(true)`, or the DFlash2 headless arm turns this into `Off` and
        // the case stops testing what it is named for. A drafter asked for by
        // name on an install that HAS it is the enabled path.
        install_has_dflash: Some(true),
        note: None,
    };
    let policies = super::draft_policies(&dflash, Speculation::Block(4));
    assert_eq!(policies.mtp, MtpDraftPolicy::Off);
    assert_eq!(policies.dflash, DflashDraftPolicy::Fixed(4));
}

/// **A NAMED BLOCK ON A HEADLESS INSTALL MUST NOT ASK THE OPEN FOR A HEAD,
/// or the open fails first and names the wrong obstacle.**
///
/// Measured 2026-08-21 on the real `ornith35b` install: `--speculative 2`
/// reached `MtpDraftPolicy::Fixed`, failed at open, and reported "carries no
/// multi-token-prediction head ... stream an install that adds the official
/// checkpoint's last shard" -- sending a caller after a 4.4 GB shard that
/// cannot help: that install routes to 256 experts, and no published MoE
/// conversion of this architecture carries an ingestible drafter, so no shard
/// of any checkpoint helps. `auto` got the same install right on the same run,
/// which is what localised it: `auto` reaches `resolve_speculation` and a
/// named block did not.
///
/// This is the `note` arm's argument on a wider input, so the two conditions
/// are checked apart. The note covers a DFlash2-only install; this covers
/// every OTHER headless one, which is where nothing covered it.
#[test]
fn a_named_block_on_a_headless_install_lets_the_open_succeed() {
    use crate::families::qwen::MtpDraftPolicy;

    let headless = DrafterChoice {
        drafter: SpeculativeDrafter::Mtp,
        install_has_mtp_head: Some(false),
        install_has_dflash: Some(false),
        note: None,
    };
    assert_eq!(
        super::draft_policies(&headless, Speculation::Block(2)).mtp,
        MtpDraftPolicy::Off,
        "a block on a known-headless install must not be asked of the open"
    );
    // `Auto` is UNCHANGED and must stay so: `MtpDraftPolicy::Auto` already
    // builds a head iff one is present, so it never had this failure and
    // routing it through `Off` would lose nothing but say less.
    assert_eq!(
        super::draft_policies(&headless, Speculation::Auto).mtp,
        MtpDraftPolicy::Auto
    );

    // **AN UNREADABLE INDEX IS `None` AND STILL ASKS.** "There is no head"
    // and "nobody could look" license different things: a broken install has
    // to keep failing at open with the engine's own message rather than being
    // explained by a guess this module is not entitled to make. Folding
    // `None` into `Some(false)` would pass every assertion above and quietly
    // change that.
    let unknown = DrafterChoice {
        drafter: SpeculativeDrafter::Mtp,
        install_has_mtp_head: None,
        install_has_dflash: None,
        note: None,
    };
    assert_eq!(
        super::draft_policies(&unknown, Speculation::Block(2)).mtp,
        MtpDraftPolicy::Fixed(2)
    );
}

/// **THE SAME ARM ON THE OTHER DRAFTER, missing until 2026-08-22.**
///
/// The MTP path got its headless arm on 2026-08-21 and the DFlash2 path did
/// not, so `--speculative-drafter dflash --speculative 2` kept the exact
/// failure that fix was written to end. Measured on the real `ornith35b`
/// install: it failed at OPEN with `DflashState::build`'s "this install
/// carries none (dflash.fc.weight is not in the resident index); stream it
/// beside the trunk", which on a MoE checkpoint is advice no artifact can
/// satisfy -- the published DFlash2 drafter targets the DENSE half of this
/// architecture. `auto` reported the right thing on the same install in the
/// same run, which is what localised it, exactly as it had for MTP.
///
/// Pinned as a TRIPLE rather than a single assertion, because two of the three
/// are what stop the arm from being over-broad: `Auto` must not route through
/// `Off` (it already builds a drafter iff one is present), and an install that
/// HAS the drafter must still reach `Fixed`.
#[test]
fn a_named_block_on_a_drafterless_install_lets_the_open_succeed_for_dflash_too() {
    use crate::families::qwen::DflashDraftPolicy;

    let choice = |install_has_dflash| DrafterChoice {
        drafter: SpeculativeDrafter::Dflash,
        install_has_mtp_head: Some(false),
        install_has_dflash,
        note: None,
    };

    assert_eq!(
        super::draft_policies(&choice(Some(false)), Speculation::Block(2)).dflash,
        DflashDraftPolicy::Off,
        "a block on a known-drafterless install must not be asked of the open"
    );
    assert_eq!(
        super::draft_policies(&choice(Some(false)), Speculation::Auto).dflash,
        DflashDraftPolicy::Auto,
        "`Auto` never had this failure and must be left alone"
    );
    assert_eq!(
        super::draft_policies(&choice(Some(true)), Speculation::Block(2)).dflash,
        DflashDraftPolicy::Fixed(2),
        "an install that carries the drafter must still enable it"
    );
    // `None` is an unreadable index and keeps asking, for the MTP arm's
    // reason: a broken install has to fail at open with the engine's own
    // message rather than be explained by a guess.
    assert_eq!(
        super::draft_policies(&choice(None), Speculation::Block(2)).dflash,
        DflashDraftPolicy::Fixed(2)
    );
}

/// The other half of the same fix: the routing above is only worth anything
/// if what it reaches names the ARCHITECTURAL obstacle ahead of the missing
/// head, which `speculation_blocker` has always done and nothing reached.
///
/// Pinned as a pair, because the MoE case is the one that was wrong and the
/// dense case is the one that must not change: on a dense headless install
/// the head really is the obstacle and the shard really would fix it, so that
/// message is correct and stays word for word.
#[test]
fn a_headless_moe_install_is_refused_for_its_architecture_not_its_head() {
    let moe = resolve_speculation(
        Speculation::Block(2),
        SpeculativeDrafter::Mtp,
        Some(moe()),
        true,
    )
    .expect_err("a named block on a MoE install must fail");
    assert!(
        moe.contains(MOE_SPECULATION_BLOCKER_MARKER) && moe.contains("128 experts"),
        "a MoE install must be refused for its architecture, got: {moe}"
    );
    // NOT because the head is irrelevant -- an absent drafter IS the whole
    // obstacle now -- but because naming THIS install's missing head reads as
    // an instruction to go and fetch one, and on a MoE checkpoint of this
    // architecture there is none to fetch.
    assert!(
        !moe.contains("multi-token-prediction head"),
        "no checkpoint helps here, so the head must not be named: {moe}"
    );

    // The contrast: dense and headless, where naming the head is right.
    let dense = resolve_speculation(
        Speculation::Block(2),
        SpeculativeDrafter::Mtp,
        Some(NO_HEAD.to_string()),
        true,
    )
    .expect_err("a named block on a headless install must fail");
    assert!(
        dense.contains("multi-token-prediction head"),
        "got: {dense}"
    );
    // The fixture keeps the POINTER, and this line pins the fixture rather
    // than the engine -- read the header above `NO_HEAD`: this module forwards
    // whatever string it is handed and never calls `speculation_blocker`, so
    // nothing here can see that function's text change. Measured, not assumed:
    // deleting the pointer from the real arm leaves this whole module green.
    // The guard that CAN see it is
    // `a_dense_int4_install_without_a_head_is_told_which_artifact_would_fix_it`
    // in `tests/real_forward_qwen35_mtp.rs`, which opens a dense INT4 headless
    // install and asks the engine. What this line is worth is keeping the
    // fixture an honest copy, so a reader of the routing cases is not shown a
    // sentence the engine stopped producing.
    assert!(
        dense.contains("last shard"),
        "the NO_HEAD fixture must stay a verbatim copy of the engine's arm: {dense}"
    );
}

#[test]
fn a_block_outside_allowed_range_is_refused() {
    for invalid in [0, 16, 100] {
        let err = resolve_speculation(
            Speculation::Block(invalid),
            SpeculativeDrafter::Mtp,
            None,
            true,
        )
        .expect_err("block outside allowed range must be refused");
        assert!(
            err.contains("outside allowed range"),
            "expected 'outside allowed range' in refusal, got: {err}"
        );
    }
}