/* core/server/dashboard.cpp -- the web view of a running engine. * * `/` serves the page and `/stats` the JSON it polls (plus `/sessions` and `/graph`). No * framework: the page is a string literal in this file, so there is no asset directory, no build * step that can go stale against the binary, and no network fetch; the engine runs on machines * with no route to a CDN. * * /metrics serves Prometheus, but answering "what is this process doing right now" from it needs a * scrape config, a time-series database and a Grafana dashboard. This is the terminal view's * snapshot (liveview.h, spec §16) in a browser, viewable from another machine. * * The per-position draft panel shows what no pooled metric does: one late draft position * collapsing while the pooled acceptance rate stays plausible. */ #include "server.h" #include "rad_internal.h" #include #include namespace rad { namespace server { /* ================================================================== /stats */ /* One polled object: the scheduler's metrics, the per-position draft table and whatever the * engine's snapshot function provides. Not a stable public API; automation should scrape /metrics. * * Derived rates are the page's job: they are counter differences over wall time, and only the * browser holds both ends of its poll interval. Computing them here would need per-client state. */ /* ------------------------------------------------------------------ /admin/control-vector * * The control vector's runtime switch (core/cvec.h). Turning it on for the next * request costs a boolean: the direction table was uploaded at startup and the per-request mask * is a derived buffer the core fills every step, so there is nothing to rebuild and nothing to * reload. The engine's own log records the load; this records the flip, because a deployment's * answer to "was that text produced with the vector" should not depend on a browser's memory. * * GET reports the state (and is what the Model view renders); POST takes {"enabled": true|false} * and answers with the same object. A deployment with no vector loaded answers 404 on both: it has * no such feature, and its requests refuse `control_vector: true` by name. */ HttpResponse Server::handle_control_vector(const HttpRequest& req) { const bool have = deps_.control_vector.available && deps_.control_vector.available(); if (!have) { /* 404, like a model the server does not serve: the route exists, this deployment has nothing * behind it, and that is what the page tests for before hiding the panel. */ ApiError e; e.status = 404; e.type = "not_found_error"; e.message = "this deployment found no control vector for its model; there is nothing to " "switch"; return error_response(e, req.peer); } if (req.method == "POST") { /* The default applies to every client's requests that name no choice, so a server * started without --api-key takes the change from a loopback client only, as it does a * runtime adapter load. */ if (opt_.api_key.empty() && !req.peer_is_loopback()) { ApiError e; e.status = 403; e.type = "permission_error"; e.message = "without --api-key, the control-vector default is changed only from a " "loopback client; start the server with --api-key to change it from " "elsewhere"; return error_response(e, req.peer); } json body; try { body = json::parse(req.body.empty() ? "{}" : req.body); } catch (const std::exception& e) { return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer); } const auto it = body.find("enabled"); if (it == body.end() || !it->is_boolean()) return error_response(err_bad("enabled", "a boolean is required"), req.peer); const bool on = it->get(); if (deps_.control_vector.set_default) deps_.control_vector.set_default(on); RAD_INFO("control vector: default %s by an admin request%s", on ? "ON" : "OFF", req.peer.empty() ? "" : (" from " + req.peer).c_str()); } metrics_.observe_http(200); return HttpResponse::json_body( 200, deps_.control_vector.json ? deps_.control_vector.json() : std::string("{}")); } /* ------------------------------------------------------------------ /sessions * * A separate route, not a /stats field: /stats is polled every second, while a stored session * changes on the scale of its idle thresholds (tens of seconds at the fastest), and the view that * reads this is usually off screen. */ 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, bytes = 0; int64_t snaps = 0; json a = json::array(); for (const SessionStat& s : v) { json e; e["id"] = s.id; e["model"] = s.model; if (!s.label.empty()) e["label"] = s.label; 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["moving"] = s.moving; /* On a hybrid model a session also needs its linear-state snapshots back: a different * object size, kept in a separate store in host memory. */ e["snapshots"] = s.snapshots; 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; snaps += s.snapshots; bytes += s.bytes; } o["sessions"] = std::move(a); /* Sessions sharing a prefix share its blocks, so these sums over-count (by more than an order * of magnitude with long agent transcripts); the field names say so. */ o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } }; o["snapshots_sum_overlapping"] = snaps; o["bytes_sum_overlapping"] = bytes; const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{}; /* What the card actually holds: the pool counts a block once however many sessions name it, * which the per-session rows cannot yield. Tokens are the binding group's only; see * SchedMetrics::kv_tokens_used for why 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 }, { "promoted", c.promoted }, { "host_drops", c.host_drops }, { "held_back", c.held_back }, { "restore_cuts", sm.prefix_restore_cuts }, { "failures", c.failures } }; /* Snapshot store on a hybrid model: bytes per snapshot and slot count. `bytes_each` is 0 * on a model with no recurrent state. */ o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } }; /* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */ o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } }; /* And the ones a client gave up on purpose (DELETE /sessions). */ o["released"] = { { "entries", sm.prefix_released }, { "snapshots", sm.prefix_ckpt_released } }; /* Step-thread time spent on tier moves; every request waits through it. */ o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 }, { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } }; /* Whether restored snapshots are served. A hybrid server can move snapshots and still replay * from token zero if the restored checkpoint is not one a hit can reach. */ o["linear"] = { { "hit_rate", sm.linear_hit_rate }, { "cached_tokens", sm.linear_cached_tokens }, { "checkpoints_written", sm.checkpoints_written }, { "evictions", { { "retention", sm.prefix_ckpt_retired }, { "store_full", sm.prefix_ckpt_lru } } }, { "refused", sm.prefix_ckpt_refused }, { "hit_cuts", { { "no_snapshot", sm.hit_cut_no_snapshot }, { "windowed_group", sm.hit_cut_window }, { "adopt_failed", sm.hit_cut_adopt }, { "resumed_below", sm.hit_cut_resumed_below } } }, { "hit_cut_tokens", sm.hit_cut_tokens } }; /* Whether a tier exists to move sessions to. A session is recorded whether or not it can be * demoted, so a non-empty table only says something is held. */ o["tiers"] = { { "host", c.host_on } }; /* Off-card bytes, counted once; see SessionOccupancy. */ o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "host_cap_bytes", occ.host_cap_bytes } }; /* The attention hit rate: the whole answer on a model with no recurrent state. On a hybrid * model, read `linear.hit_rate`. */ o["prefix_hit_rate"] = sm.prefix_hit_rate; o["enabled"] = c.host_on; return HttpResponse::json_body(200, json_dump(o)); } /* ------------------------------------------------------------------ DELETE /sessions * * A client that deletes a conversation, or replaces everything past a prefix of it, knows the * rest is dead before the TTL does. Named by the label it sent (`session_id`, or Anthropic's * `metadata.user_id`), or by the engine id `/sessions` shows. `keep_tokens` keeps the chain's * start. Shared blocks and blocks a live request reads stay; a request of the same conversation * in flight is a 409, since its close would publish the chain again. */ HttpResponse Server::handle_session_release(const HttpRequest& req) { if (!deps_.sched) return error_response(err_not_implemented("the server has no engine attached"), req.peer); const std::string label = req.param("label"); uint64_t id = 0; const std::string id_s = req.param("id"); if (!id_s.empty()) { if (id_s.find_first_not_of("0123456789") != std::string::npos || id_s.size() > 19) return error_response(err_bad("id", "expected the session's engine id, a decimal " "integer as /sessions reports it"), req.peer); id = std::stoull(id_s); if (id == 0) return error_response(err_bad("id", "0 names no session"), req.peer); } if (label.empty() && id == 0) return error_response(err_bad("label", "name the session: DELETE /sessions/