hf2q 0.1.30

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! Server policy, isolation state, and telemetry for exact Qwen speculation.
//!
//! SlotAware request state, proposer cost gates, and KV transactions live in
//! `engine_qwen35`; this module owns admission policy and process telemetry.
//! Sampled requests still fail closed to ordinary target decode because the
//! server path has not qualified rejection sampling for every API constraint.

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

/// Server policy selected with `HF2Q_QWEN_SPECULATION`.
///
/// An explicit `off`/`auto` always wins. When the variable is unset the
/// default depends on the worker ([`default_server_policy`]): `off` on a
/// SlotAware worker that selected joint decode and has at least
/// [`UNSET_OFF_MIN_SLOTS`] slots (dense and MoE), `auto` everywhere else
/// (ADR-044, updated 2026-08-21: every admission path fails closed, so the
/// worst case is ordinary decode plus telemetry).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QwenSpeculationPolicy {
    Off,
    Auto,
}

/// Narrowest SlotAware width at which an unset policy resolves to `off` for
/// joint-decode workers. Dense (Qwen3.8): ADR-063 D1 (#364) measured `auto`
/// vs `off` own-output makespan 1.020 at four slots (95% CI 1.0095-1.0308,
/// 8 ABBA pairs; `adr063-preflight-20261023/d1-speculation-ext-v2`). MoE
/// (Qwen3.6): operator ruling 2026-11-06 for repeatable four-agent serving,
/// supported by #719 (joint vs serial makespan 0.800 with speculation at its
/// default in both arms, i.e. per-slot serial K3 at N4 cost about 25% against
/// mostly-joint M1 rows). D1's Qwen3.6 result is Inconclusive and was
/// measured with joint decode off, so it is not the evidence for MoE.
pub const UNSET_OFF_MIN_SLOTS: usize = 4;

/// Unset default for a worker serving `max_slots` slots: `off` for a worker
/// whose joint decode is selected at [`UNSET_OFF_MIN_SLOTS`] or more slots,
/// `auto` otherwise (SerialFifo, narrower workers, workers whose joint
/// decode is off or unavailable).
pub fn default_server_policy(max_slots: usize, joint_decode: bool) -> QwenSpeculationPolicy {
    if joint_decode && max_slots >= UNSET_OFF_MIN_SLOTS {
        QwenSpeculationPolicy::Off
    } else {
        QwenSpeculationPolicy::Auto
    }
}

const JOINT_WIDE_DEFAULT_OFF_REASON: &str = "unset: joint-decode workers with max_slots >= 4 \
     default off (dense: ADR-063 D1 makespan 1.020; MoE: repeatable four-agent serving, #719); \
     set HF2Q_QWEN_SPECULATION=auto to opt in";
const DEFAULT_AUTO_REASON: &str = "unset: auto default (ADR-044); joint-decode workers with \
     max_slots >= 4 default off";
const EXPLICIT_REASON: &str = "explicit HF2Q_QWEN_SPECULATION";

/// How a speculating SlotAware lane is routed and gated, selected with
/// `HF2Q_QWEN_SPECULATION_ROUTE`.
///
/// - `Repeatable` (default): each tick's route is decided from the lane's
///   own state only. A lane whose tick speculates never joins a joint step,
///   and the proposer cost gates read a fixed cost model
///   ([`MTP_ROUND_COST_UNITS`], [`HISTORY_ROUND_COST_UNITS`]) instead of
///   wall time, so identical requests take identical routes in every run.
/// - `Adaptive`: the phase-1 behaviour. A speculation-capable lane joins any
///   joint group as an M1 row, and the gates compare measured wall time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QwenSpeculationRoute {
    Repeatable,
    Adaptive,
}

impl QwenSpeculationRoute {
    pub fn parse(value: Option<&str>) -> Result<Self, String> {
        match value.map(str::trim).filter(|value| !value.is_empty()) {
            None => Ok(Self::Repeatable),
            Some(value) if value.eq_ignore_ascii_case("repeatable") => Ok(Self::Repeatable),
            Some(value) if value.eq_ignore_ascii_case("adaptive") => Ok(Self::Adaptive),
            Some(value) => Err(format!(
                "HF2Q_QWEN_SPECULATION_ROUTE must be repeatable or adaptive (got {value:?})"
            )),
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::Repeatable => "repeatable",
            Self::Adaptive => "adaptive",
        }
    }

    fn from_environment() -> Self {
        Self::parse(std::env::var("HF2Q_QWEN_SPECULATION_ROUTE").ok().as_deref()).unwrap_or_else(
            |message| {
                tracing::warn!(%message, fallback = "repeatable", "invalid Qwen speculation route");
                Self::Repeatable
            },
        )
    }
}

/// Modelled cost of one MTP K3 round (draft + four-row verify + catch-up +
/// commit) in ordinary target decisions. From the cost controllers' own
/// counters in the ADR-063 D2 H1 receipts (Qwen3.8 27B, binary 38485a23;
/// `adr063-preflight-20261023/d2-v1/extra-runs/{A/01,A/10,N/01,N/14}-*-H1-*
/// .metrics/last.prom`): 102 rounds, 8.077 s of round time = 79.2 ms per
/// round; 21.355 s of equivalent ordinary time over about 339 decisions
/// (accepted + rounds) = 63.0 ms per ordinary decision; 79.2 / 63.0 = 1.26.
/// No Qwen3.6 receipt carries these counters; Qwen3.6 uses the same value.
pub const MTP_ROUND_COST_UNITS: f64 = 1.26;

