Merge main into laya-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-29 13:45:18 -04:00
commit ec243c2a7d
189 files changed
+11212 -7060

No files matched your search

+3 -1
View File
@@ -506,7 +506,9 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
return error_response(err_not_implemented(
"the server was not given a diagnostics provider; this build has no engine attached"),
req.peer);
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
/* A cross-origin browser is not a loopback client even when its own machine serves
* this port: the drive-by that guard exists to refuse. */
ApiError e;
e.status = 403;
e.type = "permission_error";
+100 -36
View File
@@ -13,6 +13,7 @@
* collapsing while the pooled acceptance rate stays plausible.
*/
#include "server.h"
#include "oai.h"
#include "rad_internal.h"
@@ -57,8 +58,10 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
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()) {
* runtime adapter load. A browser page on another origin does not qualify even when the
* victim's own browser makes it loopback: that is the drive-by this guard must refuse.
*/
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) {
ApiError e;
e.status = 403;
e.type = "permission_error";
@@ -67,12 +70,12 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
"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);
}
bool over = false, deep = false;
json body = parse_json_bounded(req.body.empty() ? "{}" : req.body, 0, &over, &deep);
if (body.is_discarded()) return error_response(err_bad("body", "not JSON"), req.peer);
if (over || deep)
return error_response(err_bad("body", "expected {\"enabled\": true|false} and "
"nothing deeper than that"), 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);
@@ -462,6 +465,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
l["prefetch_bytes"] = s.link.prefetch_bytes;
l["staged_bytes"] = s.link.staged_bytes;
l["stream_bytes"] = s.link.stream_bytes;
l["kv_stream_bytes"] = s.link.kv_stream_bytes;
l["kv_streaming"] = s.link.kv_streaming;
l["kv_stream_active"] = s.link.kv_stream_active;
o["link"] = std::move(l);
}
if (s.passes.present) {
@@ -1182,7 +1188,7 @@ nav button.on { color:var(--fg); background:var(--track); }
otherwise have had, and a percentage of the paged pool's token capacity says nothing
about it: it is a preemption signal, so it is kept, underneath, where it reads as one. -->
<div class="cell"><div class="n" id="m-kv">–<u></u></div>
<span class="cap">kv cache in vram</span>
<span class="cap" id="m-kvcap">kv cache in vram</span>
<span class="det" id="m-kvdet"></span>
<svg viewBox="0 0 200 22" preserveAspectRatio="none"><path/></svg></div>
<div class="cell"><div class="n" id="m-accept">–<u>%</u></div>
@@ -1353,7 +1359,7 @@ nav button.on { color:var(--fg); background:var(--track); }
<span class="cap">conversations can resume</span>
<span class="det" id="s-livedet"></span></div>
<div class="cell"><div class="n" id="s-vram">–<u>tok</u></div>
<span class="cap">context in vram</span>
<span class="cap" id="s-vramcap">context in vram</span>
<span class="det" id="s-vramdet"></span></div>
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
<span class="cap">moved to host ram</span>
@@ -1638,6 +1644,9 @@ const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll;
const RECENT_PREFILL = 10; /* 5 s */
const extAt = {}, winAt = {};
let lastActiveC = 0;
/* Whether the server streams its KV (--kv-resident). Settled at bringup, so it cannot change under
* a running page: the cells that name a memory tier read it instead of guessing. */
let kvStreamOn = false;
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
* `highest` from extAt. */
function noteSample(key, c, value, cap, win) {
@@ -1867,7 +1876,7 @@ const linkSegs = segs("linkbar", "linkrows");
* own mapping, read in place -- so it is the one that is not a grey. */
const TIER_INK = ["#f5f5f5", "#9a9a9a", "#5e5e5e", "#2b2b2b", "#3f6fa8"];
const INK_AR = "#60a5fa", INK_UP = "#4ade80", INK_DOWN = "#fbbf24", INK_SSD = "#a78bfa";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf", INK_KV = "#fb923c";
/* The plane is painted as raw pixels, so the same inks are wanted as RGB triples. Parsed from
* TIER_INK rather than written out a second time: two lists of five colours is one list that
* will drift, and the drift is a legend that names the wrong band of the picture. */
@@ -2243,7 +2252,13 @@ function update(s, dt) {
* wrong headline: the drafter's own window group is sized one block-run per slot and therefore
* sits at 100% for the whole life of the server, so a headline reading the max reads 100% on a
* server using 4% of its cache. */
const kvFrac = s.kv_tokens_total > 0 ? s.kv_tokens_used / s.kv_tokens_total : 0;
/* ONE UNIT FOR ONE METER. The figure is bytes -- every group's, which is the only unit groups
* can be summed in -- and the bar used to be TOKENS, the binding group's. Groups hold different
* bytes per token, so the two were answering at different rates: the figure reached its total
* while the bar was half full and then the figure stood still while the bar went on climbing.
* A streamed group's host mirror, whose pages arrive in their own order, made the gap wide
* enough to read as a bug, and it was one. Both are bytes now, and the percentage is the bar. */
const kvFrac = s.kv_bytes_total > 0 ? (s.kv_bytes_used || 0) / s.kv_bytes_total : 0;
/* HELD, NOT READ. A finished turn's blocks stay held by the prefix cache so the next turn can
* reuse them, and they occupy the card for exactly as long as they are held -- so they belong
* in this figure. What leaves it is a block that reached the free list, which is where an
@@ -2255,14 +2270,31 @@ function update(s, dt) {
* holds, in place, so what it keeps for itself is below what the carve gave it -- and the gap is
* the expert plane's "Borrowed VRAM". The line says both numbers rather than one, because
* "of 3.1 GiB" alone would read as a smaller budget. */
const kvGave = (s.kv_bytes_carved || 0) - s.kv_bytes_total;
/* TWO LINES, because the slot is two lines and a third is clipped rather than drawn. The share
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
the line that says how much context the bytes are actually holding. */
const kvGave = (s.kv_bytes_carved || 0) - (s.kv_bytes_total || 0);
/* KV STREAMING CHANGES WHAT THESE BYTES ARE -- but only where it is switched on in fact, not
* where it was asked for: --kv-resident is a preference (zeroed when the architecture refuses
* it, and a no-op at or above the group's context), while kv_stream_active says a group really
* keeps a resident window under its context. Without it every block the cache holds is on the
* card, so "of <total>" is VRAM and the carve is its ceiling. With it the card holds only the
* ring and every other block's K/V sits in a pinned host mirror: the figure above is the
* mirror, which is the whole context and therefore larger than the carve -- printing the carve
* beside it as a "max", or below as "can grow to", put a smaller number next to the larger one,
* and the pool read full the moment the mirror did. The line names the tier instead, and the
* ring keeps its own figure. */
const kvStream = !!(s.link && s.link.kv_stream_active);
/* THE TIER THE NUMBER IS IN, spelled. A streamed group's held context lives in the host mirror,
* so the same figure is "in ram" on this card; without streaming every block is on the card and
* it stays "in vram". The sessions view asks the same question of the same pool and renames its
* cell from the flag this poll settles. `kvStream` is the ring's actual state, not the switch. */
kvStreamOn = kvStream;
$("m-kvcap").textContent = kvStream ? "kv cache in ram" : "kv cache in vram";
$("m-kvdet").textContent = s.kv_bytes_total > 0
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
? (kvStream
? "of " + hb(s.kv_bytes_total) + " in host mirror · " + cnt3(s.kv_tokens_used) + " tok"
+ " · " + hb(s.kv_bytes_carved || 0) + " VRAM ring"
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : ""))
: "";
const aw = accWindow(s);
const awR = aw ? aw.ratio : null;
@@ -2298,29 +2330,31 @@ function update(s, dt) {
/* ONE MERGED FIGURE. The pool is carved into groups by state kind -- paged attention, the
* linear state, the drafter's own window -- and which of them a token landed in is an
* implementation detail of the carve, not a question anybody watching a server is asking. */
/* THE BAR IS THE BYTES BECAUSE THE PANEL IS ABOUT THE CARD, and it is filled from every group
* -- the recurrent ones included -- while the token figure beside it is the binding paged
* group's alone. They are not a unit conversion of each other and the panel says both.
*
* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The bytes are apportioned by the token split rather than
* measured, because the cache counts in blocks of the shared token axis and the bytes are
* every group's -- the ratio is what is being drawn, and it is exact in the unit it is taken
* in. */
/* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The share comes from the tokens (which blocks a running request
* reads versus which only the cache keeps is a fact about blocks) and is then spent in BYTES,
* the unit the figure and the percentage beside it are in, so the three cannot disagree. */
const kvCached = Math.min(s.kv_tokens_cached || 0, s.kv_tokens_used || 0);
const kvLive = Math.max(0, (s.kv_tokens_used || 0) - kvCached);
const kvCachedShare = (s.kv_tokens_used || 0) > 0 ? kvCached / s.kv_tokens_used : 0;
mKv.v.textContent = hbOf(s.kv_bytes_used, s.kv_bytes_total, " / ") + " · " + pct(kvFrac);
setSplit(mKv, kvLive, kvCached, s.kv_tokens_total || 0);
/* The two shares are FRACTIONS OF THE FILL, not of the track: spent as widths against a total
* of 1 they would draw a full bar for a pool holding 29 KiB. */
setSplit(mKv, (1 - kvCachedShare) * kvFrac, kvCachedShare * kvFrac, 1);
/* The segments named by what reclaiming them would cost, since a dimmer bar is not
self-explanatory. The split is by who references the blocks: the first part is context a
request on the card is reading, the second context nothing reads and the next eviction frees. */
mKvSub.textContent = s.kv_tokens_used > 0
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
: "";
mKvMax.textContent = s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "";
mKvMax.textContent = kvStream
? (s.kv_tokens_max > 0
? "a miss streams the missing blocks from the mirror into the ring"
: "")
: (s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "");
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
@@ -2498,6 +2532,8 @@ function update(s, dt) {
const pre = (f) => lk[f] || 0;
const dP = (f) => prev.link[f] == null ? 0 : Math.max(0, (pre(f) - prev.link[f]) / dt);
const ar = d("ar_bytes"), dn = d("d2h_bytes"), sd = d("ssd_bytes"), st = d("stream_bytes");
/* Null-safe until a server reports it: an older one, or the switch off, reads as zero. */
const kv = lk.kv_streaming ? dP("kv_stream_bytes") : 0;
const pf = dP("staged_bytes") + dP("prefetch_bytes");
const up = Math.max(0, d("h2d_bytes") - pf);
const pfAll = pre("staged_bytes") + pre("prefetch_bytes");
@@ -2508,7 +2544,7 @@ function update(s, dt) {
* proportion then falls back to the CUMULATIVE bytes, which is the same question asked over
* the whole run, and the panel says out loud which of the two it is showing. The rates stay
* in the rows either way: they are never wrong, only sometimes zero. */
const live = ar + up + pf + dn + sd + st > 0;
const live = ar + up + pf + dn + sd + st + kv > 0;
const w = (now, all) => live ? now : all;
linkSegs([
{ name: "All-reduce", ink: INK_AR, w: w(ar, lk.ar_bytes),
@@ -2531,6 +2567,16 @@ function update(s, dt) {
a: rate(sd), b: hb(lk.ssd_bytes) },
{ name: "Expert streaming", ink: INK_STREAM, w: w(st, lk.stream_bytes),
a: rate(st), b: hb(lk.stream_bytes) },
/* KV STREAMING, --kv-resident (core/kvstream): each step's resolve copies the blocks a
* streamed group missed from the pinned host mirror into the VRAM ring. The row rides the
* switch, not the traffic: a server that took --kv-resident but never streams -- a pipeline
* that never enters the streaming path -- is exactly what a zero row with the switch on
* says, and that is a question worth answering at a glance. The bytes are rank 0's resolve
* counters times the world: the ranks see the same misses through maps brought up
* identically, so each card's link carries one rank's figure. */
...(lk.kv_streaming ? [{ name: "KV streaming", ink: INK_KV,
w: w(kv, pre("kv_stream_bytes")),
a: rate(kv), b: hb(pre("kv_stream_bytes")) }] : []),
]);
/* THE HEADLINE IS THE PCIe TOTAL, which is the all-reduce plus the moves. The SSD tier is
* left out of it on purpose: those bytes come off a disk into host memory and only the ones
@@ -2540,8 +2586,12 @@ function update(s, dt) {
* EXPERT STREAMING IS IN IT. A routed expert that was not resident is read by the MoE GEMM
* where it lies, which for every tier above VRAM means crossing the link on the critical
* path of the step. It is not a move and not a collective, and it is the traffic a promotion
* is spent to remove -- so the two belong on one axis. */
const lr = rates(ar + up + pf + dn + st);
* is spent to remove -- so the two belong on one axis.
*
* KV STREAMING IS IN IT WHILE THE SWITCH IS ON. Its resolve copies cross the same PCIe the
* movers use, already summed over the cards; with the switch off the term is zero and the
* headline reads as it did without the counter. */
const lr = rates(ar + up + pf + dn + st + kv);
$("lnk_n").firstChild.nodeValue = lr.n;
$("lnk_n").querySelector("u").textContent = lr.u;
/* WHAT IS SUMMED AND WHAT IS NOT. The move and stream rows are every card's added up,
@@ -3462,6 +3512,9 @@ async function loadSessions() {
/* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can
serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A
tier that is off has no cell. */
/* A streamed server holds that context in its host mirror, not on the card, so the cell says
* where the tokens are; the flag comes from the stats poll (kvStreamOn). */
$("s-vramcap").textContent = kvStreamOn ? "context in ram" : "context in vram";
$("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0);
$("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : "";
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) {
@@ -3619,6 +3672,17 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) {
/* No caching: the page must match the binary's /stats shape, and a stale copy shows only
* blank panels. */
r.set_header("Cache-Control", "no-store");
/* The page is fixed markup that talks only to its own origin, and CSP is how that promise
* becomes enforceable: even a future markup bug could not phone an injected payload's
* findings home, and could not reach the key beyond this origin. script/style 'unsafe-inline'
* is the cost of shipping as one compiled-in literal with its own <style> and <script>;
* frame-ancestors keeps a hostile page from framing the Model view and clickjacking its
* guardrail toggle. */
r.set_header("Content-Security-Policy",
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
"connect-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; "
"form-action 'none'");
r.set_header("X-Frame-Options", "DENY");
return r;
}
+41 -5
View File
@@ -433,6 +433,14 @@ static std::string lower_ascii(std::string s) {
return s;
}
bool HttpRequest::is_cross_origin() const {
const std::string origin = header("Origin");
if (origin.empty()) return false;
const size_t at = origin.find("://");
const std::string auth = at == std::string::npos ? origin : origin.substr(at + 3);
return lower_ascii(auth) != lower_ascii(header("Host"));
}
/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
* OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.<key>`, beside
* `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
@@ -486,6 +494,11 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
/* Every response, refusals and preflights included: no browser may second-guess the type.
* The JSON routes answer only the dashboard's own fetch, and a body sniffed as HTML would
* otherwise execute where it was only meant to be read. */
svr.set_default_headers({{"X-Content-Type-Options", "nosniff"}});
/* An exception escaping a handler would close the connection with no body; answer 500 with
* an error object instead. */
svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
@@ -494,7 +507,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
try { std::rethrow_exception(ep); }
catch (const std::exception& e) { what = e.what(); }
catch (...) {}
RAD_ERR("server: %s", what.c_str());
/* e.what() can carry request text (a path, a header): keep it off the log as an
* escape-sequence vector. */
RAD_ERR("server: %s", log_sanitize(what).c_str());
res.status = 500;
res.set_content(error_body(req.path, 500, "internal_server_error", what),
"application/json");
@@ -534,10 +549,17 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
/* The probe paths and the dashboard page are exempt. A load balancer cannot send a
* bearer token, and a browser opening the page cannot send a header; the page holds no
* data and sends the key on every data fetch. Everything else is guarded, including
* /tokenize, which vLLM leaves open (it only guards /v1). */
* /tokenize, which vLLM leaves open (it only guards /v1).
*
* The exemption follows the methods those paths actually answer — reads, plus the POST
* /ping of the health-check convention — so it cannot ride a method the router might
* one day put behind one of these paths. */
const std::string& p = hreq.path;
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
p != "/dashboard") {
const std::string& m = hreq.method;
const bool reads = m == "GET" || m == "HEAD";
const bool probe = p == "/health" || p == "/v1/health" || p == "/" || p == "/dashboard";
const bool exempt = (reads && (probe || p == "/ping")) || (p == "/ping" && m == "POST");
if (!api_key.empty() && !exempt) {
if (!key_ok(hreq)) {
/* Logged in Server::error_response's format; the gate answers before the router. */
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
@@ -582,8 +604,22 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
hres.set_chunked_content_provider(
st->content_type,
[st](size_t /*offset*/, httplib::DataSink& sink) -> bool {
/* In the vendored 0.46 an exception escaping the provider unwinds the task queue
* and aborts the process (upstream's 0.54.0 serve_guarded fixed exactly this);
* until the lift moves, a throwing next() ends this response, not the server. */
std::string chunk;
bool more = st->next(chunk);
bool more = true;
try {
more = st->next(chunk);
} catch (const std::exception& e) {
RAD_ERR("server: stream provider threw: %s", log_sanitize(e.what()).c_str());
sink.done();
return true;
} catch (...) {
RAD_ERR("server: stream provider threw a non-standard exception");
sink.done();
return true;
}
if (!chunk.empty()) {
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
}
+5
View File
@@ -52,6 +52,11 @@ struct HttpRequest {
bool peer_gone() const { return closed && closed(); }
/* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
bool peer_is_loopback() const;
/* True when the request comes from a browser on another origin: an `Origin` header whose
* authority differs from `Host`. Scripts send no Origin, so this never fires for curl or an
* SDK. Through a proxy that rewrites Host, every browser reads as cross-origin — which is
* exactly the case the "loopback-only" guards must not wave through. */
bool is_cross_origin() const;
};
struct HttpResponse {
+26 -6
View File
@@ -92,10 +92,13 @@ json form_value(const std::string& key, const std::string& v) {
if (v == "true" || v == "1") return json(true);
if (v == "false" || v == "0") return json(false);
}
/* `loras` as JSON text, or one adapter's name. */
/* `loras` as JSON text, or one adapter's name. Bounded like a request body: a form field
* under the body cap can be brackets alone, and the deep tree's teardown would take the
* process with it. Over-deep or over-budget reads as plain text, as a discarded parse did. */
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
json j = json::parse(v, nullptr, false);
if (!j.is_discarded()) return j;
bool over = false, deep = false;
json j = parse_json_bounded(v, 0, &over, &deep);
if (!j.is_discarded() && !over && !deep) return j;
}
return json(v);
}
@@ -623,7 +626,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
src_px = std::move(src.rgba);
}
auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int {
auto render = [&](const std::string& prompt, const char* field, gen::Branch* out,
ApiError* err) -> int {
/* A prompt spelling the media marker would be scanned for pictures this request never
* uploaded, and the scan would walk off the item list: refuse the text, as the chat and
* embeddings paths refuse marker text (oai.cpp). */
if (prompt.find(RAD_MEDIA_MARKER) != std::string::npos) {
*err = err_bad(field, std::string("contains \"") + RAD_MEDIA_MARKER +
"\": it names a picture this request did not upload");
return RAD_E_INVAL;
}
std::string text = r.background == "transparent" && !info.tmpl_transparent.empty()
? replace_all(info.tmpl_transparent, "{prompt}", prompt)
: prompt;
@@ -651,6 +663,14 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
}
if (at == std::string::npos) break;
if (mi >= items.size()) {
/* Unreachable for any request: the prompt text is refused above, so only a model
* template that spells the marker past its pictures could reach it. Belt for the
* day one does. */
*err = err_internal("the render template spells the media marker more times "
"than the request has pictures");
return RAD_E_STATE;
}
mm::Placed pl;
pl.item = items[mi++];
pl.tok = (int32_t)out->tokens.size();
@@ -716,8 +736,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
};
{
ApiError err;
if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, &g->neg, &err) < 0)
if (render(r.prompt, "prompt", &g->pos, &err) < 0) return error_response(err, req.peer);
if (r.has_neg && render(r.negative, "negative_prompt", &g->neg, &err) < 0)
return error_response(err, req.peer);
}
+6 -3
View File
@@ -260,15 +260,18 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
o += " readmit=" + std::to_string(s.experts.readmits);
}
}
/* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
* of these lines can be differenced into rates. */
/* Link traffic by consumer (collective, mover, MoE GEMM streaming, KV streaming), cumulative
* so a `| tee` of these lines can be differenced into rates. */
if (s.link.present &&
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes ||
s.link.kv_streaming)) {
o += " link ar=" + std::to_string(s.link.ar_bytes);
o += " h2d=" + std::to_string(s.link.h2d_bytes);
o += " d2h=" + std::to_string(s.link.d2h_bytes);
if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes);
if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes);
/* Printed at zero when the switch is on: the zero is the measurement. */
if (s.link.kv_streaming) o += " kv=" + std::to_string(s.link.kv_stream_bytes);
}
o += "\n";
return o;
+20 -5
View File
@@ -95,11 +95,12 @@ struct ExpertPlane {
/* Interconnect traffic by consumer.
*
* Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
* on one clock, so rates from two polls compare directly: is the link busy because the model is
* wide or because placement is thrashing?
* Four things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid), and --kv-resident's per-step
* resolve, which copies the blocks a streamed KV group missed from its host mirror into the VRAM
* ring (core/kvstream). All are cumulative byte counts on one clock, so rates from two polls
* compare directly: is the link busy because the model is wide or because placement is thrashing?
*
* `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
* mover's measured copy sizes.
@@ -117,6 +118,20 @@ struct LinkStat {
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
* Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
int64_t staged_bytes = 0;
/* KV streaming (--kv-resident): the bytes the resolves copied from the host mirror into the
* ring. Rank 0's counters -- the ranks resolve the same block ids through maps brought up
* identically, so one rank's answer is every rank's (see Engine::stream_probe_take) -- times
* the world, to sit on every card's link like the move rows. `kv_streaming` says the switch
* was asked for; a renderer then shows the row at zero included, because a zero with the
* switch on is the answer to "does this model's pipeline ever stream?".
*
* `kv_stream_active` is the DIFFERENT question: whether a group's device pool really is a
* resident window under its context. The switch is a preference -- it is zeroed when the
* architecture refuses it, and --kv-resident at or above the group's context leaves a plain
* resident pool -- so text that names a memory tier must read this, never the flag. */
int64_t kv_stream_bytes = 0;
bool kv_streaming = false;
bool kv_stream_active = false;
};
/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
+22 -10
View File
@@ -163,7 +163,11 @@ std::string ApiError::dump() const {
if (n_ctx >= 0) e["n_ctx"] = n_ctx;
json o;
o["error"] = e;
return o.dump();
/* A message can carry raw request text (a URL-decoded label, an echoed field name): dump
* must survive invalid UTF-8 by replacing it rather than throwing and turning a 404 into
* a 500. The JSON parsers refuse invalid UTF-8 in bodies, but URL-decoded params do not
* pass through one. */
return o.dump(-1, ' ', false, json::error_handler_t::replace);
}
ApiError err_bad(const std::string& param, const std::string& why) {
@@ -431,13 +435,16 @@ std::string str_or(const json& o, const char* k, const std::string& def = std::s
}
/* A conversation's label for /sessions: at most 128 bytes, cut at a UTF-8 character boundary
* because the label is serialised into JSON. */
* because the label is serialised into JSON. Control bytes are dropped at the door: the label
* is logged on release and shown on the dashboard, and an embedded ESC sequence would drive
* whatever terminal renders it. */
std::string session_label_of(const std::string& s) {
std::string t = log_sanitize(s);
constexpr size_t kMax = 128;
if (s.size() <= kMax) return s;
if (t.size() <= kMax) return t;
size_t cut = kMax;
while (cut > 0 && ((unsigned char)s[cut] & 0xC0) == 0x80) --cut;
return s.substr(0, cut);
while (cut > 0 && ((unsigned char)t[cut] & 0xC0) == 0x80) --cut;
return t.substr(0, cut);
}
/* One field under several spellings (OpenAI's, vLLM's, llama.cpp's), read as a number (double)
@@ -1053,8 +1060,11 @@ void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
if (lim.reasoning_effort_map.empty()) return;
auto it = opt->template_kwargs.find("reasoning_effort");
if (it == opt->template_kwargs.end()) return;
const json v = json::parse(it->second, nullptr, false);
if (!v.is_string()) return;
/* The kwarg is client text re-parsed as JSON: bound it like a body, a string of brackets
* would overflow this worker's stack when the tree comes down. */
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
if (over || deep || !v.is_string()) return;
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
if (m == lim.reasoning_effort_map.end()) return;
if (m->second == "none" || m->second == "minimal") {
@@ -1071,9 +1081,11 @@ ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, in
* variable was in the render. The set is more actionable than the template's traceback. */
auto it = opt.template_kwargs.find("reasoning_effort");
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
const json v = json::parse(it->second, nullptr, false);
bool over = false, deep = false;
const json v = parse_json_bounded(it->second, 0, &over, &deep);
const std::vector<std::string>& set = lim.reasoning_efforts;
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
if (!over && !deep && v.is_string() &&
std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
std::string list;
for (size_t i = 0; i < set.size(); ++i)
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
@@ -3782,7 +3794,7 @@ std::string anthropic_error_body(const ApiError& e) {
json o;
o["type"] = "error";
o["error"] = json{ { "type", anthropic_error_type(e.status) }, { "message", e.message } };
return o.dump();
return o.dump(-1, ' ', false, json::error_handler_t::replace); /* see ApiError::dump */
}
AnthropicStream::AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser)
+7 -2
View File
@@ -38,6 +38,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "mm/processor.h"
#include "mm/resample.h"
@@ -658,8 +659,12 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
auto handle = [&](const std::string& msg, bool binary) {
if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
/* Bounded like a request body: 2 MiB of brackets is a legal WebSocket frame, and the
* recursive teardown of a deep tree would take the whole process down with it. */
bool over = false, deep = false;
const ojson j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string())
return error("invalid_request_error", "invalid_json",
"a client event is a JSON object with a string `type`", "", nullptr);
const std::string type = j["type"].get<std::string>();
+21 -10
View File
@@ -406,13 +406,15 @@ static std::string from_peer(const std::string& peer) {
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
metrics_.observe_http(e.status);
/* Log every refusal with status, type, message and peer: 4xx at info (the client's doing),
* 5xx as a warning (ours). */
* 5xx as a warning (ours). The message can echo request text (a URL-decoded label, a field
* name), so the log copy is control-byte-clean; the wire copy keeps the bytes. */
const std::string msg = log_sanitize(e.message), typ = log_sanitize(e.type);
if (e.status >= 500)
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
else
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
msg.c_str());
HttpResponse r = HttpResponse::json_body(
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
@@ -1791,6 +1793,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
}
@@ -1969,6 +1972,7 @@ HttpResponse Server::handle_mica(const HttpRequest& req) {
if (mica_answers(r, dist, &answers, &err) < 0) return error_response(err, req.peer);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", input_tokens }, { "output_tokens", 0 } } } }));
}
@@ -2056,6 +2060,7 @@ HttpResponse Server::handle_clef(const HttpRequest& req) {
release(1);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{
{ "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", { { "input_tokens", (int64_t)r.tokens.size() }, { "output_tokens", 0 } } } }));
}
@@ -2150,7 +2155,8 @@ HttpResponse Server::handle_laya(const HttpRequest& req) {
retire(gens);
release(n);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(json{ { "answers", std::move(answers) },
return HttpResponse::json_body(200, json_dump(json{ { "model", opt_.model_id },
{ "answers", std::move(answers) },
{ "usage", laya_usage(r) } }));
}
@@ -2206,7 +2212,6 @@ HttpResponse Server::handle_loras(const HttpRequest& req) {
}
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
using json = nlohmann::json;
auto fail = [&](int status, const char* type, const std::string& msg) {
ApiError e;
e.status = status;
@@ -2217,12 +2222,18 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
if (!opt_.lora_load || !opt_.lora_unload)
return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or "
"--max-loras)");
if (opt_.api_key.empty() && !req.peer_is_loopback())
if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin()))
/* A cross-origin browser counts as neither loopback nor local: the victim's own browser
* is loopback to this port, and that is exactly how a hostile page would reach here. */
return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a "
"server started without --api-key takes it only from a "
"loopback client");
const json j = json::parse(req.body, nullptr, false);
if (j.is_discarded() || !j.is_object() || !j.contains("lora_name") || !j["lora_name"].is_string())
/* Bounded like a generation body: this parses client text the same way, and a deep bracket
* nest would overflow this worker's stack when the tree is torn down. */
bool over = false, deep = false;
const json j = parse_json_bounded(req.body, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("lora_name") ||
!j["lora_name"].is_string())
return fail(400, "invalid_request_error", "the body must be a JSON object with lora_name");
const std::string name = j["lora_name"].get<std::string>();
if (name.empty() || name == opt_.model_id)
+4 -3
View File
@@ -149,9 +149,10 @@ struct ServerOptions {
* a string rendered once: the dump includes `OpInfo::issued`, which a pre-first-step snapshot
* would report as false for every op, hiding dead declarations.
*
* Regenerating reads the Program on the HTTP thread while the step path writes that field. It
* is a monotonic false -> true bool, so at worst a mid-step fetch shows an op unissued one step
* early. Registry::select is called with record = false and mutates nothing else. */
* Regenerating reads the Program on the HTTP thread while the step path writes that field;
* both sides go through std::atomic_ref (Ctx::flush_issued, rad_graph.cpp), so the pairing is
* a relaxed exchange rather than a data race. Registry::select is called with record = false
* and mutates nothing else. */
std::function<std::string()> graph_json;
/* The startup report as JSON (core/diag/diag.h): options in force, the machine as it is now
* (the provider may reuse a reading for a second), and what on it costs speed. Without an API
+7 -2
View File
@@ -27,6 +27,7 @@
*/
#include "server.h"
#include "server_priv.h"
#include "oai.h"
#include "text_split.h"
#include "gen/audio.h"
@@ -279,8 +280,12 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
"session.close");
return false;
}
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
/* Bounded like a request body: a deep bracket nest is a legal frame, and tearing its
* tree down recurses once per level. */
bool over = false, deep = false;
const json j = parse_json_bounded(msg, 0, &over, &deep);
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
!j["type"].is_string()) {
error("a client message is a JSON object with a string `type`");
return false;
}