Skip to content

feat: Prometheus /metrics on both servers (tensorfold:* mirroring vLLM's names) - #156

Closed
jeidbugs404 wants to merge 2 commits into
ashhart:mainfrom
jeidbugs404:feat/metrics-endpoint
Closed

jeidbugs404 wants to merge 2 commits into
ashhart:mainfrom
jeidbugs404:feat/metrics-endpoint

Conversation

@jeidbugs404

Copy link
Copy Markdown
Contributor

Closes #110.

TensorFold's engines already know these numbers: the CUDA server's /health reports prompt and generation token totals and drafter counters per request (since #79), and both servers track which requests are admitted, queued and finished. But nothing publishes them in a form a scraper can collect: no tensorfold:num_requests_running to put on a dashboard, no time-to-first-token to alert on.

This adds GET /metrics to both servers (the CUDA server also answers GET /v1/metrics) in Prometheus text format (0.0.4), from a small hand-rolled shared module (server/metrics.py) with no new dependency. The metric names, types and HELP strings mirror vLLM's vllm:* metrics one for one under the tensorfold: prefix (issue #110), so a vLLM dashboard scrapes a TensorFold server by swapping the prefix.

Change

  • server/metrics.py (new): Counter, Gauge and Histogram (vLLM's default bucket lists) plus a Metrics container for the Mac server. Counters and histograms are lock-guarded; the exposition follows Prometheus 0.0.4 (label escaping, the +Inf bucket, cumulative bucket counts, _sum/_count).
  • CUDA server
    • cuda/health.py: Request records when it arrived and when its first token arrived; the fold that feeds /health now also observes the TTFT histogram (only when a first token was seen) and the e2e latency histogram (every finished request). New Health.exposition(app): the running/waiting gauges read the engine's own tables (a concurrent engine's decoder streams and prefill plus its scheduler queue; a serialized engine's one in-flight request and its turn queue), the token counters and drafter counters are /health's own numbers, and kv_cache_usage_perc{stream} reports each stream's rows held in its own pool: per-stream pools on concurrent engines, the serialized engine's single pool while a request runs it, omitted when no pool is reachable.
    • cuda/server.py: App.run timestamps each request at entry and passes it to the health context; the token callback stamps the first token exactly once.
    • cuda/http.py: GET /metrics (and /v1/metrics) serve the exposition as text/plain; version=0.0.4; the JSON writer gained a content-type argument with unchanged wire behavior.
    • cuda/scheduler.py: _yield reads the decoder's stream table whether it is a dict (the real engines) or a list (the repo's test fakes); the old code assumed a dict and crashed the scheduler thread the moment the lanes filled with the fakes' list-based decoder.
  • Mac server
    • server/scheduler.py: Scheduler accepts the app's Metrics (default None, so standalone construction is unchanged), and _finish (now an instance method, which the prompt_fill delegation already anticipated) observes TTFT when the prefill completed, e2e latency for every finished job, and the reply's tokens.
    • server/prompt_fill.py: when a job's prefill completes, its whole prompt is counted once in prompt_tokens_total ("prefill tokens processed", as vLLM counts it), so a job cancelled while still queued adds nothing.
    • server/app.py: the app owns the Metrics and hands it to the scheduler; new metrics_text() renders the gauges from the scheduler's own tables and the token counters, and includes the engine's drafter counters when the engine carries them (every lane engine does: an engine with no active drafter reads zero, exactly as vLLM's do with speculative decoding off).
    • server/http.py: GET /metrics and /v1/metrics serve the app's exposition (a handler around an app without metrics_text answers 200 with an empty body); scrapes no longer appear in the request log.
  • docs/api.md: a route-table row and a Metrics section naming each metric, what it reads on each server, and what vLLM reports that stays out and why.

The metric set, under the tensorfold: prefix: num_requests_running (gauge), num_requests_waiting (gauge), prompt_tokens_total (counter), generation_tokens_total (counter), kv_cache_usage_perc{stream} (gauge, 0..1), spec_decode_num_draft_tokens_total (counter), spec_decode_num_accepted_tokens_total (counter), time_to_first_token_seconds (histogram) and e2e_request_latency_seconds (histogram, vLLM's default buckets).

What vLLM reports that stays out:

  • spec_decode_num_drafts_total, on both servers: the engines count drafted and accepted tokens, not draft steps, and the round counter mixes draft and non-draft rounds, so a draft count would be a guess.
  • kv_cache_usage_perc on the Mac server: each stream's cache there grows from the memory budget, so there is no fixed pool to take a fraction of; the metric is omitted rather than read zero.

Clock semantics: on CUDA the TTFT clock starts at the request's arrival in App.run, so queue and turn waits are in, as in vLLM; a reply whose client left before any token took no TTFT observation but still counts in the e2e histogram. On the Mac, TTFT is prefill completion (when the first token is emitted) minus submission. Counters and histograms are cumulative since server start; a stream's kv_cache_usage_perc line disappears when its request ends, and because the label is the request's stream ID a scraper sees one short-lived series per request (at most the engine's stream count at once). Each metric in a scrape is read on its own, not as one atomic snapshot.

Tests

  • tests/prometheus_format.py (new): a strict 0.0.4 parser plus histogram consistency checks, so the endpoint tests parse the servers' actual output instead of eyeballing strings.
  • tests/test_cuda_server_metrics.py (new, 7 tests): the endpoint's names, types and HELP strings against vLLM's; the token counters and both latency histograms fold from real (fake-engine) requests; the running/waiting gauges, including a request queued behind a held one; per-stream KV gauges with a concurrent dict-streams engine (per-stream pools) and a serialized single-pool engine (present while a request runs it, gone when it ends); and the histogram bucket math directly. All 7 pass; the CUDA path is exercised with the repo's fake engines, as the existing CUDA server tests do.
  • tests/test_server_metrics.py (new, 6 tests): the Mac endpoint on a real app (both routes; the plain engine's drafter counters read zero and its KV pool stays out of the body) and with a drafter engine (the counters follow it); the prompt and generation counters and both histograms from a real request through the real scheduler, with the request log silent for scrapes; a job cancelled while queued adds no prompt tokens while a served one counts its prompt once (this test fails if the prompt is counted at submission); the gauges mirroring the scheduler's queue; and counter accumulation.
  • The two new test files each retry the port an ephemeral server binds while it is one a previous test's server used: with SO_REUSEADDR a closing server's port can still accept connections for a moment, and a second server bound to it has half its requests answered by the first test's dying app. Ports are retired for the session.
  • Results (pytest 9.1.1, Python 3.12.3, Linux, no MLX/torch installed; each run under a memory-capped private mount namespace, and the same file sets run on origin/main and on this branch so the results are directly comparable — the full suite on this workstation stalls on a pre-existing slow test, so the runs cover the files that touch the changed modules):
  • CUDA-server files (test_cuda_server_health, test_cuda_server_disconnect, test_cuda_server_errors, test_cuda_server_stream, test_cuda_server_connections, test_cuda_stop_strings, test_cuda_admission, test_cuda_capacity, test_cuda_priority, test_cuda_parallel_admission, test_cuda_nemotron_admission): 463 passed, 66 skipped on origin/main; on this branch the same 463 pass and 66 are skipped, plus the 7 new metrics tests pass.
  • Mac-server files (test_lane_server, test_prompt_fill, test_prefill_cancellation, test_background_free_lane, test_live_line, test_lane_stream_text, test_server_watchdog, test_server_openai_compat, test_server_backlog, test_server_stacks): 22 failed, 69 passed, 6 skipped on origin/main; on this branch the same 22 node-ids fail (all pre-existing ModuleNotFoundError: No module named 'mlx' — the venv has no mlx, and these drive the real prefill path), plus the 6 new metrics tests pass.
  • Disconnect files (test_cancellation, test_cancelled_prefill): identical on both trees: 3 failed, then the run stalls inside test_cancellation::test_streaming_socket_disconnect_during_decode_releases_the_active_row — a pre-existing stall on this workstation (it stalls identically on origin/main); both runs carry a 600 s watchdog on these files.
  • New tests on this branch: tests/test_cuda_server_metrics.py (7 passed) and tests/test_server_metrics.py (6 passed). Two Mac tests drive the real scheduler (one through a real app + HTTP server); off-Mac, the engine's lazy import mlx.core is pointed at a numpy-backed stand-in installed via monkeypatch (the default chat is greedy, so only array/concatenate/argmax arithmetic is involved — the same result Metal gives).
    ruff check reports nothing new on the changed files.

Prepared with AI coding assistants. The change and the test results above were produced and checked locally as described. It has not yet run on GPU hardware.

…t at submission

prompt_tokens_total is 'prefill tokens processed': a job cancelled while
still queued no longer adds its prompt. The docs name the counting rule,
the Mac TTFT population, the per-request stream label and that a scrape
reads each metric on its own.
@ashhart

ashhart commented Sep 30, 2026

Copy link
Copy Markdown
Owner

Thanks, @jeidbugs404, this is thorough work, and the Prometheus 0.0.4 details (label escaping, cumulative buckets, +Inf) are the parts people usually get wrong. 0.6.0, out tonight, already answers #110 with /metrics on both servers, using the names its reporter listed: tensorfold:requests_running and requests_waiting, the prompt and generation token totals, kv_cache_usage_ratio, mtp_drafted_total and mtp_accepted_total, and the latency and time-to-first-token histograms. Your PR mirrors vLLM's names one for one instead (num_requests_running, the spec_decode_* counters), which is what makes a vLLM dashboard work with a prefix swap. That's a real advantage, so for 0.6.1 we'll settle the naming with you and @DakotaTexas and keep what's better from each. It came in at the 0.6.0 freeze, and 0.6.0 has moved a lot since, so we'll do the rebase ourselves in 0.6.1, keeping your commits.

@ashhart

ashhart commented Oct 1, 2026

Copy link
Copy Markdown
Owner

Thanks. This is landed for 0.6.1 as one design on top of 0.6.0's /metrics. Your vLLM names now mirror our tensorfold:* families with identical values, so a vLLM dashboard works with a prefix swap. Your PR rewrote the module from 0.5.0, so it didn't apply as a commit, and the commit message credits you. It ships with 0.6.1, and we'll close this then.

@ashhart

ashhart commented Oct 1, 2026

Copy link
Copy Markdown
Owner

This is in TensorFold 0.6.1, with your commits under your name in the release history: https://github.com/ashhart/TensorFold/releases/tag/v0.6.1

Thank you, @jeidbugs404!

@ashhart

ashhart commented Oct 14, 2026

Copy link
Copy Markdown
Owner

@jeidbugs404, a correction and an apology. When we closed this we said your commits were in 0.6.1 under your name. They weren't: the metrics under vLLM's names went in inside one of our own commits, with no line naming you. That was our mistake.

The native server carries your work today. zig/src/server/metrics.zig writes the vLLM-named mirrors (num_requests_running, kv_cache_usage_perc and the rest) as the Python server did. As of f930fbb you are a co-author on main for it, and the credits page names #156 beside it, with your GLM tool-call parser from #35.

Thank you for the metrics, and sorry it took us this long to put your name on them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Prometheus /metrics endpoint (running/waiting requests, tokens, KV usage)

2 participants