/// Modelled cost of one history-lookup verify round, one constant for every
/// row count (aggregate counters cannot split it by rows). Same receipts:
/// 17 rounds, 1.640 s = 96.5 ms per round; 3.171 s over about 49 decisions
/// = 64.7 ms per ordinary decision; 96.5 / 64.7 = 1.49.
///
/// Caveat for both constants: those runs were four-slot `adaptive` with joint
/// decode, so the ordinary-decision time comes from joint rows (prepare to
/// the lane's own finish). Speculation now runs by default only at one to
/// three slots, where a serial ordinary decision is cheaper. ADR-044's
/// one-slot profile suggests about 2.1 for MTP (68–75 ms per round against
/// about 34 ms per token) [INFERENCE], so these constants may undercharge a
/// round there. This is a speed effect only; the route stays request-local.
pub const HISTORY_ROUND_COST_UNITS: f64 = 1.49;

/// Development-only overrides of the modelled round costs, used by the
/// repeatability gate to force a cost-disabled proposer. Invalid or
/// non-positive values warn and keep the default.
fn modelled_round_cost(env: &str, default: f64) -> f64 {
    match std::env::var(env) {
        Ok(raw) => match raw.trim().parse::<f64>() {
            Ok(value) if value.is_finite() && value > 0.0 => value,
            _ => {
                tracing::warn!(variable = env, value = %raw, fallback = default, "invalid Qwen speculation cost override");
                default
            }
        },
        Err(_) => default,
    }
}

impl QwenSpeculationPolicy {
    pub fn parse(value: Option<&str>) -> Result<Self, String> {
        match value.map(str::trim).filter(|value| !value.is_empty()) {
            None | Some("off") | Some("0") => Ok(Self::Off),
            Some("auto") | Some("1") => Ok(Self::Auto),
            Some(value) => Err(format!(
                "HF2Q_QWEN_SPECULATION must be off or auto (got {value:?})"
            )),
        }
    }

    pub const fn label(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Auto => "auto",
        }
    }

    /// The operator's explicit choice: `None` when the variable is absent;
    /// a present value is parsed strictly and an invalid value warns and
    /// fails closed to an explicit `off` (it never inherits the default).
    /// Kept pure (the caller passes the env read) so it is unit-testable
    /// without mutating process state.
    pub fn requested(value: Option<&str>) -> Option<Self> {
        let value = value?;
        Some(Self::parse(Some(value)).unwrap_or_else(|message| {
            tracing::warn!(%message, "disabling Qwen speculation");
            Self::Off
        }))
    }

    pub fn requested_from_environment() -> Option<Self> {
        Self::requested(std::env::var("HF2Q_QWEN_SPECULATION").ok().as_deref())
    }

    /// Server-side resolution for the qwen35 engine: an explicit request
    /// wins; an unset one takes [`default_server_policy`] for a worker of
    /// `max_slots` slots, with or without joint decode selected. Pure.
    pub fn resolve_server_policy(
        requested: Option<Self>,
        max_slots: usize,
        joint_decode: bool,
    ) -> Self {
        requested.unwrap_or_else(|| default_server_policy(max_slots, joint_decode))
    }

    fn resolution_reason(
        requested: Option<Self>,
        max_slots: usize,
        joint_decode: bool,
    ) -> &'static str {
        match (requested, default_server_policy(max_slots, joint_decode)) {
            (Some(_), _) => EXPLICIT_REASON,
            (None, Self::Off) => JOINT_WIDE_DEFAULT_OFF_REASON,
            (None, Self::Auto) => DEFAULT_AUTO_REASON,
        }
    }
}

/// Why a Qwen request used ordinary target decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QwenSpeculationDecision {
    Disabled,
    UnsupportedSemantics,
    PromptCacheHit,
    Unprofitable,
    RuntimeUnavailable,
    Eligible,
}

impl QwenSpeculationDecision {
    pub const fn metric_reason(self) -> &'static str {
        match self {
            Self::Disabled => "disabled",
            Self::UnsupportedSemantics => "unsupported_semantics",
            Self::PromptCacheHit => "prompt_cache_hit",
            Self::Unprofitable => "unprofitable",
            Self::RuntimeUnavailable => "runtime_unavailable",
            Self::Eligible => "eligible",
        }
    }
}

/// Classify a request without retaining conversation-local state. SlotAware
/// scheduling uses this at admission; the per-slot decoder owns all
/// request-local proposer and KV state and never shares a serial controller.
pub fn classify_request(
    policy: QwenSpeculationPolicy,
    exact_semantics: bool,
    prompt_cache_hit: bool,
) -> QwenSpeculationDecision {
    if policy == QwenSpeculationPolicy::Off {
        QwenSpeculationDecision::Disabled
    } else if !exact_semantics {
        QwenSpeculationDecision::UnsupportedSemantics
    } else if prompt_cache_hit {
        QwenSpeculationDecision::PromptCacheHit
    } else {
        QwenSpeculationDecision::Eligible
    }
}

