Observability
Use this reference to configure logs, metrics, traces, and KV cache events, and to interpret request and PD lifecycle measurements.
The following table summarizes the observability command-line parameters:
| Parameter | Purpose |
|---|---|
--log-level | Engine logging threshold for Python, the Rust host, and the C++ scheduler. Python critical/fatal maps to Rust error, its highest severity. Explicit TS_HOST_LOG and SPDLOG_LEVEL settings override their native writers. |
--enable-async-logging | Write Rust host and default Python root logs on background threads. Defaults to off; --no-enable-async-logging explicitly selects synchronous output. |
--enable-log-request-stats, --enable-request-time-stats-logging | Log a one-line per-request performance summary on finish/abort. For details, see Per-request stats. |
--enable-metrics | Enable the selected metrics reporters. |
--metrics-reporters | Select prometheus or an installed metric output; repeat for multiple. Defaults to prometheus. |
--metrics-reporter-config | JSON file mapping external reporter names to their settings. See metric output plugins. |
--metrics-port | Port for the engine's /metrics HTTP endpoint. Defaults to an automatically allocated free port (logged at startup). |
--metrics-host | Bind host for the /metrics endpoint. Defaults to --host. |
--decode-log-interval | Decode batch log interval. |
--kv-events-config | JSON config for KV cache mutation events. Set enable_kv_cache_events and a publisher such as zmq to publish device prefix-cache stores and removals. |
--otlp-traces-endpoint | OTLP/HTTP traces endpoint (a collector's /v1/traces, Jaeger, Langfuse). Each finished request exports one span built from its lifecycle timestamps. |
--trace-sample-ratio | The share of requests the OTLP endpoint traces (0..1). 0, the default, disables tracing. |
Every --decode-log-interval decode rounds the scheduler's representative rank prints one Decode batch. line: #running-req, avg_seq_len (the mean of prompt plus generated tokens over the running requests, so a step's attention cost can be read alongside its batch size), device page usage, the generation throughput accumulated since the previous line, avg_accept_len / accept_rate under speculative decoding, and #queue-req. Every field is a host-side scheduler counter. The line adds no GPU synchronization.
Logging is synchronous by default. With --enable-async-logging, the Rust host's tracing output and the default Python root logger each use a queue of at most 8,192 records. A background thread owns writes and flushes, so an occasional slow write to a distributed file system or collector does not hold the thread emitting the log. When a queue fills, new records are dropped without writing a synchronous overflow warning. This removes output stalls from the serving thread; it does not increase the sink's throughput.
The host explicitly drains Python logs on both normal and error returns, before notifying the launcher of a failure; it does not rely on Python interpreter finalization. Python cleanup waits up to five seconds, and the Rust appender also performs a bounded, best-effort drain on exit. A sink that remains blocked through shutdown can lose pending records.
Colorful Python loggers retain their direct handlers. Custom handlers remain under TOKENSPEED_LOGGING_CONFIG_PATH control: combining that variable with --enable-async-logging is rejected. Configure asynchronous handlers in the custom file, or use the default configuration with this flag.
#queue-req counts requests admitted to the scheduler but not yet running. On a PD engine that includes requests still bootstrapping with the peer — on the prefill role, waiting for the decode side to allocate their KV pages — which the #req-state(bootstrap/prefill/remote-prefill/decode/pd-pinned) suffix also lists on its own. The Prometheus waiting gauge and the router load snapshot report the scheduler's narrower waiting count, without the bootstrapping share. Under --disaggregation-decode-allocation-policy deferred a prefill request bootstraps only until the prefill server admits it, which does not wait for the decode allocation; a computed prompt then stays in the prefill share until its destination is allocated and its transfer starts (P/D admission).
tokenspeed:request_queue_time_seconds is the Prometheus per-request queue-wait histogram (--enable-metrics): the wall time from a request's submission to the scheduler's waiting queue to its first dispatch into a forward batch, observed once per request. The enqueue point is submission — frontend and IPC wait are not included, and neither are the waits that precede submission: a structured-output request's grammar-compile wait (readiness gates submission), a pause admission hold, and an EPD embedding wait all stay out of the sample. A request preempted by capacity retraction re-enters the queue without recording a second sample. Under prefill/decode disaggregation each node records its own leg: the prefill node's sample spans its queue admission to the prefill batch, the decode node's its own admission to the decode batch. Bucket boundaries span 0.3 s to 7680 s.
Set TOKENSPEED_LOG_SPEC_ACCEPT_LENGTHS=1 to log each speculative verify step's committed widths and accepted draft-token counts. This reads the already-synchronized CPU result and does not add a GPU synchronization, but it is intentionally verbose. Enable it only while debugging. For decode-only batches it also logs the anchor, draft candidates, target verify tokens, and their position-wise matches.
Set TOKENSPEED_VALIDATE_PAGE_IDS=1 to check every page ID in each forward's block tables against its cache group's page range before the forward runs. The structural checks (cache groups, dtype, shape, rows) always run; the scan reads every ID of every scheduled row, which at long contexts costs as much as the rest of the forward thread's table packing, so it is off by default. Enable it while debugging a page-table fault. The model executor reads it once at startup. Prefill-graph capture scans the tables it builds either way.
To send observations to another monitoring system, install and select a metric output plugin. Selecting only external outputs does not start a Prometheus endpoint.
Prometheus metrics
With --enable-metrics and the prometheus reporter, every engine rank on a node writes its metrics to a node-local PROMETHEUS_MULTIPROC_DIR, and the node's launcher process aggregates and serves them as GET /metrics in Prometheus text format. Scrape it at http://<metrics-host>:<metrics-port>/metrics; the bound address is logged at startup. Scrape traffic shares nothing with the request path — a bind failure degrades to an error log and serving continues.
Where the endpoint lives depends on the launch mode:
- Single node /
ts serve: the engine's launcher process serves/metricson--metrics-port(an allocated free port if unset).ts servepins this port itself and printsengine metrics available at http://...once ready. The gateway's own router metrics are separate: smg serves them on its--prometheus-port, whichts servealso allocates per launch. - Multi-node: every node's launcher serves its own node's
/metricsthe same way. Scrape every node — the multiprocess directory is node-local, so no single endpoint covers the whole cluster.
Request metrics
The engine exports the scheduler's view of a request: the queue wait (tokenspeed:request_queue_time_seconds), the running, waiting, and inflight gauges, and the preemption and abort counters. Latency from the client's side (time to first token, inter-token latency, and end-to-end latency) and the per-request finish counts are the frontend's: under ts serve, SMG's router metrics on its --prometheus-port.
tokenspeed:num_requests_running counts the rank's running batch: local prefill forwards, prompts whose prefill is done (about to decode on a fused rank, or awaiting the PD transfer on a prefill rank), and decode rows. On a decode rank it includes requests whose KV has landed but that are waiting for an execution permit; it excludes RemotePrefilling requests waiting for the prefill peer's KV. With extra resident slots, this gauge can exceed the execution batch limit. The decode batch line's #running-req remains the actual number of rows dispatched. tokenspeed:num_requests_inflight counts every request the rank admitted and has not finished, including the scheduler's waiting and retracted requests and the PD states the batch excludes — a decode rank's RemotePrefilling and PdTransferring requests wait for the prefill node's KV and take no batch row. On a PD decode rank the inflight gauge therefore exceeds the running gauge while prompts wait for transfer. The inflight gauge also includes unadmitted work, so it does not measure request-slot occupancy.
Three additional rank-local gauges expose the decode capacity split:
| Metric | Meaning |
|---|---|
tokenspeed:num_requests_resident | Requests holding a request-pool slot, bounded by B + E. Includes slots still held while a finished request's work drains. |
tokenspeed:num_active_decode_slots | Execution permits held by requests or their in-flight work, bounded by B. Includes permits reserved for restore and permits awaiting the final forward result. |
tokenspeed:num_decode_ready_waiting_reqs | Resident requests whose KV is ready but that have no execution permit. |
The decode line reports these as #slots(resident/active-decode/ready-waiting). For B=36 and E=128, sustained resident=164 proves the resident pool is full; active-decode=36 proves the execution permits are occupied. Use the actual batch row count and throughput alongside these counters: draining or restoring work can hold a permit without dispatching a row that round.
Ready-waiting counts only resident PrefillDone requests waiting for their first decode. It excludes Retracted requests whose snapshots are on Host, as well as Restoring and Finishing requests. On PD nodes, tokenspeed:num_retracted_queue_reqs tracks Retracted and Restoring requests separately.
The rank-local histogram tokenspeed:decode_ready_wait_seconds measures E-queue wait from the decode host observing complete prefill KV arrival to the first decode forward dispatch. It records once per request, including requests that dispatch immediately, and excludes requests cancelled or finished before decode. This wait is inside the decode role's time to first token and outside its decode time. It excludes prefill computation and KV transfer; dispatch is the host boundary, not a GPU kernel start timestamp. The 0.1-second bucket measures how many observed waits meet a 100 ms target. Requests still waiting have no histogram observation yet; read it alongside tokenspeed:num_decode_ready_waiting_reqs.
The decode role splits that PD wait into its own gauges. tokenspeed:num_decode_kv_wait_reqs counts RemotePrefilling requests: the prefill peer is working, this rank already holds their destination pages, and nothing here is schedulable until the bootstrap token arrives. tokenspeed:num_decode_prealloc_queue_reqs counts the earlier wait for the peer to connect; when the prefill server runs deferred it also counts the requests waiting for that server's notice (its queueing and computation). tokenspeed:num_decode_transfer_queue_reqs counts requests whose pages a transfer still pins, including requests that already ended (aborted or failed) and are only waiting for the transport to report stopped; it is a resource count, not a queue depth. The transfer gauge is a superset of num_decode_kv_wait_reqs: every waiting request's destination pages are pinned by its inbound transfer, so do not add the two. Use num_decode_kv_wait_reqs for "waiting for KV", and num_requests_inflight for the rank's total held requests. tokenspeed:num_requests_waiting is the scheduler's narrower waiting queue, without the PD bootstrapping share (see the preceding description of #queue-req). All of these carry the dp_rank label and are per scheduler rank.
The scheduler process exports tokenspeed:num_preemptions_total: requests preempted by a capacity retraction — suspended with their pages imaged to the Host snapshot pool (they resume by restore; nothing is recomputed) to free Device pages for a blocked admission. One increment per retraction victim, counted from the plan's snapshot-store ops; forced retractions from --debug-force-retraction-interval count too. A retraction whose victim cannot be imaged aborts it instead — those are tokenspeed:num_capacity_aborted_requests, never preemptions. A forced retraction's victim refused after its pages were published is aborted and counts there too.
OTLP tracing
--otlp-traces-endpoint exports one span per request to an OTLP/HTTP receiver, assembled at the request's release from the same timestamps the stats line prints — the serving loop never blocks on it, a full export queue drops spans and counts them, and --trace-sample-ratio bounds the share. A request that names a continual-prompting session (session_params.id) carries it as the session.id attribute, so a tracing UI groups one conversation's requests under the session. Trace IDs derive from the request ID, so a span, its Req: … Finish! line and its Prometheus samples cross-reference. The span carries the GenAI attribute conventions (gen_ai.request.model, prompt and completion tokens, and finish reason) plus the cached prompt tokens and preemption counts, with the lifecycle points as time-stamped events. See the tracing design.
Request lifecycle logs
Search the engine logs for a request ID to follow it across roles. For example, rg -F 'chatcmpl-019ef6b7' prefill.log decode.log finds both sides of a disaggregated request when the frontend uses the same ID. The PD events also carry bootstrap_room to correlate peers that use different request IDs.
The following table describes the request lifecycle log events:
| Event | When it appears | Fields besides rid |
|---|---|---|
ts_request_accepted | The engine registers the request. | Role, session ID when present, input tokens, and effective maximum new tokens |
ts_prefill_kv_transfer_queued | A prefill rank queues the final KV chunk for a data transfer. | Bootstrap room, rank, token range [start_idx, end_idx), and block count across cache groups |
ts_decode_kv_transfer_success | The decode replica confirms receipt of KV and the bootstrap token. | Bootstrap room, rank, cached tokens, and output token count |
ts_decode_kv_transfer_failed | The decode replica confirms transfer failure. | Bootstrap room (also retained as room for compatibility), rank, and failure reason when available |
ts_request_finished | The engine releases the request or refuses it at admission. | Role, prompt, cached and completion token counts, finish and abort reasons, e2e_latency_s when the frontend supplied a creation time, and optional request_stats |
These events are enabled for every request at the default INFO log level, with WARN for a failed transfer. They are independent of the request-stats flag. Request admission and completion use the same logging ranks as the per-request stats. Each PD role records its own completion time. Ingress refusals have a finish event only. A duplicate-ID refusal logs a finish event for the rejected submission with an abort reason; the original request with that ID remains live and emits its own finish event later.
Logging uses synchronous writers by default. --enable-async-logging moves Rust and Python root logger writes to bounded background queues; C++ scheduler logs still write synchronously. Formatting and queueing cost CPU time, and full asynchronous queues can drop records.
For a first successful prefill admission, set TOKENSPEED_PREFIX_CACHE_DIAGNOSTICS=1 to include the Device and Host contributions to the prefix hit in [PrefixCacheDiagnostic]. Their sum is the resumed token count. host_gain_tokens measures the extra reusable prefix beyond a device-only match. At DEBUG, the native client logs the chosen engine and routing policy by request ID. Scheduler diagnostics (SPDLOG_LEVEL=debug) report restore and decode preallocation waits, and link L3 prefetch queries, reads, and timeouts to the request ID.
PD phase metrics
Every PD request records its first local lifecycle timestamps on a monotonic clock, independently of metrics and logging. The timestamps remain with the request until release. Replanning, resubmission, and subsequent streamed outputs do not overwrite them. Plain-role requests keep no PD timing state.
With --enable-metrics, the engine exports the following per-request phase histograms independently of log level. Each completed phase contributes one observation in seconds when its ending milestone is reached. Unreached boundaries contribute no observation; a measured zero duration remains a zero observation. Repeated plans, dispatches and chunks do not create duplicate phase samples.
| Metric | Role | Boundaries |
|---|---|---|
tokenspeed:pd_bootstrap_wait_seconds | P/D | submitted to bootstrapped |
tokenspeed:pd_prefill_schedule_wait_seconds | P | bootstrapped to first_planned |
tokenspeed:pd_prefill_dispatch_wait_seconds | P | first_planned to first_dispatched |
tokenspeed:pd_prefill_time_seconds | P | first_dispatched to prompt_done, including all chunks and host waits |
tokenspeed:pd_prefill_kv_transfer_tail_seconds | P | prompt_done to P transfer_done; earlier overlapping transfer is excluded |
tokenspeed:pd_decode_kv_reserve_wait_seconds | D | bootstrapped to remote_admitted, when KV landing pages are reserved |
tokenspeed:pd_decode_kv_arrival_wait_seconds | D | remote_admitted to D transfer_done; includes preparation, P execution, and transfer |
With early PD allocation, the first three P phases split the scheduler-submission-to-dispatch interval of tokenspeed:request_queue_time_seconds. With deferred allocation, P can compute immediately after submission and has no bootstrap-complete boundary. Its bootstrap-wait and schedule-wait phases are therefore absent, not zero; its dispatch, prefill, and transfer-tail phases remain available. Those remaining phases do not decompose the full queue interval. RequestStats.queue_ms additionally includes the interval before scheduler submission. On D, the reserve and arrival phases precede tokenspeed:decode_ready_wait_seconds, which measures complete KV arrival to first local decode dispatch. Do not add parent phases and their subdivisions, or add independently computed phase quantiles.
For short diagnostic runs, TS_HOST_LOG=info,ts_pd::decode=debug,ts_pd::prefill=debug,_host::data_plane=debug also reports D route lookup, manifest queueing, P manifest receipt and validation, and the forward thread's Execute queue duration. Correlate Execute records by their request IDs and manifest records by room and cache incarnation within the same deployment and time window. A queued manifest is not yet delivered. The D route and connection durations are cumulative from connection setup; route resolution may use a cached route. P accepts a complete bootstrap only after all expected manifests arrive. Execute queue time ends when the forward thread dequeues the plan, before dependency waits, metadata work, or GPU execution.
Per-request stats
--enable-log-request-stats adds a request_stats field to the existing ts_request_finished event for registered requests. There is one finish log record per completion. The field retains the Req: <rid> Finish! RequestStats(...) text, including the speculative acceptance average as acc_len. With the flag off, the finish event still appears without detailed stats. The scheduler derives the stats from host-side timestamps and counters, adding no GPU synchronization; formatting and writing the log still have a CPU cost. Example request_stats value:
Req: chatcmpl-019ef6b7 Finish! RequestStats(status='finished', reason='stop', prompt_tokens=28684, cache_tokens=832, output_tokens=33, cache_hit_rate=0.029, queue_ms=13.8, prefill_ms=15.8, decode_wait_ms=0.0, ttft_ms=42.1, total_ms=58.0, preempt_ms=0.0, preempt_count=0, decode_tps=2012.6, acc_len=None, acc_rate=None, recv_ts=1782255696.726, commit_ts=1782255696.74, finish_ts=1782255696.784)The following table defines the fields in request_stats:
| Field | Meaning |
|---|---|
status / reason | finished vs aborted; finish-reason type (stop/length/abort). |
prompt_tokens / cache_tokens / output_tokens | Prompt tokens, prefix-cache-hit tokens, generated tokens. |
cache_hit_rate | cache_tokens / prompt_tokens (0–1). |
queue_ms | Request-supplied created_time → first dispatch into a forward batch. Includes time before Rust registration; differs from the submitted → dispatch metrics histogram. |
prefill_ms | Scheduled → prefill complete. Always 0 on a decode node, whose prompt is prefilled on the prefill node. |
decode_wait_ms | Decode nodes only: KV (with the bootstrap token) landed → first decode batch dispatch. 0 elsewhere. This wait is inside ttft_ms and outside the decode window. |
ttft_ms | Request-supplied created_time → this role's first output token. On a decode node the endpoint is the first local decode output, or the bootstrap token when that token ends the request; the remote bootstrap token's landing only starts decode_wait_ms, so a wait for a decode execution permit is included. |
total_ms | Request-supplied created_time → finished/aborted. |
preempt_ms / preempt_count | Wall-clock this request's decode was delayed by prefilling other requests, and the number of such interruptions. Host-side best-effort. |
decode_tps | Decode throughput (generated tokens / decode window). On a decode node the window starts at the first local decode output, so queue, prefill, and the decode admission wait are excluded. The bootstrap token and the first local token are delivered together, so the metric counts one zero interval: it is the client-observed average, not the local decode step rate. |
acc_len / acc_rate | Spec-decode acceptance length and rate (None when speculative decoding is off). |
recv_ts / commit_ts / finish_ts | Absolute epoch timestamps for request-supplied creation / first dispatch / finish. recv_ts is copied from created_time, not stamped by the Rust transport. |
KV cache events
KV cache events publish reusable prefix-cache mutations from the live C++ scheduler path, on two media: the GPU cache (no medium) and, with Host L2 (--enable-kvstore), the pinned Host cache (medium CPU_PINNED). The scheduler caches block hash lineage on prefix-cache nodes, so publishing a stored block uses the parent node's cached hash instead of rebuilding the full ancestor prefix.
Each medium's stream is prefix-closed for a router that continues a GPU match into the Host tier: a GPU block is stored once its parent is stored on the GPU, and a Host block once its parent is stored on either medium. A block on both media is stored on each. Under --kvstore-write-policy write_back, a block the GPU evicts is reported BlockRemoved on the GPU and, once its copy lands, BlockStored on the Host. A Host block read from L3 for a prefix this engine never published carries no tokens to describe it and publishes nothing.
The following example enables ZMQ publication on tcp://*:5557 with the kv-events topic. Replace the endpoint and topic with the values for your deployment:
--kv-events-config '{"enable_kv_cache_events":true,"publisher":"zmq","endpoint":"tcp://*:5557","topic":"kv-events"}'The ZMQ publisher sends three frames: topic bytes, an 8-byte big-endian sequence number, and a msgpack payload. The payload is an array-like KVEventBatch:
[timestamp, [["BlockStored", [block_hash, ...], parent_hash, token_ids, block_size, None, medium]], attn_dp_rank]
[timestamp, [["BlockRemoved", [block_hash, ...], medium]], attn_dp_rank]This is vLLM's layout: the None is lora_id, and medium is None for the GPU cache, "CPU_PINNED" for the Host cache, or "DISK" for the Disk tier. Each BlockStored or BlockRemoved event may carry multiple block hashes (for BlockStored, block_hashes forms a linear parent -> child chain whose first block's parent is parent_hash, and token_ids is the concatenated token list across those blocks).
With attention data parallelism, each attention DP rank publishes on an offset port from the configured endpoint.
By default, the publisher coalesces single-round BlockStored linear parent -> child chains and contiguous same-medium BlockRemoved runs into multi-block wire events without adding cross-round batching delay, preserving phase boundaries and cross-medium parent-first / leaf-first ordering. TOKENSPEED_KV_EVENT_COALESCE_MAX_BLOCKS sets the maximum blocks per merged wire event (default 128, valid range 0..=1024). Subscribers that assume one block per event can roll back to byte-identical single-block payloads by setting TOKENSPEED_KV_EVENT_COALESCE_MAX_BLOCKS=1 (or 0). Malformed or out-of-range values fail startup.
PD KV transfer metrics
In a PD-disaggregated deployment (--disaggregation-mode prefill / decode), both engine roles record KV cache transfer metrics when metrics are enabled (--enable-metrics --metrics-reporters prometheus). The following table describes the three metrics, which all carry the model_name and app_key labels:
| Metric | Type | Meaning |
|---|---|---|
tokenspeed:kv_transfer_latency_seconds | Histogram | Wall time of one KV transfer send to a peer, recorded on the prefill node (one sample per peer per transferred chunk — per layerwise interval in layerwise mode, except an interval with nothing for that peer; buckets span 1 ms to 60 s). |
tokenspeed:kv_transfer_timeouts_total | Counter | Transfers that timed out, with a bounded stage label: bootstrapping (prefill never received the cache manifest; TOKENSPEED_DISAGGREGATION_BOOTSTRAP_TIMEOUT), waiting_for_admission (decode never published its manifest; TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT), or waiting_for_input (decode never received the transfer-done signal; TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT). |
tokenspeed:kv_transfer_failures_total | Counter | Transfers aborted on failure: send failures on the prefill node, and rooms failed on prefill-node loss (heartbeat) on the decode node. Timeouts are counted separately. |
Every prefill server states its policy (P/D admission) in what it registers with the bootstrap server (decode_allocation_policy, served to Decode servers as prefill_decode_allocation_policy in /route).
Under deferred, requests enter tokenspeed:num_requests_waiting directly; tokenspeed:num_prefill_prealloc_queue_reqs stays zero. A computed prompt waiting for its destination counts in tokenspeed:num_requests_running, as one awaiting its PD transfer does: both hold their pages and request slot.