Files
alzeo/dashboard/tests/test_engine_metrics.py
T
2247aaf005 cockpit: the Traffic view reads the vLLM lanes' counters too
The window read SGLang's counter names only, and the collector asked the
SGLang lanes alone for their page: each of the four vLLM lanes (Flash
FP4-Local, Kolibri, the two Nemotron lanes) gave the Traffic view nothing.
It asks them too now and reads either engine's names, taken from the pull
request's rework (2026-10-20): the same keys off an sglang: or a vllm: page,
and the decode speed on one clock for each engine. SGLang's inter-token
count is already tokens. vLLM samples once per scheduler output, so with a
drafter its count is steps, and read as tokens it showed 14.8 tok/s where
the engine decoded 36.4. Its decode speed is its generated tokens less its
first tokens over the inter-token time, three counters it moves every
iteration.

Added here: the collector's key taken among the vLLM lanes too, the canary
kept to the SGLang lanes it runs on, and a page that says no canary ran on a
vLLM lane. vLLM counts no client that left (its abort skips the statistics
of a finished request, in v0.29.0, the Nemotron lanes' nightly and
FP4-Local's build), so its abandons are said not counted, rather than none.
Its tokens accepted per draft step are vLLM's own measure there, one plus
the accepted tokens per draft: the generated tokens per draft said 6.22 on a
page where vLLM counts 2.99. Its verdict says vLLM counts its tokens and
latencies at every step, and a request, its wait and its prefill once it
finishes, and its lanes go by the cockpit's names, from VLLM_UNITS, a list
the lane-lists test holds to the vLLM family by its name. Every vLLM name the
window reads is on the pages captured from this box's four vLLM lanes,
three vLLM builds. The collector's and the page's tests fail on the old
code.

Co-Authored-By: Dimitris Kontokostas <jimkont@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 22:14:49 +02:00

711 lines
39 KiB
Python

#!/usr/bin/env python3
"""The engine's own counters (engine_metrics.py): what is read, and what the window says.
The window answers the last 5 minutes (how much of the prompts the cache held, how fast
the engine prefilled and each request decoded, how long a request waited in the queue and
for its first token, how many tokens all clients got per second, how idle the scheduler
was, what aborts landed) from two reads of SGLang's counters, and its own peaks of the
levels it saw at those reads. These tests hold the reading (every label set summed, only
the label sets asked for, nothing but the listed counters), the arithmetic, and the two
things that are not the clients': the cockpit's canary, taken out exactly, and an engine
that started again, whose counters started again from zero.
"""
import importlib.util
import pathlib
import random
import re
import unittest
DASH = pathlib.Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("engine_metrics_under_test", DASH / "engine_metrics.py")
em = importlib.util.module_from_spec(spec)
spec.loader.exec_module(em)
L = 'engine_type="unified",model_name="qwen3.8-27b",pp_rank="0",tp_rank="0"'
def page(requests=0, prompt=0, cached_device=0, cached_host=0, generated=0,
ttft_sum=0.0, ttft_count=0, itl_sum=0.0, itl_count=0, pc=0, fwd=0.0, chk=0.0,
q_sum=0.0, q_count=0, idle=0.0, aborted=0, ver=0, running=None, queued=None, pool=None,
streaming_split=True):
"""A /metrics page in the shape SGLang's multiprocess collector writes."""
half = (lambda v: (v // 2, v - v // 2)) if streaming_split else (lambda v: (v, 0))
pr, ps = half(prompt)
gr, gs = half(generated)
rr, rs = half(requests)
cr, cs = half(pc)
g = ([f'sglang:num_running_reqs{{{L}}} {running}', f'sglang:num_queue_reqs{{{L}}} {queued}',
f'sglang:full_token_usage{{{L}}} {pool}'] if running is not None else [])
return "\n".join([
"# HELP sglang:prompt_tokens_total Number of prefill tokens processed.",
"# TYPE sglang:prompt_tokens_total counter",
f'sglang:prompt_tokens_total{{{L},is_streaming="false"}} {pr}.0',
f'sglang:prompt_tokens_total{{{L},is_streaming="true"}} {ps}.0',
f'sglang:prompt_tokens_created{{{L},is_streaming="true"}} 1.7917e+09',
f'sglang:generation_tokens_total{{{L},is_streaming="false"}} {gr}.0',
f'sglang:generation_tokens_total{{{L},is_streaming="true"}} {gs}.0',
f'sglang:num_requests_total{{{L},is_streaming="false"}} {rr}.0',
f'sglang:num_requests_total{{{L},is_streaming="true"}} {rs}.0',
f'sglang:cached_tokens_total{{{L},cache_source="device"}} {cached_device}.0',
f'sglang:cached_tokens_total{{{L},cache_source="host"}} {cached_host}.0',
"# TYPE sglang:time_to_first_token_seconds histogram",
f'sglang:time_to_first_token_seconds_bucket{{{L},is_streaming="true",le="0.1"}} {ttft_count}.0',
f'sglang:time_to_first_token_seconds_bucket{{{L},is_streaming="true",le="+Inf"}} {ttft_count}.0',
f'sglang:time_to_first_token_seconds_count{{{L},is_streaming="true"}} {ttft_count}.0',
f'sglang:time_to_first_token_seconds_sum{{{L},is_streaming="true"}} {ttft_sum}',
f'sglang:inter_token_latency_seconds_bucket{{{L},le="0.05"}} {itl_count}.0',
f'sglang:inter_token_latency_seconds_count{{{L}}} {itl_count}.0',
f'sglang:inter_token_latency_seconds_sum{{{L}}} {itl_sum}',
f'sglang:inter_token_latency_seconds_created{{{L}}} 1.7917e+09',
f'sglang:realtime_tokens_total{{{L},mode="prefill_compute"}} {cr}.0',
f'sglang:realtime_tokens_total{{{L},mode="prefill_compute"}} {cs}.0',
f'sglang:realtime_tokens_total{{{L},mode="prefill_cache"}} 999999.0',
f'sglang:realtime_tokens_total{{{L},mode="decode"}} 999999.0',
f'sglang:realtime_tokens_created{{{L},mode="prefill_compute"}} 1.7917e+09',
f'sglang:per_stage_req_latency_seconds_sum{{{L},stage="prefill_forward"}} {fwd}',
f'sglang:per_stage_req_latency_seconds_sum{{{L},stage="chunked_prefill"}} {chk}',
f'sglang:per_stage_req_latency_seconds_sum{{{L},stage="decode"}} 9999.0',
f'sglang:per_stage_req_latency_seconds_count{{{L},stage="prefill_forward"}} {prompt + 1}.0',
f'sglang:queue_time_seconds_sum{{{L}}} {q_sum}',
f'sglang:queue_time_seconds_count{{{L}}} {q_count}.0',
f'sglang:scheduler_idle_seconds_total{{{L}}} {idle}',
f'sglang:num_aborted_requests_total{{{L}}} {aborted}.0',
f'sglang:spec_verify_calls_total{{{L}}} {ver}.0',
f'sglang:spec_verify_calls_total_created{{{L}}} 1.7917e+09',
*g,
'sglang:cache_hit_rate{%s} 0.93' % L,
"", ])
class Reading(unittest.TestCase):
def test_every_label_set_is_summed(self):
v = em.parse(page(requests=7, prompt=1001, cached_device=600, cached_host=100, generated=33,
ttft_sum=2.5, ttft_count=7, itl_sum=1.25, itl_count=26,
pc=900, fwd=0.5, chk=0.25, q_sum=1.5, q_count=5, idle=3.0, aborted=2, ver=9))
self.assertEqual(v, {"requests": 7.0, "prompt": 1001.0, "cached": 700.0, "generated": 33.0,
"ttft_sum": 2.5, "ttft_count": 7.0, "itl_sum": 1.25, "decoded": 26.0,
"first": 0.0,
"pc": 900.0, "fwd": 0.5, "q_sum": 1.5, "q_count": 5.0,
"idle": 3.0, "aborted": 2.0, "ver": 9.0, "acc": 0.0, "idle_seen": True, "engine": "sglang"})
def test_ttft_le_buckets_are_not_summed_into_the_count(self):
v = em.parse(page(ttft_count=3))
self.assertEqual(v["ttft_count"], 3.0, "the le= buckets are not added to the count")
def test_a_page_that_is_not_an_engines_is_none(self):
for text in ("", "hello", "# HELP x\n# TYPE x counter\nx_total 3\n", "<html>404</html>"):
self.assertIsNone(em.parse(text), text)
def test_odd_values_are_skipped(self):
v = em.parse(f'sglang:num_requests_total{{{L}}} NaN\nsglang:num_requests_total{{x="1"}} 4\n'
'sglang:prompt_tokens_total +Inf\nsglang:prompt_tokens_total{a="b"} junk\n')
self.assertEqual((v["requests"], v["prompt"]), (4.0, 0.0))
def test_the_real_page_of_a_27b_just_ready(self):
# captured on the reference box (2026-10-07), right after the lane was ready: its own
# warm-up request is the one counted, and the families it never fed are not listed
page_ = (DASH / "tests" / "fixtures" / "sglang-metrics-27b-ready.txt").read_text()
self.assertNotIn("cached_tokens_total{", page_, "the fixture is the page as it was")
v = em.parse(page_)
self.assertEqual(v, {"requests": 1.0, "prompt": 178.0, "cached": 0.0, "generated": 8.0,
"ttft_sum": 12.01112219899369, "ttft_count": 1.0,
"itl_sum": 0.0, "decoded": 0.0, "first": 0.0,
"pc": 0.0, "fwd": 0.0, "q_sum": 0.0, "q_count": 0.0,
"idle": 0.0, "aborted": 0.0, "ver": 0.0, "acc": 0.0, "idle_seen": False, "engine": "sglang"})
def test_an_engine_page_with_no_request_yet_is_zeros_not_none(self):
v = em.parse("# HELP sglang:num_requests_total The number of requests.\n"
"# TYPE sglang:num_requests_total counter\n"
'sglang:num_running_reqs{model_name="m"} 0.0\n')
self.assertEqual(v, {**dict.fromkeys(em.NAMES, 0.0), "idle_seen": False, "engine": "sglang"})
def test_a_trailing_timestamp_is_not_the_value(self):
v = em.parse(f'sglang:num_requests_total{{{L}}} 12 1791322000000\n')
self.assertEqual(v["requests"], 12.0)
def test_only_the_label_sets_asked_for_are_summed(self):
# the page carries the cache and decode modes of the realtime tokens and the decode
# and chunked stages of the stopwatch: none of them may leak into the prefill
# numbers
v = em.parse(page(pc=800, fwd=0.4, chk=0.25))
self.assertEqual((v["pc"], v["fwd"]), (800.0, 0.4))
def test_the_levels_are_read_apart_and_absence_is_none(self):
self.assertEqual(em.parse_gauges(page(running=2, queued=1, pool=0.62)),
{"running": 2.0, "queued": 1.0, "pool": 0.62})
self.assertEqual(em.parse_gauges(page()), {"running": None, "queued": None, "pool": None})
self.assertIsNone(em.parse_gauges(f'sglang:num_running_reqs{{{L}}} NaN\n')["running"])
self.assertIsNone(em.parse_gauges("hello"))
def test_a_page_without_the_idle_counter_says_so(self):
# some SGLang builds do not publish scheduler_idle_seconds_total at all
v = em.parse(page().replace("scheduler_idle_seconds_total",
"scheduler_idle_other_total"))
self.assertEqual((v["idle_seen"], v["idle"]), (False, 0.0))
def test_idle_counter_help_lines_and_nan_do_not_count_as_seen(self):
# a counter that is registered but never observed prints only its HELP and TYPE
# lines, and a NaN is not a value: neither may read as an engine that is fully busy
head = ('# HELP sglang:scheduler_idle_seconds_total The idle time of the scheduler.\n'
'# TYPE sglang:scheduler_idle_seconds_total counter\n'
f'sglang:num_requests_total{{{L}}} 3.0\n')
v = em.parse(head)
self.assertEqual((v["idle_seen"], v["idle"]), (False, 0.0), "HELP lines only")
v = em.parse(head + f'sglang:scheduler_idle_seconds_total{{{L}}} NaN\n')
self.assertEqual((v["idle_seen"], v["idle"]), (False, 0.0), "a NaN is not a value")
v = em.parse(head + f'sglang:scheduler_idle_seconds_total{{{L}}} 12.5\n')
self.assertEqual((v["idle_seen"], v["idle"]), (True, 12.5))
def test_the_pool_keeps_its_fullest_rank_and_counts_add(self):
# multi-rank page: usage is a fraction and keeps its fullest rank; request
# counts add across ranks
t = ('sglang:full_token_usage{model_name="m",tp_rank="0"} 0.4\n'
'sglang:full_token_usage{model_name="m",tp_rank="1"} 0.7\n'
'sglang:num_running_reqs{model_name="m",tp_rank="0"} 3.0\n'
'sglang:num_running_reqs{model_name="m",tp_rank="1"} 5.0\n')
self.assertEqual(em.parse_gauges(t), {"pool": 0.7, "running": 8.0, "queued": None})
def vals(**kw):
seen = kw.pop("idle_seen", True)
out = dict.fromkeys(em.NAMES, 0.0)
out["idle_seen"] = seen
out.update({k: float(v) for k, v in kw.items()})
return out
class TheWindow(unittest.TestCase):
KEY = ("qwen38-sglang.service", "123")
def test_two_reads_say_the_four_numbers(self):
w = em.Window(300)
w.add(1000, self.KEY, vals(requests=10, prompt=50_000, cached=40_000, generated=2_000,
ttft_sum=5, ttft_count=10, itl_sum=40, decoded=1_990))
w.add(1300, self.KEY, vals(requests=14, prompt=250_000, cached=230_000, generated=3_000,
ttft_sum=9, ttft_count=14, itl_sum=60, decoded=2_986))
s = w.stats(1300)
self.assertEqual((s["requests"], s["prompt_tokens"], s["cached_tokens"], s["generated_tokens"]),
(4, 200_000, 190_000, 1_000))
self.assertAlmostEqual(s["reuse"], 0.95)
self.assertAlmostEqual(s["decode_tps"], 996 / 20)
self.assertAlmostEqual(s["ttft_s"], 1.0)
self.assertAlmostEqual(s["throughput_tps"], 1_000 / 300)
self.assertEqual((s["watched_s"], s["canaries_out"], s["approximate"]), (300.0, 0, False))
def test_a_younger_window_says_how_long_it_watched(self):
w = em.Window(300)
w.add(1000, self.KEY, vals())
w.add(1090, self.KEY, vals(requests=1, prompt=100, generated=10, ttft_sum=0.2, ttft_count=1,
itl_sum=0.3, decoded=9))
self.assertEqual(w.stats(1090)["watched_s"], 90.0)
def test_the_window_starts_at_the_last_read_before_its_span(self):
w = em.Window(300)
for t, n in ((0, 0), (100, 1), (200, 2), (305, 3), (410, 4), (520, 5)):
w.add(t, self.KEY, vals(requests=n))
self.assertEqual(w.samples[0][0], 200, "520 - 300 = 220: the read at 200 starts it")
self.assertEqual(w.stats(520)["requests"], 3)
def test_nothing_happened_is_no_number(self):
w = em.Window(300)
w.add(0, self.KEY, vals(requests=5, prompt=10))
w.add(300, self.KEY, vals(requests=5, prompt=10))
s = w.stats(300)
self.assertEqual(s["requests"], 0)
self.assertEqual((s["reuse"], s["decode_tps"], s["ttft_s"]), (None, None, None))
self.assertEqual(s["throughput_tps"], 0.0)
def test_a_request_still_decoding_has_a_speed_before_it_finishes(self):
# the inter-token counters move with every output; the request counters at its end
w = em.Window(300)
w.add(0, self.KEY, vals())
w.add(30, self.KEY, vals(ttft_sum=0.4, ttft_count=1, itl_sum=20, decoded=900))
s = w.stats(30)
self.assertEqual(s["requests"], 0)
self.assertAlmostEqual(s["decode_tps"], 45.0)
self.assertAlmostEqual(s["ttft_s"], 0.4)
def test_the_drafters_step_rate_is_not_printed_as_the_decode_speed(self):
# FP4-Local's vLLM samples inter-token latency once per draft, not once
# per token: its MTP steps netted ~2.5 tokens each while the sample count
# equalled the drafter's exactly (2026-10-19). The sample count over the
# sample sum is a step rate: it printed 14.8 where the engine decoded 36.4
# tokens per second. On a vLLM page "decoded" is the generated tokens and
# "first" the first-token count
key = ("qwen38-flash-local.service", "7")
w = em.Window(300)
w.add(0, key, vals())
w.add(30, key, vals(requests=1, prompt=500, generated=682, decoded=682, first=1,
ttft_sum=0.2, ttft_count=1, itl_sum=18.69, ver=276))
s = w.stats(30)
self.assertAlmostEqual(s["decode_tps"], (682 - 1) / 18.69, places=6)
self.assertGreater(s["decode_tps"], 2 * (276 / 18.69),
"the step rate was printed again as the token rate:"
" these steps netted 682/276 = 2.47 tokens each")
def test_a_new_engine_starts_the_window_again(self):
w = em.Window(300)
w.add(0, self.KEY, vals(requests=100))
w.add(100, ("qwen38-flash.service", "999"), vals(requests=3))
w.add(150, ("qwen38-flash.service", "999"), vals(requests=4))
s = w.stats(150)
self.assertEqual((s["requests"], s["watched_s"]), (1, 50.0))
def test_counters_that_went_back_start_it_again(self):
# the same unit restarted between two reads that both saw it serving
w = em.Window(300)
w.add(0, self.KEY, vals(requests=100, prompt=9_000))
w.add(10, self.KEY, vals(requests=2, prompt=300))
w.add(20, self.KEY, vals(requests=3, prompt=400))
s = w.stats(20)
self.assertEqual((s["requests"], s["prompt_tokens"], s["watched_s"]), (1, 100, 10.0))
def test_prefill_queue_idle_aborts_and_the_peaks(self):
w = em.Window(300)
w.add(0, self.KEY, vals(pc=1000, fwd=1.0, q_sum=2.0, q_count=4, idle=20, aborted=1),
gauges={"running": 3, "queued": 1, "pool": 0.4})
w.add(300, self.KEY, vals(pc=3000, fwd=2.5, q_sum=6.0, q_count=8, idle=170, aborted=3),
gauges={"running": 8, "queued": 0, "pool": 0.62})
s = w.stats(300)
self.assertAlmostEqual(s["prefill_tps"], 2000 / 1.5, 6)
self.assertAlmostEqual(s["queue_s"], 1.0)
self.assertAlmostEqual(s["idle_share"], 0.5)
self.assertEqual(s["aborted"], 2)
self.assertEqual((s["pool_max"], s["running_max"], s["queued_max"]), (0.62, 8, 1))
def test_a_read_without_levels_peaks_nothing(self):
w = em.Window(300)
w.add(0, self.KEY, vals(requests=1, prompt=100))
w.add(50, self.KEY, vals(requests=2, prompt=200), gauges={"running": None, "queued": None, "pool": None})
s = w.stats(50)
self.assertEqual(s["requests"], 1)
self.assertEqual((s["pool_max"], s["running_max"], s["queued_max"]), (None, None, None))
def test_prefill_tokens_with_no_stopwatch_is_no_number(self):
# an engine whose per-stage stopwatch is not on its page: the tokens alone are not
# a speed, they would divide by idle time
w = em.Window(300)
w.add(0, self.KEY, vals())
w.add(50, self.KEY, vals(pc=900))
self.assertIsNone(w.stats(50)["prefill_tps"])
def test_a_quiet_window_says_fully_idle(self):
w = em.Window(300)
w.add(0, self.KEY, vals(idle=5), gauges={"running": 0, "queued": 0, "pool": 0.0})
w.add(300, self.KEY, vals(idle=300), gauges={"running": 0, "queued": 0, "pool": 0.0})
s = w.stats(300)
self.assertAlmostEqual(s["idle_share"], 295 / 300)
self.assertEqual((s["pool_max"], s["running_max"], s["queued_max"]), (0.0, 0, 0))
self.assertEqual(s["aborted"], 0)
def test_the_drafter_yields_its_window_accept_length(self):
w = em.Window(300)
w.add(0, self.KEY, vals(generated=1000, ver=250))
w.add(60, self.KEY, vals(generated=1700, ver=440))
self.assertAlmostEqual(w.stats(60)["acc_len"], 700 / 190, 6)
def test_a_lane_without_a_drafter_says_nothing_about_it(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.add(50, self.KEY, vals(generated=100, itl_sum=2, decoded=100))
self.assertIsNone(w.stats(50)["acc_len"], "no verification calls: no accept length")
def test_a_chunked_prompt_counts_its_prefill_once(self):
# prefill_forward spans the chunked prompt's whole prefill; the chunked_prefill
# stage re-times the chunks from the same start, so summing both would halve the
# speed (a 27B lane: 80,400 tokens in ten 8,192-token chunks)
w = em.Window(300)
w.add(0, self.KEY, em.parse(page()))
w.add(61.8, self.KEY, em.parse(page(pc=80_400, fwd=61.8, chk=61.7)))
self.assertAlmostEqual(w.stats(61.8)["prefill_tps"], 80_400 / 61.8, places=1)
def test_a_missing_idle_counter_says_nothing_about_idle(self):
# both ends of the window must have seen the idle counter: a build that never
# publishes it must not read as fully busy
w = em.Window(300)
w.add(0, self.KEY, vals(idle_seen=False))
w.add(300, self.KEY, vals(idle=300, idle_seen=False))
self.assertIsNone(w.stats(300)["idle_share"])
w.add(600, self.KEY, vals(idle=600))
self.assertIsNone(w.stats(600)["idle_share"], "one end still lacks the counter")
CANARY = vals(requests=1, prompt=14, generated=2, ttft_sum=0.08, ttft_count=1, itl_sum=0.02, decoded=1,
pc=14, fwd=0.01, q_sum=0.0004, q_count=1, ver=1)
def plus(a, b):
return {k: a[k] + b[k] for k in em.NAMES}
class TheCanaryIsTakenOut(unittest.TestCase):
KEY = ("qwen38-flash.service", "7")
def test_an_idle_lane_with_canaries_says_nothing_happened(self):
w = em.Window(300)
v = vals()
w.add(0, self.KEY, v)
for t in (90, 180, 270):
before = v
v = plus(v, CANARY)
w.canary(t, self.KEY, before, v)
w.add(t + 1, self.KEY, v)
s = w.stats(271)
self.assertEqual((s["requests"], s["prompt_tokens"], s["generated_tokens"]), (0, 0, 0))
self.assertEqual((s["reuse"], s["decode_tps"], s["ttft_s"]), (None, None, None))
self.assertEqual((s["prefill_tps"], s["queue_s"], s["acc_len"]), (None, None, None),
"the canary's prefill, queue and verifications out too")
self.assertEqual((s["canaries_out"], s["approximate"]), (3, False))
def test_client_numbers_are_exact_with_a_canary_among_them(self):
w = em.Window(300)
client = vals(requests=2, prompt=40_000, cached=39_000, generated=800,
ttft_sum=1.0, ttft_count=2, itl_sum=19.0, decoded=798)
w.add(0, self.KEY, vals())
w.canary(100, self.KEY, vals(), CANARY)
w.add(200, self.KEY, plus(CANARY, client))
s = w.stats(200)
self.assertEqual((s["requests"], s["prompt_tokens"], s["cached_tokens"], s["generated_tokens"]),
(2, 40_000, 39_000, 800))
self.assertAlmostEqual(s["decode_tps"], 798 / 19.0)
self.assertAlmostEqual(s["ttft_s"], 0.5)
def test_a_canary_that_overlapped_a_client_makes_the_window_approximate(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
overlapped = plus(CANARY, vals(requests=1, prompt=500, ttft_sum=0.3, ttft_count=1))
w.canary(50, self.KEY, vals(), overlapped)
w.add(60, self.KEY, overlapped)
self.assertTrue(w.stats(60)["approximate"])
self.assertEqual(w.stats(60)["canaries_out"], 0, "nothing is taken out that is not the canary's alone")
w.add(400, self.KEY, overlapped)
self.assertFalse(w.stats(400)["approximate"], "once that canary has left the window")
def test_a_canary_with_a_missed_read_makes_it_approximate(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary(10, self.KEY, None, CANARY)
self.assertFalse(w.stats(10)["approximate"], "no read holds it yet")
w.add(20, self.KEY, CANARY)
s = w.stats(20)
self.assertTrue(s["approximate"])
self.assertEqual((s["requests"], s["canaries_out"]), (1, 0), "counted, and said to be")
w.add(330, self.KEY, CANARY)
self.assertFalse(w.stats(330)["approximate"], "once the window starts after it")
def test_a_canary_of_another_engine_changes_nothing(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary(10, ("qwen38-sglang.service", "1"), vals(), CANARY)
self.assertEqual(list(w.canaries), [])
self.assertFalse(w.stats(20)["approximate"])
def test_a_canary_before_the_window_is_not_taken_out_of_it(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary(10, self.KEY, vals(), CANARY)
w.add(20, self.KEY, CANARY)
w.add(330, self.KEY, plus(CANARY, vals(requests=1, prompt=10)))
s = w.stats(330)
self.assertEqual((s["requests"], s["prompt_tokens"], s["canaries_out"]), (1, 10, 0))
def test_the_canary_span_keeps_its_idle_time(self):
# the idle wall clock is the engine's, not the canary's: the idle that accumulated
# inside the canary's before/after reads stays in the window's share
w = em.Window(300)
w.add(0, self.KEY, vals(idle=0))
w.canary(100, self.KEY, vals(idle=95),
vals(idle=105, requests=1, prompt=14, generated=2, ttft_sum=0.08,
ttft_count=1, itl_sum=0.02, decoded=1, pc=14, fwd=0.01, ver=1))
w.add(300, self.KEY,
vals(idle=300, requests=1, prompt=14, generated=2, ttft_sum=0.08,
ttft_count=1, itl_sum=0.02, decoded=1, pc=14, fwd=0.01, ver=1))
s = w.stats(300)
self.assertAlmostEqual(s["idle_share"], 1.0)
self.assertEqual((s["requests"], s["canaries_out"]), (0, 1))
class AgainstAReplay(unittest.TestCase):
"""Random traffic and canaries with the timing of the box, each step at its own instant:
a read of the window takes its values when it starts and is added when it ends; the
canary reads, its request is counted, it reads again. After EVERY read the window's
numbers equal the sums over the client requests between the instants its two ends took
their values, unless the window says itself it is approximate (a client finished inside
a canary). No read across a canary is kept, so no canary is taken out of a window that
does not hold it, or left in one that does."""
def test_random_traffic_at_every_read(self):
rnd = random.Random(20261007)
checked = dropped = approximate = 0
for trial in range(60):
w = em.Window(300)
key = ("qwen38-flash.service", str(trial))
events = [] # (instant, order, kind, payload)
t = 0.0
while t < 900:
for _ in range(rnd.randint(0, 2)):
p = rnd.randint(1, 60_000)
events.append((t + rnd.uniform(0, 5), 0, "client", vals(
requests=1, prompt=p, cached=rnd.randint(0, p), generated=rnd.randint(1, 900),
ttft_sum=rnd.uniform(0.05, 30), ttft_count=1,
# SGLang's per-token inter-token count, drawn on its own: the
# window must not tie it to the finish-time counters
itl_sum=rnd.uniform(0.1, 40), decoded=rnd.randint(0, 899))))
if rnd.random() < 0.15:
b, x = t + rnd.uniform(0, 4.5), rnd.uniform(0.05, 0.5)
events += [(b, 1, "canary_begins", None), (b + x / 2, 2, "canary_counted", None),
(b + x, 3, "canary_ends", None)]
r, d = t + 5 - rnd.uniform(0, 0.2), rnd.uniform(0.001, 0.3)
events += [(r, 4, "read_starts", r), (r + d, 5, "read_ends", r)]
t += 5
events.sort(key=lambda e: (e[0], e[1]))
total, finished, snaps, took, before = vals(), [], {}, {}, None
for at, _, kind, x in events:
if kind == "client":
total = plus(total, x)
finished.append((at, x))
elif kind == "canary_begins":
w.canary_begins(at)
before = total
elif kind == "canary_counted":
total = plus(total, CANARY)
elif kind == "canary_ends":
w.canary(at, key, before, total)
elif kind == "read_starts":
snaps[x] = total
else:
kept = w.add(at, key, snaps.pop(x), started=x)
dropped += not kept
if kept:
took[at] = x
if len(w.samples) < 2:
continue
s = w.stats(at)
if s["approximate"]:
approximate += 1
continue
t0, t1 = took[w.samples[0][0]], took[w.samples[-1][0]]
mine = [c for tc, c in finished if t0 < tc <= t1]
want = {k: sum(c[k] for c in mine) for k in em.NAMES}
self.assertEqual(s["requests"], len(mine), (trial, at))
self.assertEqual(s["prompt_tokens"], want["prompt"])
self.assertEqual(s["cached_tokens"], want["cached"])
self.assertEqual(s["generated_tokens"], want["generated"])
if want["ttft_count"]:
self.assertAlmostEqual(s["ttft_s"], want["ttft_sum"] / want["ttft_count"], places=6)
if want["decoded"]:
self.assertAlmostEqual(s["decode_tps"], want["decoded"] / want["itl_sum"], places=6)
checked += 1
self.assertGreater(checked, 5000)
self.assertGreater(dropped, 0, "the replay never put a read across a canary")
self.assertGreater(approximate, 0, "the replay never put a client inside a canary")
class AReadAcrossTheCanaryIsDropped(unittest.TestCase):
KEY = ("qwen38-flash.service", "7")
def test_a_read_while_the_canary_is_in_flight(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary_begins(10)
self.assertFalse(w.add(11, self.KEY, CANARY, started=10.5))
w.canary(12, self.KEY, vals(), CANARY)
self.assertTrue(w.add(15, self.KEY, CANARY, started=14.9))
self.assertEqual((w.stats(15)["requests"], w.stats(15)["canaries_out"]), (0, 1))
def test_a_read_that_began_before_the_canary_ended_after_it(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary_begins(10)
w.canary(12, self.KEY, vals(), CANARY)
self.assertFalse(w.add(13, self.KEY, vals(), started=9.9), "it may hold the canary or not")
self.assertEqual(w.stats(13)["requests"], 0)
def test_a_canary_that_never_said_it_ended_stops_blinding_after_a_minute(self):
w = em.Window(300)
w.add(0, self.KEY, vals())
w.canary_begins(10)
self.assertFalse(w.add(65, self.KEY, vals(), started=64.9))
self.assertTrue(w.add(75, self.KEY, vals(), started=74.9))
class TheVLLMPage(unittest.TestCase):
"""The same window keys off a vLLM page (the Kolibri, Nemotron and Flash FP4-Local
lanes serve vLLM): the names differ, the reading does not, and a page carrying neither
prefix is still no engine's /metrics."""
def test_the_reference_page_of_the_serving_fp4_engine(self):
# captured by the author of PR #55 on his own DGX Spark (2026-10-19), FP4-Local served
# by the vLLM build this repo's lane runs, under the flash lane's name in his config of
# it, with cache hits that this repo's capture of the lane has none of: every key the
# window reads is on the page, under the vllm: names
page_ = (DASH / "tests" / "fixtures" / "vllm-metrics-fp4-local.txt").read_text()
v = em.parse(page_)
self.assertIsNotNone(v)
# each key with a vLLM name read a value off the page: parse zero-fills an absent
# name, so a key set says nothing (found in review, 2026-10-20)
for key, pairs in em.NAMES.items():
# no request was aborted while the page was captured
if key != "aborted" and any(name.startswith("vllm:") for name, _ in pairs):
self.assertGreater(v[key], 0, key)
self.assertGreater(v["prompt"], v["cached"]) # the cache held most of the prompts
self.assertEqual(v["requests"], v["ttft_count"]) # every finished one timed its first token
self.assertEqual((v["decoded"], v["first"]), (v["generated"], v["ttft_count"]))
self.assertLess(v["pc"], v["prompt"]) # cache-served tokens are not in pc
self.assertEqual(v["pc"], 103958.0) # the computed tokens' histogram sum
self.assertEqual(v["fwd"], 54.32581236108672)
# every level read a value, not the None of a name not on the page
self.assertTrue(all(g is not None for g in em.parse_gauges(page_).values()),
em.parse_gauges(page_))
w = em.Window(300)
w.add(0, ("qwen38-flash-local.service", "1"), dict.fromkeys(em.NAMES, 0.0))
w.add(300, ("qwen38-flash-local.service", "1"), v)
# 7,706 tokens less the 15 first ones over 211.9 s of inter-token time: the 36.3
# tok/s the engine decoded, not the 14.3 its 3,032 samples would say
self.assertAlmostEqual(w.stats(300)["decode_tps"], (7706 - 15) / 211.90875176200643, places=6)
def test_only_the_filtered_label_set_counts(self):
page = "\n".join([
'vllm:prompt_tokens_by_source_total{model_name="m",source="local_compute"} 100.0',
'vllm:prompt_tokens_by_source_total{model_name="m",source="local_cache_hit"} 400.0',
'vllm:request_prefill_kv_computed_tokens_count{model_name="m"} 2.0',
'vllm:request_prefill_kv_computed_tokens_sum{model_name="m"} 60.0',
'vllm:prompt_tokens_cached_total{model_name="m"} 400.0',
'vllm:request_success_total{model_name="m",finished_reason="stop"} 3.0',
'vllm:request_success_total{model_name="m",finished_reason="length"} 1.0',
'vllm:request_success_created{model_name="m"} 1.0', # prometheus convention: not the counter
'vllm:generation_tokens_total{model_name="m"} 12.0',
'vllm:num_requests_running{model_name="m"} 2.0',
'vllm:num_requests_waiting{model_name="m"} 1.0',
'vllm:kv_cache_usage_perc{model_name="m"} 0.25',
])
v = em.parse(page)
# pc is the finished requests' computed tokens, not the per-iteration source counter
self.assertEqual((v["pc"], v["cached"], v["requests"]), (60.0, 400.0, 4.0))
self.assertEqual((v["generated"], v["decoded"]), (12.0, 12.0))
self.assertEqual(em.parse_gauges(page), {"running": 2.0, "queued": 1.0, "pool": 0.25})
def test_vllm_counts_no_client_that_left(self):
# vLLM's abort ends a request without the statistics of a finished one, so its
# request_success_total{finished_reason="abort"} never moves for a client that left (read in
# output_processor.py of v0.29.0, the Nemotron lanes' nightly and FP4-Local's build): the
# window said "none" of aborts it cannot see (found in review, 2026-10-20)
def read(n, aborted):
return em.parse("\n".join([
f'vllm:request_success_total{{model_name="m",finished_reason="stop"}} {n}.0',
f'vllm:request_success_total{{model_name="m",finished_reason="abort"}} {aborted}.0',
f'vllm:generation_tokens_total{{model_name="m"}} {9 * n}.0']))
a, b = read(1, 0), read(4, 2)
self.assertEqual((a["engine"], b["engine"]), ("vllm", "vllm"))
w = em.Window(300.0)
w.add(0, ("qwen38-flash-local.service", "1000"), a)
w.add(60, ("qwen38-flash-local.service", "1000"), b)
s = w.stats(60)
self.assertEqual(s["requests"], 5, "every finished request, an abort among them, is still a request")
self.assertIsNone(s["aborted"], "a zero would say no client left")
self.assertEqual(em.parse(page(aborted=2))["engine"], "sglang")
def test_vllms_accept_length_is_one_plus_its_accepted_drafts_per_draft(self):
# vLLM drafts on some steps only: Kolibri's page holds 816 drafts over 3,444 steps and
# 1,622 tokens accepted. Generated over drafts said 6.22 tokens a step, where vLLM's own
# counters say 1 + 1,622 / 816 = 2.99 (found in review, 2026-10-20)
page_ = (DASH / "tests" / "fixtures" / "vllm-metrics-kolibri.txt").read_text()
w = em.Window(300)
w.add(0, ("qwen38-kolibri.service", "1"), dict.fromkeys(em.NAMES, 0.0))
w.add(300, ("qwen38-kolibri.service", "1"), em.parse(page_))
self.assertAlmostEqual(w.stats(300)["acc_len"], 1 + 1622 / 816, places=6)
def test_each_vllm_lanes_own_page_holds_every_name_read(self):
# captured from this box's four vLLM lanes, three vLLM builds: every vLLM name the window
# reads is on each page, and every level reads a value
names = {n for pairs in em.NAMES.values() for n, _ in pairs if n.startswith("vllm:")}
for lane in ("flash-local", "kolibri", "nemotron", "nemotron-super"):
page_ = (DASH / "tests" / "fixtures" / f"vllm-metrics-{lane}.txt").read_text()
self.assertIsNotNone(em.parse(page_), lane)
for n in sorted(names):
with self.subTest(lane=lane, name=n):
self.assertRegex(page_, rf"(?m)^{re.escape(n)}[{{ ]")
self.assertTrue(all(g is not None for g in em.parse_gauges(page_).values()), lane)
def test_a_page_of_neither_engine_is_no_read(self):
self.assertIsNone(em.parse('prometheus_build_info{v="1"} 1.0\n'))
VL = 'engine="0",model_name="qwen3.8-flash-next-fp4"'
def vllm_page(requests=0, prompt=0, by_source=0, kv_computed=0, prefill_s=0.0, generated=0,
ttft_count=0, ttft_sum=0.0, itl_count=0, itl_sum=0.0, drafts=0):
"""A /metrics page in the shape the FP4-Local lane's vLLM writes: the token, first
token and inter-token counters move every scheduler iteration; the request count and
the per-request prefill histograms when a request finishes."""
return "\n".join([
f'vllm:request_success_total{{{VL},finished_reason="stop"}} {requests}.0',
f'vllm:request_success_total{{{VL},finished_reason="abort"}} 0.0',
f'vllm:prompt_tokens_total{{{VL}}} {prompt}.0',
f'vllm:prompt_tokens_by_source_total{{{VL},source="local_compute"}} {by_source}.0',
f'vllm:request_prefill_kv_computed_tokens_count{{{VL}}} {requests}.0',
f'vllm:request_prefill_kv_computed_tokens_sum{{{VL}}} {kv_computed}.0',
f'vllm:request_prefill_time_seconds_count{{{VL}}} {requests}.0',
f'vllm:request_prefill_time_seconds_sum{{{VL}}} {prefill_s}',
f'vllm:generation_tokens_total{{{VL}}} {generated}.0',
f'vllm:time_to_first_token_seconds_count{{{VL}}} {ttft_count}.0',
f'vllm:time_to_first_token_seconds_sum{{{VL}}} {ttft_sum}',
f'vllm:inter_token_latency_seconds_count{{{VL}}} {itl_count}.0',
f'vllm:inter_token_latency_seconds_sum{{{VL}}} {itl_sum}',
f'vllm:spec_decode_num_drafts_total{{{VL}}} {drafts}.0',
"", ])
class AtTheWindowsEdges(unittest.TestCase):
"""A request straddling the window's start, or still decoding at its end, must not
skew the decode speed: numerator and denominator have to move on one clock. On
SGLang the inter-token count is tokens and moves with its sum, the request and
generated counters only at a finish; on vLLM the generated tokens, first tokens
and inter-token sum all move per iteration (found in review, 2026-10-20). Each
case decodes at 50 tok/s; the vLLM one in MTP steps of 3 tokens every 0.06 s."""
KEY = ("qwen38-flash.service", "9")
def speeds(self, a, b, t0=0, t1=300):
w = em.Window(300)
self.assertTrue(w.add(t0, self.KEY, em.parse(a)))
self.assertTrue(w.add(t1, self.KEY, em.parse(b)))
return w.stats(t1)
def test_sglang_a_request_straddling_the_windows_start(self):
# first token at 0, decoding until 600, 500 s of it before the window's start
s = self.speeds(page(ttft_count=1, ttft_sum=0.5, itl_count=25_000, itl_sum=500.0),
page(requests=1, generated=30_001, ttft_count=1, ttft_sum=0.5,
itl_count=30_000, itl_sum=600.0), 500, 800)
self.assertAlmostEqual(s["decode_tps"], 50.0)
def test_sglang_a_request_still_decoding_at_the_windows_end(self):
# a finished 10-token request, then one decoding for 100 s that has not finished
s = self.speeds(page(), page(requests=1, generated=10, ttft_count=2, ttft_sum=0.4,
itl_count=9 + 5_000, itl_sum=0.18 + 100.0))
self.assertAlmostEqual(s["decode_tps"], 50.0)
def test_vllm_a_request_straddling_the_windows_start(self):
# first token at 0, decoding until 600 in 0.06 s steps, finished inside the window
s = self.speeds(vllm_page(generated=1 + 25_000, ttft_count=1, ttft_sum=0.5,
itl_count=8_333, itl_sum=500.0, drafts=8_333),
vllm_page(requests=1, generated=1 + 30_000, ttft_count=1, ttft_sum=0.5,
itl_count=10_000, itl_sum=600.0, drafts=10_000), 500, 800)
self.assertAlmostEqual(s["decode_tps"], 50.0)
def test_vllm_a_request_still_decoding_at_the_windows_end(self):
# a finished 10-token request (500 prompt tokens computed in 0.25 s), then an agent
# turn whose 50,000 computed prompt tokens and 5,001 tokens so far are on the
# per-iteration counters while it decodes, unfinished
s = self.speeds(vllm_page(), vllm_page(
requests=1, prompt=50_500, by_source=50_500, kv_computed=500, prefill_s=0.25,
generated=10 + 5_001, ttft_count=2, ttft_sum=0.4,
itl_count=3 + 1_667, itl_sum=0.18 + 100.0, drafts=3 + 1_667))
self.assertAlmostEqual(s["decode_tps"], 50.0)
# the in-flight prompt has no prefill time yet, so it adds no tokens either
self.assertAlmostEqual(s["prefill_tps"], 2_000.0)
if __name__ == "__main__":
unittest.main()