/// SlotAware admission decision: [`classify_request`] plus the bound-graft
/// fallback (ADR-059). The MTP cache is a separate slot arena that never
/// receives the graft, so its drafts and any retained speculative boundary
/// describe the ungrafted context. Speculation is an optimization, never a
/// semantic path: an otherwise eligible grafted request is served by ordinary
/// grafted decode and reported as `RuntimeUnavailable`.
pub fn classify_slot_request(
    policy: QwenSpeculationPolicy,
    exact_semantics: bool,
    prompt_cache_hit: bool,
    graft_bound: bool,
) -> QwenSpeculationDecision {
    match classify_request(policy, exact_semantics, prompt_cache_hit) {
        QwenSpeculationDecision::Eligible if graft_bound => {
            QwenSpeculationDecision::RuntimeUnavailable
        }
        decision => decision,
    }
}

/// Whether a bounded SlotAware prefill chunk also runs the MTP prompt
/// catch-up that seeds K3 drafting. It needs `auto`, exact request semantics,
/// a text-only chunk, MTP weights with an MTP cache arena, and no bound KV
/// graft (same reason as [`classify_slot_request`]).
pub fn prefill_mtp_catchup_allowed(
    policy: QwenSpeculationPolicy,
    exact_semantics: bool,
    text_only: bool,
    mtp_runtime: bool,
    graft_bound: bool,
) -> bool {
    policy == QwenSpeculationPolicy::Auto
        && exact_semantics
        && text_only
        && mtp_runtime
        && !graft_bound
}

/// Fixed round costs the repeatable route's proposer gates read, in ordinary
/// target decisions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QwenSpeculationCostModel {
    pub mtp_round: f64,
    pub history_round: f64,
}

/// One-worker controller. It holds no KV tensors and only carries the
/// current conversation identity plus the previous speculative result.
#[derive(Debug, Clone)]
pub struct QwenSpeculationController {
    /// Operator choice (`None` = `HF2Q_QWEN_SPECULATION` unset).
    requested: Option<QwenSpeculationPolicy>,
    /// Policy every admission/prefill/decode consumer reads.
    policy: QwenSpeculationPolicy,
    /// Routing and cost-gate mode for speculating lanes.
    route: QwenSpeculationRoute,
    /// Round costs of the repeatable gates.
    cost_model: QwenSpeculationCostModel,
    /// Joint MTP verify (`HF2Q_QWEN_JOINT_MTP`): speculating lanes verify
    /// their MTP drafts as windows of the joint step, and no request runs a
    /// serial K3 round or history lookup.
    joint_mtp: bool,
    conversation_prompt: Option<Vec<u32>>,
}

impl QwenSpeculationController {
    /// Controller with an explicit policy and the default (repeatable)
    /// route; worker resolution keeps both.
    pub fn new(policy: QwenSpeculationPolicy) -> Self {
        Self {
            requested: Some(policy),
            policy,
            route: QwenSpeculationRoute::Repeatable,
            cost_model: QwenSpeculationCostModel {
                mtp_round: MTP_ROUND_COST_UNITS,
                history_round: HISTORY_ROUND_COST_UNITS,
            },
            joint_mtp: false,
            conversation_prompt: None,
        }
    }

    /// Reads `HF2Q_QWEN_SPECULATION`, `HF2Q_QWEN_SPECULATION_ROUTE` and the
    /// development-only cost overrides once at engine load. Until a SlotAware
    /// worker calls [`Self::resolve_for_worker`], the policy is the one-slot
    /// (SerialFifo) resolution, which is `auto` when unset.
    pub fn from_environment() -> Self {
        let requested = QwenSpeculationPolicy::requested_from_environment();
        Self {
            requested,
            policy: requested.unwrap_or(QwenSpeculationPolicy::Auto),
            route: QwenSpeculationRoute::from_environment(),
            cost_model: QwenSpeculationCostModel {
                mtp_round: modelled_round_cost("HF2Q_QWEN_SPEC_COST_MTP", MTP_ROUND_COST_UNITS),
                history_round: modelled_round_cost(
                    "HF2Q_QWEN_SPEC_COST_HISTORY",
                    HISTORY_ROUND_COST_UNITS,
                ),
            },
            joint_mtp: false,
            conversation_prompt: None,
        }
    }

    /// Resolve the unset default for a SlotAware worker of `max_slots`
    /// slots once at worker start and log the decision. `joint_decode` is
    /// whether the worker selected Qwen joint decode; `moe` is logged only.
    pub fn resolve_for_worker(&mut self, max_slots: usize, moe: bool, joint_decode: bool) {
        let requested = self.requested;
        self.policy =
            QwenSpeculationPolicy::resolve_server_policy(requested, max_slots, joint_decode);
        let reason = QwenSpeculationPolicy::resolution_reason(requested, max_slots, joint_decode);
        tracing::info!(
            target: "hf2q::serve::api::engine_qwen35::progress",
            requested = requested.map_or("unset", QwenSpeculationPolicy::label),
            policy = self.policy.label(),
            route = self.route.label(),
            mtp_round_cost = self.cost_model.mtp_round,
            history_round_cost = self.cost_model.history_round,
            max_slots,
            moe,
            joint_decode,
            reason,
            "Qwen speculation worker policy"
        );
    }

