use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QwenSpeculationPolicy {
Off,
Auto,
}
pub const UNSET_OFF_MIN_SLOTS: usize = 4;
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";
#[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
},
)
}
}
pub const MTP_ROUND_COST_UNITS: f64 = 1.26;
pub const HISTORY_ROUND_COST_UNITS: f64 = 1.49;
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",
}
}
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())
}
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,
}
}
}
#[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",
}
}
}
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
}
}
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,
}
}
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
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct QwenSpeculationCostModel {
pub mtp_round: f64,
pub history_round: f64,
}
#[derive(Debug, Clone)]
pub struct QwenSpeculationController {
requested: Option<QwenSpeculationPolicy>,
policy: QwenSpeculationPolicy,
route: QwenSpeculationRoute,
cost_model: QwenSpeculationCostModel,
joint_mtp: bool,
conversation_prompt: Option<Vec<u32>>,
}
impl QwenSpeculationController {
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,
}
}
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,
}
}
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"
);
}
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
}
pub fn joint_mtp(&self) -> bool {
self.joint_mtp
}
pub fn policy(&self) -> QwenSpeculationPolicy {
self.policy
}
pub fn route(&self) -> QwenSpeculationRoute {
self.route
}
pub fn cost_model(&self) -> Option<QwenSpeculationCostModel> {
(self.route == QwenSpeculationRoute::Repeatable).then_some(self.cost_model)
}
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)
}
}
#[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,
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),
("always", QwenSpeculationPolicy::Off),
] {
assert_eq!(
QwenSpeculationPolicy::requested(Some(raw)),
Some(expected),
"HF2Q_QWEN_SPECULATION={raw:?}"
);
}
}
#[test]
fn server_policy_resolution_table() {
use QwenSpeculationPolicy::{Auto, Off};
let invalid = QwenSpeculationPolicy::requested(Some("always"));
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);
}
#[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
);
}
#[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
);
}
}