/* core/server/dashboard.cpp -- the web view of a running engine. * * Two routes: `/` serves a page, `/stats` serves the JSON it polls. Nothing else, and no * framework: the page is a string literal in this file, so there is no asset directory to install, * no build step that can go stale against the binary, and no network fetch at all. This engine is * deployed on machines with no route to a CDN, and a dashboard that renders blank without one is * a dashboard that does not exist. * * WHY IT IS NOT JUST /metrics. Prometheus exposition is the right answer for an operator who has * a Prometheus, and this server serves it. It is the wrong answer for the question * being asked here -- "what is this process doing right now" -- because getting to that answer * costs a scrape config, a time-series database and a Grafana dashboard somebody has to build. * The engine already has a terminal view for exactly this (liveview.h, spec §16); this is the * same snapshot in a browser, which is where it can be looked at from another machine. * * THE PER-POSITION DRAFT PANEL IS THE POINT. Everything else here is visible in some other tool. * The conditional acceptance at each draft position is not: it is in SchedMetrics and in /metrics * as a labelled gauge, and no ordinary reading of either shows that one late position collapsed * while the pooled rate stayed plausible. As a bar chart it is the first thing seen. */ #include "server.h" #include "rad_internal.h" #include #include namespace rad { namespace server { /* ================================================================== /stats */ /* One object, polled. It carries the scheduler's metrics, the per-position draft table and * whatever the engine's snapshot function could see -- and it is deliberately NOT a stable * public API: /metrics is that, with vLLM's names, and this is free to say whatever the page * needs. A client automating against radiance should scrape /metrics. * * DERIVED RATES ARE THE PAGE'S JOB, not this handler's. Tokens a second and milliseconds a step * are differences of counters over wall time, and the browser has both endpoints of the interval * while this handler has neither -- computing them here would mean holding per-client state for * something the client can subtract. */ /* ------------------------------------------------------------------ /sessions * * ITS OWN ROUTE, not a field in /stats. The dashboard polls /stats every second and a stored * session changes on the scale of its idle thresholds -- tens of seconds at the fastest. Folding * a table of conversations into the per-second poll would carry the same bytes a hundred times * for each change in them, and the view that reads it is not even on screen most of the time. */ HttpResponse Server::handle_sessions(const HttpRequest&) { json o; std::vector v; SessionOccupancy occ; if (deps_.sched) deps_.sched->sessions(&v, &occ); int64_t dev = 0, host = 0, disk = 0, bytes = 0; int64_t sdev = 0, shost = 0, sdisk = 0; json a = json::array(); for (const SessionStat& s : v) { json e; e["id"] = s.id; e["model"] = s.model; e["tokens"] = s.n_tokens; e["bytes"] = s.bytes; e["idle_s"] = s.idle_s; e["age_s"] = s.age_s; e["on_device"] = s.on_device; e["on_host"] = s.on_host; e["on_disk"] = s.on_disk; e["moving"] = s.moving; /* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of * what it needs back; the rest is its linear-state snapshots, which are a different size * of object in a different store. Counted where the BYTES are, so a snapshot that stayed * on the device while its blocks went to disk shows as exactly that. */ e["snapshots"] = s.snapshots; e["snap_device"] = s.snap_device; e["snap_host"] = s.snap_host; e["snap_disk"] = s.snap_disk; e["snap_bytes"] = s.snap_bytes; e["resume_tokens"] = s.resume_tokens; a.push_back(std::move(e)); dev += s.on_device; host += s.on_host; disk += s.on_disk; sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk; bytes += s.bytes; } o["sessions"] = std::move(a); /* SAID HERE SO A READER DOES NOT HAVE TO INFER IT. Two sessions sharing a system prompt share * the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on * a server carrying long agent transcripts by more than an order of magnitude. The field * names say so rather than pretending the sums are totals. */ o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } }; o["snapshots"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } }; o["bytes_sum_overlapping"] = bytes; const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{}; /* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has * to be able to say what the card is actually holding. The pool counts a block once however * many sessions name it, which is the number an operator is asking for and the only one the * per-session rows cannot be made to yield. One group's, the binding one -- see * SchedMetrics::kv_tokens_used for why tokens across paged groups are not additive. */ o["pool"] = { { "tokens_used", sm.kv_tokens_used }, { "tokens_total", sm.kv_tokens_total }, { "unshared_tokens", sm.kv_tokens_cached }, { "bytes_used", sm.kv_bytes_used }, { "bytes_total", sm.kv_bytes_total } }; const IScheduler::TierCounters c = deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{}; o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "to_disk", c.to_disk }, { "promoted", c.promoted }, { "host_freed", c.host_freed }, { "host_drops", c.host_drops }, { "failures", c.failures }, { "fetched", c.fetched } }; /* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every * block it has and no snapshots at all looks identical in the block counters to one where * tiering works -- and the difference is a full linear replay on every restored session. * `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had * no room, which --prefix-cache-host-mib fixes. */ o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk }, { "promoted", c.ck_promoted }, { "fetched", c.ck_fetched }, { "drops", c.ck_drops }, { "starved", c.ck_starved }, { "bytes_each", c.ck_bytes }, { "host_slots", c.ck_host_slots }, { "disk_slots", c.ck_disk_slots } }; /* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes * travelled; this is the number that says a lookup then SERVED one. A hybrid server can move * snapshots all day and still replay from token zero if the checkpoint the restore put back * is not the one a hit can reach. */ o["linear"] = { { "hit_rate", sm.linear_hit_rate }, { "cached_tokens", sm.linear_cached_tokens }, { "checkpoints_written", sm.checkpoints_written } }; /* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded * whether or not it can be demoted, so a non-empty table says only that something is held; * these say whether a tier exists that can move it. */ o["tiers"] = { { "host", c.host_on }, { "disk", c.disk_on } }; /* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */ o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "disk_bytes", occ.disk_bytes }, { "host_cap_bytes", occ.host_cap_bytes }, { "disk_cap_bytes", occ.disk_cap_bytes } }; /* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer * to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */ o["prefix_hit_rate"] = sm.prefix_hit_rate; o["enabled"] = c.host_on || c.disk_on; return HttpResponse::json_body(200, json_dump(o)); } HttpResponse Server::handle_stats(const HttpRequest&) { json o; o["model"] = opt_.model_id; o["version"] = opt_.version; o["uptime_s"] = unix_now() - started_at_; o["in_flight"] = in_flight_.load(std::memory_order_relaxed); o["queue_cap"] = queue_depth_; o["now_ms"] = (int64_t)std::time(nullptr) * 1000; if (deps_.sched) { const SchedMetrics m = deps_.sched->metrics(); o["running"] = m.running; o["waiting"] = m.waiting; o["preempted"] = m.preempted; o["kv_util"] = m.kv_util; o["kv_tokens_used"] = m.kv_tokens_used; o["kv_tokens_total"] = m.kv_tokens_total; /* AND THE PART OF `used` THAT NO RUNNING REQUEST IS READING. Held is held, so a finished * turn's blocks are in the figure above for exactly as long as the cache keeps them -- * and on a server carrying conversations that is most of a full pool. Without the split * a cache doing its job and a pool that never releases draw the same bar. */ o["kv_tokens_cached"] = m.kv_tokens_cached; /* THE POOL IN BYTES BESIDE THE POOL IN TOKENS, because they answer different questions and * only one of them is about the card. Tokens say how much context fits; bytes say how much * VRAM is being held, which is what a reader comparing the cache against the weights and * against the card's total is asking. The two are not a unit conversion of each other: * tokens are the binding paged group's and bytes are every group's, recurrent included. */ o["kv_bytes_used"] = (double)m.kv_bytes_used; o["kv_bytes_total"] = (double)m.kv_bytes_total; o["kv_bytes_carved"] = (double)m.kv_bytes_carved; o["prefix_hit_rate"] = m.prefix_hit_rate; /* The leading indicator beside the lagging one: past ~75% kv utilisation the cache * begins dropping prefixes the next turn wants, and the hit rate only falls once * that has happened. An agent turn that re-prefills from scratch costs orders of * magnitude more than one that resumes from the cache. */ o["prefix_evictions"] = (double)m.prefix_evictions; /* THE LINEAR HALF, WHICH THE ATTENTION HIT RATE SAYS NOTHING ABOUT. On a hybrid model a * prompt can be 100% attention-cached and still re-run every recurrent layer over its * whole prefix, because the two hit at different granularities. Without these a * deployment cannot tell whether linear checkpointing is working at all. Zero throughout * on a model with no recurrent state. */ o["linear_hit_rate"] = m.linear_hit_rate; o["linear_cached_tokens"] = (double)m.linear_cached_tokens; o["checkpoints_written"] = (double)m.checkpoints_written; o["prefill_tps"] = m.prefill_tps; o["decode_tps"] = m.decode_tps; o["draft_accept"] = m.draft_acceptance; o["preemptions"] = m.preemptions; o["total_requests"] = m.total_requests; o["steps"] = m.steps; o["steps_prefill"] = m.steps_prefill; o["steps_mixed"] = m.steps_mixed; o["steps_decode"] = m.steps_decode; /* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count. * That is the derivation this handler's header calls the page's job, and it is the one * derivation the page cannot do: the browser's two endpoints bracket the engine's IDLE * time as well as its work, and an agent client is idle between turns. See * SchedMetrics::step_ns. */ o["step_ns"] = m.step_ns; o["step_ns_decode"] = m.step_ns_decode; o["rows_unspec"] = m.decode_rows_unspeculated; /* THE CONDITIONAL RATE AT EACH POSITION, with the reach count beside it. Both are needed * and neither alone means anything: a position with a rate of 0.0 and a reach of 3 is * noise, and one with a rate of 0.0 and a reach of 40000 is a broken draft round. */ json pos = json::array(); for (int j = 0; j < m.draft_depth_seen && j < SchedMetrics::MAX_DRAFT_POS; ++j) { json p; p["reached"] = m.draft_pos_reached[j]; p["accepted"] = m.draft_pos_accepted[j]; p["rate"] = m.draft_pos_reached[j] > 0 ? (double)m.draft_pos_accepted[j] / (double)m.draft_pos_reached[j] : 0.0; pos.push_back(std::move(p)); } o["draft_positions"] = std::move(pos); /* THE LIVE REQUEST TABLE. Counters and timestamps, not rates the page could not check: * `decode_tps` is this request's own average since its first token, which is the number * that stays meaningful when a request has been running for four minutes. */ std::vector rq; deps_.sched->requests(&rq); json reqs = json::array(); for (const RequestStat& q : rq) { json j; j["id"] = q.id; j["state"] = q.state; j["prompt"] = q.prompt_tokens; j["computed"] = q.computed_tokens; j["cached"] = q.cached_tokens; j["output"] = q.output_tokens; j["max"] = q.max_tokens; j["ctx"] = q.ctx_tokens; j["kv_tokens"] = q.kv_tokens; j["kv_blocks"] = q.kv_blocks; j["draft"] = q.n_draft; j["slot"] = q.slot; j["age_s"] = q.age_s; if (q.ttft_s >= 0) j["ttft_s"] = q.ttft_s; j["tps"] = q.decode_tps; reqs.push_back(std::move(j)); } o["requests"] = std::move(reqs); } /* The engine's half. Absent when nothing supplied a snapshot function, in which case the page * omits the panels rather than drawing zeroes -- an empty VRAM bar reads as "no memory used", * which is a much worse answer than no bar. */ if (deps_.live) { LiveSnapshot s; deps_.live(s); json cards = json::array(); for (const CardStat& c : s.cards) { json k; k["index"] = c.index; k["name"] = c.name; k["vram_used"] = c.vram_used; k["vram_total"] = c.vram_total; /* 0 means "not sampled" for these three; the page shows nothing rather than a zero. */ if (c.util > 0) k["util"] = c.util; if (c.power_w > 0) k["power_w"] = c.power_w; if (c.temp_c > 0) k["temp_c"] = c.temp_c; cards.push_back(std::move(k)); } o["cards"] = std::move(cards); /* THE EXPERT PANEL'S DATA. The plane is the picture; everything beside it is what the * picture cannot say -- how much of the model is resident in BYTES, whether the residency * is spread across layers or piled into the first ones, and whether the move traffic is * discovery or thrash. Counted in the engine (liveview.h), not here and not in the page: * three tallies of one snapshot is three chances to disagree. */ if (s.experts.n_layers > 0 && s.experts.n_experts > 0) { json e; e["n_layers"] = s.experts.n_layers; e["n_experts"] = s.experts.n_experts; e["tier"] = s.experts.tier; e["n_units"] = s.experts.n_units; e["bytes"] = s.experts.total_bytes; e["movable"] = s.experts.movable; e["heat"] = s.experts.heat_enabled; /* One row per tier, named -- the page must not hold its own copy of the enum's order, * which is the kind of duplication that survives a reordering and then lies. */ json tiers = json::array(); for (int t = 0; t < kTierCount; ++t) { json r; r["name"] = tier_name((Tier)t); r["units"] = s.experts.units[t]; r["bytes"] = s.experts.bytes[t]; tiers.push_back(std::move(r)); } e["tiers"] = std::move(tiers); e["layer_units"] = s.experts.layer_units; e["layer_resident"] = s.experts.layer_resident; e["promotions"] = s.experts.promotions; e["demotions"] = s.experts.demotions; e["distinct_promoted"] = s.experts.distinct_promoted; e["readmits"] = s.experts.readmits; e["routed"] = s.experts.routed; e["routed_res"] = s.experts.routed_resident; e["dispatches"] = s.experts.dispatches; e["refused"] = s.experts.refused; e["no_candidate"] = s.experts.no_candidate; e["no_record"] = s.experts.no_record; e["starved_slab"] = s.experts.starved_slab; e["flex_bytes"] = (double)s.experts.flex_bytes; e["flex_capacity"] = (double)s.experts.flex_capacity; e["starved_pool"] = s.experts.starved_pool; e["quarantined"] = s.experts.quarantined; e["stage_layers"] = s.experts.stage_layers; e["staged_units"] = s.experts.staged_units; e["staged_bytes"] = (double)s.experts.staged_bytes; e["stage_overflow"] = s.experts.stage_overflow; o["experts"] = std::move(e); } /* THE LINK. Cumulative byte counters and nothing derived: both ends of the poll interval * are in the browser and neither is here, exactly as for step time above. */ if (s.link.present) { json l; l["world"] = s.link.world; l["ar_calls"] = s.link.ar_calls; l["ar_bytes"] = s.link.ar_bytes; l["h2d_bytes"] = s.link.h2d_bytes; l["d2h_bytes"] = s.link.d2h_bytes; l["ssd_reads"] = s.link.ssd_reads; l["ssd_bytes"] = s.link.ssd_bytes; l["prefetched"] = s.link.prefetched; l["prefetch_bytes"] = s.link.prefetch_bytes; l["staged_bytes"] = s.link.staged_bytes; l["stream_bytes"] = s.link.stream_bytes; o["link"] = std::move(l); } if (s.passes.present) { json p; p["played"] = s.passes.played; p["recorded"] = s.passes.recorded; p["audited"] = s.passes.audited; p["issued_unkeyed"] = s.passes.issued_unkeyed; p["issued_refused"] = s.passes.issued_refused; p["issued_first"] = s.passes.issued_first; p["dispatched"] = s.passes.dispatched; p["unordered"] = s.passes.unordered; o["passes"] = std::move(p); } } /* No metrics_.observe_http here, and the same reasoning as /health: a page polling twice a * second would make request_success_total a statement about the dashboard. */ return HttpResponse::json_body(200, json_dump(o)); } /* ================================================================== /graph */ /* THE DECLARED COMPUTE GRAPH: every op, its bucket table, the kernel that resolved each band, the * library it came from, the constraints it matched on and the chain it stands in for. * * `--debug-graph` prints all of this, but printing it is not the same as being able to look at it: * the text dump answers the question on a terminal, at startup, on the machine the engine is on. * This is the same walk (dump_graph_json shares every helper with the text one) served from the * process that is actually running, which is where the question is usually asked. Static after * declare, so it is rendered once and handed over. */ HttpResponse Server::handle_graph(const HttpRequest& req) { if (!opt_.graph_json) return error_response(err_not_implemented( "the server was not given a declared graph; this build has no engine attached"), req.peer); HttpResponse r; r.status = 200; r.body = opt_.graph_json(); return r; } /* ================================================================== the page */ /* One string. It is long, and every alternative is worse: a file on disk is a file that can be * missing or stale against the binary, a generated header is a build step, and a framework is a * network fetch. It parses no untrusted input -- every value it renders comes from /stats on the * same origin and goes in through textContent or a numeric attribute, never innerHTML. * * IT IS BUILT ONCE AND UPDATED IN PLACE. A dashboard that rebuilds its DOM twice a second lays * the document out twice a second, drops the reader's text selection every time, and flickers -- * and it does that on the machine the engine is being watched from. Elements are created when * their SHAPE changes (a different draft depth, a different card count) and after that only * textContent and one style property are written. * * The design rules are the terminal view's (spec §16) in a browser: a number nobody sampled is * blank rather than zero, a section with no data is hidden rather than empty, and nothing moves * that is not actually changing. Black, one weight, one accent -- the numbers are the content and * everything else on the page is there to not compete with them. */ static const char* const kPage = R"HTML( radiance

radiance

–ms
decode step
–tok/s
decode
–tok/s
prefill
–
requests in flight
–
kv cache in vram
–%
acceptance
Requests
nothing in flight
Batch
decode prefill waiting preempted free
Admission queue
–
Memory
)HTML"; HttpResponse Server::handle_dashboard(const HttpRequest&) { HttpResponse r; r.status = 200; r.content_type = "text/html; charset=utf-8"; r.body = kPage; /* No caching: the page and the binary ship together, so a browser holding yesterday's copy * against today's /stats is a shape mismatch with no symptom other than blank panels. */ r.set_header("Cache-Control", "no-store"); return r; } } /* namespace server */ } /* namespace rad */