    /// Select the joint MTP verify route for a joint-decode worker after
    /// [`Self::resolve_for_worker`]. An unset policy resolves to `auto` (the
    /// route needs MTP prompt catch-up and per-request MTP state); an
    /// explicit `off` keeps speculation and the route off. Returns whether
    /// the route is active.
    pub fn select_joint_mtp(&mut self, requested: bool) -> bool {
        if requested && self.requested.is_none() {
            self.policy = QwenSpeculationPolicy::Auto;
        }
        self.joint_mtp = requested && self.policy == QwenSpeculationPolicy::Auto;
        tracing::info!(
            target: "hf2q::serve::api::engine_qwen35::progress",
            requested,
            policy = self.policy.label(),
            joint_mtp = self.joint_mtp,
            "Qwen joint MTP verify route"
        );
        self.joint_mtp
    }

    /// Whether the joint MTP verify route is active.
    pub fn joint_mtp(&self) -> bool {
        self.joint_mtp
    }

    pub fn policy(&self) -> QwenSpeculationPolicy {
        self.policy
    }

    pub fn route(&self) -> QwenSpeculationRoute {
        self.route
    }

    /// The fixed round costs when the route is repeatable; `None` keeps the
    /// measured (wall-time) gates of the adaptive route.
    pub fn cost_model(&self) -> Option<QwenSpeculationCostModel> {
        (self.route == QwenSpeculationRoute::Repeatable).then_some(self.cost_model)
    }

    /// Decide the transaction path. A non-extension resets the state before
    /// inspection, which prevents one chat's negative acceptance outcome from
    /// disabling (or enabling) another chat.
    pub fn decide(
        &mut self,
        prompt: &[u32],
        greedy_exact: bool,
        _has_mtp: bool,
        prompt_cache_hit: bool,
    ) -> QwenSpeculationDecision {
        let same_conversation = self
            .conversation_prompt
            .as_ref()
            .is_some_and(|prior| prompt.starts_with(prior));
        if !same_conversation {
            self.conversation_prompt = None;
            TELEMETRY
                .conversation_resets
                .fetch_add(1, Ordering::Relaxed);
        }
        self.conversation_prompt = Some(prompt.to_vec());

        classify_request(self.policy, greedy_exact, prompt_cache_hit)
    }
}

/// Process telemetry, emitted by the server `/metrics` endpoint and tracing.
#[derive(Debug, Default)]
pub struct QwenSpeculationTelemetry {
    pub drafted_tokens: AtomicU64,
    pub accepted_tokens: AtomicU64,
    pub rejected_tokens: AtomicU64,
    pub target_forwards: AtomicU64,
    pub cached_token_reuse: AtomicU64,
    pub fallback_requests: AtomicU64,
    pub fallback_disabled: AtomicU64,
    pub fallback_unsupported_semantics: AtomicU64,
    // Retained as a zero-valued compatibility metric while `auto` can use
    // history lookup without MTP weights.
    pub fallback_no_mtp_weights: AtomicU64,
    pub fallback_prompt_cache_hit: AtomicU64,
    pub fallback_unprofitable: AtomicU64,
    pub fallback_slot_aware_unavailable: AtomicU64,
    pub fallback_runtime_unavailable: AtomicU64,
    pub conversation_resets: AtomicU64,
    pub history_lookup_proposals: AtomicU64,
    pub mtp_proposals: AtomicU64,
    pub history_lookup_no_match: AtomicU64,
    pub history_lookup_drafted_tokens: AtomicU64,
    pub history_lookup_accepted_tokens: AtomicU64,
    pub history_lookup_rejected_tokens: AtomicU64,
    pub history_lookup_target_forwards: AtomicU64,
    pub mtp_drafted_tokens: AtomicU64,
    pub mtp_accepted_tokens: AtomicU64,
    pub mtp_rejected_tokens: AtomicU64,
    pub mtp_target_forwards: AtomicU64,
    pub history_lookup_cost_disabled: AtomicU64,
    pub mtp_cost_disabled: AtomicU64,
    pub history_lookup_round_nanos: AtomicU64,
    pub mtp_round_nanos: AtomicU64,
    pub history_lookup_equivalent_ordinary_nanos: AtomicU64,
    pub mtp_equivalent_ordinary_nanos: AtomicU64,
}

pub static TELEMETRY: QwenSpeculationTelemetry = QwenSpeculationTelemetry {
    drafted_tokens: AtomicU64::new(0),
    accepted_tokens: AtomicU64::new(0),
    rejected_tokens: AtomicU64::new(0),
    target_forwards: AtomicU64::new(0),
    cached_token_reuse: AtomicU64::new(0),
    fallback_requests: AtomicU64::new(0),
    fallback_disabled: AtomicU64::new(0),
    fallback_unsupported_semantics: AtomicU64::new(0),
    fallback_no_mtp_weights: AtomicU64::new(0),
    fallback_prompt_cache_hit: AtomicU64::new(0),
    fallback_unprofitable: AtomicU64::new(0),
    fallback_slot_aware_unavailable: AtomicU64::new(0),
    fallback_runtime_unavailable: AtomicU64::new(0),
    conversation_resets: AtomicU64::new(0),
    history_lookup_proposals: AtomicU64::new(0),
    mtp_proposals: AtomicU64::new(0),
    history_lookup_no_match: AtomicU64::new(0),
    history_lookup_drafted_tokens: AtomicU64::new(0),
    history_lookup_accepted_tokens: AtomicU64::new(0),
    history_lookup_rejected_tokens: AtomicU64::new(0),
    history_lookup_target_forwards: AtomicU64::new(0),
    mtp_drafted_tokens: AtomicU64::new(0),
    mtp_accepted_tokens: AtomicU64::new(0),
    mtp_rejected_tokens: AtomicU64::new(0),
    mtp_target_forwards: AtomicU64::new(0),
    history_lookup_cost_disabled: AtomicU64::new(0),
    mtp_cost_disabled: AtomicU64::new(0),
    history_lookup_round_nanos: AtomicU64::new(0),
    mtp_round_nanos: AtomicU64::new(0),
    history_lookup_equivalent_ordinary_nanos: AtomicU64::new(0),
    mtp_equivalent_ordinary_nanos: AtomicU64::new(0),
};

pub fn record_fallback(decision: QwenSpeculationDecision) {
    TELEMETRY.fallback_requests.fetch_add(1, Ordering::Relaxed);
    let counter = match decision {
        QwenSpeculationDecision::Disabled => &TELEMETRY.fallback_disabled,
        QwenSpeculationDecision::UnsupportedSemantics => &TELEMETRY.fallback_unsupported_semantics,
        QwenSpeculationDecision::PromptCacheHit => &TELEMETRY.fallback_prompt_cache_hit,
        QwenSpeculationDecision::Unprofitable => &TELEMETRY.fallback_unprofitable,
        QwenSpeculationDecision::RuntimeUnavailable => &TELEMETRY.fallback_runtime_unavailable,
        QwenSpeculationDecision::Eligible => return,
    };
    counter.fetch_add(1, Ordering::Relaxed);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QwenSpeculationProposer {
    HistoryLookup,
    Mtp,
}

pub fn record_history_lookup_no_match() {
    TELEMETRY
        .history_lookup_no_match
        .fetch_add(1, Ordering::Relaxed);
}

pub fn record_outcome(
    drafted: usize,
    accepted: usize,
    rejected: usize,
    target_forwards: usize,
    cached_tokens: usize,
) {
    TELEMETRY
        .drafted_tokens
        .fetch_add(drafted as u64, Ordering::Relaxed);
    TELEMETRY
        .accepted_tokens
        .fetch_add(accepted as u64, Ordering::Relaxed);
    TELEMETRY
        .rejected_tokens
        .fetch_add(rejected as u64, Ordering::Relaxed);
    TELEMETRY
        .target_forwards
        .fetch_add(target_forwards as u64, Ordering::Relaxed);
    TELEMETRY
        .cached_token_reuse
        .fetch_add(cached_tokens as u64, Ordering::Relaxed);
}

pub fn record_proposer_outcome(
    proposer: QwenSpeculationProposer,
    drafted: usize,
    accepted: usize,
    rejected: usize,
    target_forwards: usize,
    cached_tokens: usize,
) {
    match proposer {
        QwenSpeculationProposer::HistoryLookup => {
            TELEMETRY
                .history_lookup_proposals
                .fetch_add(1, Ordering::Relaxed);
            TELEMETRY
                .history_lookup_drafted_tokens
                .fetch_add(drafted as u64, Ordering::Relaxed);
            TELEMETRY
                .history_lookup_accepted_tokens
                .fetch_add(accepted as u64, Ordering::Relaxed);
            TELEMETRY
                .history_lookup_rejected_tokens
                .fetch_add(rejected as u64, Ordering::Relaxed);
            TELEMETRY
                .history_lookup_target_forwards
                .fetch_add(target_forwards as u64, Ordering::Relaxed);
        }
        QwenSpeculationProposer::Mtp => {
            TELEMETRY.mtp_proposals.fetch_add(1, Ordering::Relaxed);
            TELEMETRY
                .mtp_drafted_tokens
                .fetch_add(drafted as u64, Ordering::Relaxed);
            TELEMETRY
                .mtp_accepted_tokens
                .fetch_add(accepted as u64, Ordering::Relaxed);
            TELEMETRY
                .mtp_rejected_tokens
                .fetch_add(rejected as u64, Ordering::Relaxed);
            TELEMETRY
                .mtp_target_forwards
                .fetch_add(target_forwards as u64, Ordering::Relaxed);
        }
    };
    record_outcome(drafted, accepted, rejected, target_forwards, cached_tokens);
}

pub fn record_cost_disabled(proposer: QwenSpeculationProposer) {
    let counter = match proposer {
        QwenSpeculationProposer::HistoryLookup => &TELEMETRY.history_lookup_cost_disabled,
        QwenSpeculationProposer::Mtp => &TELEMETRY.mtp_cost_disabled,
    };
    counter.fetch_add(1, Ordering::Relaxed);
}

pub fn record_proposer_timing(
    proposer: QwenSpeculationProposer,
    elapsed: Duration,
    equivalent_ordinary: Duration,
) {
    let elapsed = elapsed.as_nanos().min(u128::from(u64::MAX)) as u64;
    let equivalent = equivalent_ordinary.as_nanos().min(u128::from(u64::MAX)) as u64;
    let (round, baseline) = match proposer {
        QwenSpeculationProposer::HistoryLookup => (
            &TELEMETRY.history_lookup_round_nanos,
            &TELEMETRY.history_lookup_equivalent_ordinary_nanos,
        ),
        QwenSpeculationProposer::Mtp => (
            &TELEMETRY.mtp_round_nanos,
            &TELEMETRY.mtp_equivalent_ordinary_nanos,
        ),
    };
    round.fetch_add(elapsed, Ordering::Relaxed);
    baseline.fetch_add(equivalent, Ordering::Relaxed);
}

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

    static TELEMETRY_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn policy_parser_is_explicit_and_fail_closed() {
        assert_eq!(
            QwenSpeculationPolicy::parse(None),
            Ok(QwenSpeculationPolicy::Off)
        );
        assert_eq!(
            QwenSpeculationPolicy::parse(Some("auto")),
            Ok(QwenSpeculationPolicy::Auto)
        );
        assert!(QwenSpeculationPolicy::parse(Some("always")).is_err());
    }

    #[test]
    fn requested_policy_is_explicit_or_unset_and_fails_closed() {
        assert_eq!(QwenSpeculationPolicy::requested(None), None);
        for (raw, expected) in [
            ("auto", QwenSpeculationPolicy::Auto),
            ("1", QwenSpeculationPolicy::Auto),
            ("off", QwenSpeculationPolicy::Off),
            ("0", QwenSpeculationPolicy::Off),
            ("", QwenSpeculationPolicy::Off),
            // Invalid values fail closed rather than inheriting the default.
            ("always", QwenSpeculationPolicy::Off),
        ] {
            assert_eq!(
                QwenSpeculationPolicy::requested(Some(raw)),
                Some(expected),
                "HF2Q_QWEN_SPECULATION={raw:?}"
            );
        }
    }

    /// Unset resolves to `off` for every joint-decode worker with at least
    /// four slots (dense: ADR-063 D1; MoE: operator ruling 2026-11-06);
    /// explicit values always win.
    #[test]
    fn server_policy_resolution_table() {
        use QwenSpeculationPolicy::{Auto, Off};
        let invalid = QwenSpeculationPolicy::requested(Some("always"));
        // (requested, max_slots, joint_decode, expected)
        let table = [
            (None, 4, true, Off),
            (None, 8, true, Off),
            (None, 3, true, Auto),
            (None, 2, true, Auto),
            (None, 1, true, Auto),
            (None, 4, false, Auto),
            (None, 8, false, Auto),
            (None, 1, false, Auto),
            (Some(Auto), 4, true, Auto),
            (Some(Auto), 8, true, Auto),
            (Some(Off), 1, false, Off),
            (Some(Off), 3, true, Off),
            (Some(Off), 4, true, Off),
            (invalid, 1, false, Off),
            (invalid, 4, true, Off),
        ];
        for (requested, max_slots, joint, expected) in table {
            assert_eq!(
                QwenSpeculationPolicy::resolve_server_policy(requested, max_slots, joint),
                expected,
                "requested={requested:?} max_slots={max_slots} joint={joint}"
            );
        }
    }

    #[test]
    fn worker_resolution_replaces_only_the_unset_default() {
        let unset = || QwenSpeculationController {
            requested: None,
            ..QwenSpeculationController::new(QwenSpeculationPolicy::Auto)
        };
        for moe in [false, true] {
            let mut joint_four = unset();
            joint_four.resolve_for_worker(4, moe, true);
            assert_eq!(joint_four.policy(), QwenSpeculationPolicy::Off, "moe={moe}");
            let mut serial_four = unset();
            serial_four.resolve_for_worker(4, moe, false);
            assert_eq!(
                serial_four.policy(),
                QwenSpeculationPolicy::Auto,
                "moe={moe}"
            );
            let mut joint_three = unset();
            joint_three.resolve_for_worker(3, moe, true);
            assert_eq!(
                joint_three.policy(),
                QwenSpeculationPolicy::Auto,
                "moe={moe}"
            );
        }

        let mut explicit_auto = QwenSpeculationController::new(QwenSpeculationPolicy::Auto);
        explicit_auto.resolve_for_worker(4, true, true);
        assert_eq!(explicit_auto.policy(), QwenSpeculationPolicy::Auto);
        let mut explicit_off = QwenSpeculationController::new(QwenSpeculationPolicy::Off);
        explicit_off.resolve_for_worker(1, true, false);
        assert_eq!(explicit_off.policy(), QwenSpeculationPolicy::Off);
    }

    /// The joint MTP route turns an unset four-slot `off` into `auto`; an
    /// explicit `off` wins and keeps the route off.
    #[test]
    fn joint_mtp_selection_overrides_only_the_unset_default() {
        let mut unset = QwenSpeculationController {
            requested: None,
            ..QwenSpeculationController::new(QwenSpeculationPolicy::Auto)
        };
        unset.resolve_for_worker(4, false, true);
        assert_eq!(unset.policy(), QwenSpeculationPolicy::Off);
        assert!(unset.select_joint_mtp(true));
        assert_eq!(unset.policy(), QwenSpeculationPolicy::Auto);
        assert!(unset.joint_mtp());

        let mut explicit_off = QwenSpeculationController::new(QwenSpeculationPolicy::Off);
        explicit_off.resolve_for_worker(4, false, true);
        assert!(!explicit_off.select_joint_mtp(true));
        assert_eq!(explicit_off.policy(), QwenSpeculationPolicy::Off);

        let mut not_requested = QwenSpeculationController {
            requested: None,
            ..QwenSpeculationController::new(QwenSpeculationPolicy::Auto)
        };
        not_requested.resolve_for_worker(4, false, true);
        assert!(!not_requested.select_joint_mtp(false));
        assert_eq!(not_requested.policy(), QwenSpeculationPolicy::Off);
    }

    #[test]
    fn speculation_route_defaults_repeatable_and_parses_both_arms() {
        use QwenSpeculationRoute::{Adaptive, Repeatable};
        assert_eq!(QwenSpeculationRoute::parse(None), Ok(Repeatable));
        assert_eq!(QwenSpeculationRoute::parse(Some(" ")), Ok(Repeatable));
        assert_eq!(
            QwenSpeculationRoute::parse(Some("Repeatable")),
            Ok(Repeatable)
        );
        assert_eq!(QwenSpeculationRoute::parse(Some("adaptive")), Ok(Adaptive));
        assert!(QwenSpeculationRoute::parse(Some("measured")).is_err());
        let repeatable = QwenSpeculationController::new(QwenSpeculationPolicy::Auto);
        assert_eq!(
            repeatable.cost_model(),
            Some(QwenSpeculationCostModel {
                mtp_round: MTP_ROUND_COST_UNITS,
                history_round: HISTORY_ROUND_COST_UNITS,
            })
        );
        let adaptive = QwenSpeculationController {
            route: Adaptive,
            ..QwenSpeculationController::new(QwenSpeculationPolicy::Auto)
        };
        assert_eq!(adaptive.cost_model(), None);
    }

    #[test]
    fn sampled_requests_and_prompt_cache_hits_fall_back() {
        let mut controller = QwenSpeculationController::new(QwenSpeculationPolicy::Auto);
        assert_eq!(
            controller.decide(&[1, 2], false, true, false),
            QwenSpeculationDecision::UnsupportedSemantics
        );
        assert_eq!(
            controller.decide(&[1, 2, 3], true, true, true),
            QwenSpeculationDecision::PromptCacheHit
        );
    }

    #[test]
    fn eligibility_does_not_use_acceptance_as_a_profitability_proxy() {
        let mut controller = QwenSpeculationController::new(QwenSpeculationPolicy::Auto);
        assert_eq!(
            controller.decide(&[7, 8], true, true, false),
            QwenSpeculationDecision::Eligible
        );
        assert_eq!(
            controller.decide(&[7, 8, 9], true, true, false),
            QwenSpeculationDecision::Eligible
        );
    }

    /// ADR-063 D1 graft-restore fallback: a bound graft never reaches MTP,
    /// whether the request would start cold or resume a retained speculative
    /// boundary, while every non-eligible reason keeps its own label.
    #[test]
    fn bound_graft_keeps_eligible_requests_off_mtp_at_admission_and_prefill() {
        let auto = QwenSpeculationPolicy::Auto;
        assert_eq!(
            classify_slot_request(auto, true, false, false),
            QwenSpeculationDecision::Eligible
        );
        assert_eq!(
            classify_slot_request(auto, true, false, true),
            QwenSpeculationDecision::RuntimeUnavailable,
            "a warm grafted slot with reusable speculative metadata must not resume MTP"
        );
        for graft_bound in [false, true] {
            assert_eq!(
                classify_slot_request(QwenSpeculationPolicy::Off, true, false, graft_bound),
                QwenSpeculationDecision::Disabled
            );
            assert_eq!(
                classify_slot_request(auto, false, false, graft_bound),
                QwenSpeculationDecision::UnsupportedSemantics
            );
            assert_eq!(
                classify_slot_request(auto, true, true, graft_bound),
                QwenSpeculationDecision::PromptCacheHit
            );
        }

        assert!(prefill_mtp_catchup_allowed(auto, true, true, true, false));
        assert!(
            !prefill_mtp_catchup_allowed(auto, true, true, true, true),
            "a grafted prefill must not seed the ungrafted MTP arena"
        );
        assert!(!prefill_mtp_catchup_allowed(
            QwenSpeculationPolicy::Off,
            true,
            true,
            true,
            false
        ));
        assert!(!prefill_mtp_catchup_allowed(auto, false, true, true, false));
        assert!(!prefill_mtp_catchup_allowed(auto, true, false, true, false));
        assert!(!prefill_mtp_catchup_allowed(auto, true, true, false, false));
    }

    #[test]
    fn telemetry_records_every_transaction_counter() {
        let _guard = TELEMETRY_TEST_LOCK.lock().expect("telemetry test lock");
        let before = (
            TELEMETRY.drafted_tokens.load(Ordering::Relaxed),
            TELEMETRY.accepted_tokens.load(Ordering::Relaxed),
            TELEMETRY.rejected_tokens.load(Ordering::Relaxed),
            TELEMETRY.target_forwards.load(Ordering::Relaxed),
            TELEMETRY.cached_token_reuse.load(Ordering::Relaxed),
        );
        record_outcome(8, 5, 3, 4, 12);
        assert_eq!(
            TELEMETRY.drafted_tokens.load(Ordering::Relaxed),
            before.0 + 8
        );
        assert_eq!(
            TELEMETRY.accepted_tokens.load(Ordering::Relaxed),
            before.1 + 5
        );
        assert_eq!(
            TELEMETRY.rejected_tokens.load(Ordering::Relaxed),
            before.2 + 3
        );
        assert_eq!(
            TELEMETRY.target_forwards.load(Ordering::Relaxed),
            before.3 + 4
        );
        assert_eq!(
            TELEMETRY.cached_token_reuse.load(Ordering::Relaxed),
            before.4 + 12
        );
    }

    #[test]
    fn telemetry_keeps_proposer_and_cost_gate_counters_separate() {
        let _guard = TELEMETRY_TEST_LOCK.lock().expect("telemetry test lock");
        let before = (
            TELEMETRY.history_lookup_proposals.load(Ordering::Relaxed),
            TELEMETRY
                .history_lookup_accepted_tokens
                .load(Ordering::Relaxed),
            TELEMETRY.mtp_proposals.load(Ordering::Relaxed),
            TELEMETRY.mtp_rejected_tokens.load(Ordering::Relaxed),
            TELEMETRY
                .history_lookup_cost_disabled
                .load(Ordering::Relaxed),
            TELEMETRY.mtp_cost_disabled.load(Ordering::Relaxed),
        );

        record_proposer_outcome(QwenSpeculationProposer::HistoryLookup, 3, 2, 1, 2, 0);
        record_proposer_outcome(QwenSpeculationProposer::Mtp, 4, 1, 3, 2, 0);
        record_cost_disabled(QwenSpeculationProposer::HistoryLookup);
        record_cost_disabled(QwenSpeculationProposer::Mtp);

        assert_eq!(
            TELEMETRY.history_lookup_proposals.load(Ordering::Relaxed),
            before.0 + 1
        );
        assert_eq!(
            TELEMETRY
                .history_lookup_accepted_tokens
                .load(Ordering::Relaxed),
            before.1 + 2
        );
        assert_eq!(
            TELEMETRY.mtp_proposals.load(Ordering::Relaxed),
            before.2 + 1
        );
        assert_eq!(
            TELEMETRY.mtp_rejected_tokens.load(Ordering::Relaxed),
            before.3 + 3
        );
        assert_eq!(
            TELEMETRY
                .history_lookup_cost_disabled
                .load(Ordering::Relaxed),
            before.4 + 1
        );
        assert_eq!(
            TELEMETRY.mtp_cost_disabled.load(Ordering::Relaxed),
            before.5 + 1
        );
    }

    #[test]
    fn fallback_reason_is_counted_separately() {
        let _guard = TELEMETRY_TEST_LOCK.lock().expect("telemetry test lock");
        let total = TELEMETRY.fallback_requests.load(Ordering::Relaxed);
        let slot_aware = TELEMETRY
            .fallback_runtime_unavailable
            .load(Ordering::Relaxed);
        record_fallback(QwenSpeculationDecision::RuntimeUnavailable);
        assert_eq!(
            TELEMETRY.fallback_requests.load(Ordering::Relaxed),
            total + 1
        );
        assert_eq!(
            TELEMETRY
                .fallback_runtime_unavailable
                .load(Ordering::Relaxed),
            slot_aware + 1
        );
    }

    #[test]
    fn telemetry_records_measured_round_and_equivalent_baseline_time() {
        let _guard = TELEMETRY_TEST_LOCK.lock().expect("telemetry test lock");
        let before = (
            TELEMETRY.mtp_round_nanos.load(Ordering::Relaxed),
            TELEMETRY
                .mtp_equivalent_ordinary_nanos
                .load(Ordering::Relaxed),
        );
        record_proposer_timing(
            QwenSpeculationProposer::Mtp,
            Duration::from_millis(17),
            Duration::from_millis(24),
        );
        assert_eq!(
            TELEMETRY.mtp_round_nanos.load(Ordering::Relaxed),
            before.0 + 17_000_000
        );
        assert_eq!(
            TELEMETRY
                .mtp_equivalent_ordinary_nanos
                .load(Ordering::Relaxed),
            before.1 + 24_000_000
        );
    }
}