Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

web: a Conversation cache card in the Monitor tab (#596)

Niko1221a9fe9236bf81
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 2ea4641bc..704bc8f58 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -596,6 +596,11 @@ INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring
remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be
reported separately from Linux/CUDA evidence.
+The web page's Monitor tab has a **Conversation cache** card (0.1.39, #596): the parked conversations against the
+slots and the RAM budget, how many were parked, restored and evicted, and the last switch (read from the engine's
+log), and for every setup how many prompt tokens the cache gave back - in the last request and since the start.
+`/metrics` has the same under `"conversation_cache"`.
+
Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V.
They add host RAM, not another model or VRAM allocation. The byte budget also counts
an incoming snapshot during a switch. After a restore, unchanged K/V pages can be
diff --git a/serve/server.py b/serve/server.py
index 0c2c65b28..26c81cc76 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -299,6 +299,76 @@ def narrate_start(log_path: str, offset: int, args: list, done: threading.Event,
print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True)
+class ConvCacheLog:
+ """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation
+ cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr,
+ which is the log): read on from where it was last read, from the start of the engine's current run."""
+ EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)"
+ r"(?: evictions=(\d+))?")
+ DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)")
+ READ_MAX = 1 << 20 # at most the last MiB of new lines per read
+
+ def __init__(self):
+ self.key, self.pos = None, 0
+ self.reset()
+
+ def reset(self):
+ self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None,
+ "last_tokens": None, "last_at": None}
+
+ def poll(self, path, start) -> dict:
+ """The state after the log's new lines; `start` is where the engine's current run began in it."""
+ if not path or start is None:
+ return dict(self.state)
+ if self.key != (path, start): # another start of the engine: its cache starts empty
+ self.key, self.pos = (path, start), start
+ self.reset()
+ try:
+ size = os.path.getsize(path)
+ if size < self.pos: # the log was emptied or replaced
+ self.pos = 0
+ if size - self.pos > self.READ_MAX:
+ self.pos = size - self.READ_MAX
+ with open(path, "rb") as f:
+ f.seek(self.pos)
+ data = f.read(size - self.pos)
+ except OSError:
+ return dict(self.state)
+ end = data.rfind(b"\n") + 1 # whole lines only: the rest is read next time
+ self.pos += end
+ now = time.time()
+ for line in data[:end].decode("utf-8", "replace").splitlines():
+ if "conversation cache:" not in line:
+ continue
+ m = self.EVENT.search(line)
+ if m:
+ st = self.state
+ st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4))
+ if m.group(5) is not None:
+ st["evictions"] = int(m.group(5))
+ if m.group(1) != "skipped":
+ st["parks" if m.group(1) == "parked" else "restores"] += 1
+ st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now
+ continue
+ m = self.DROPPED.search(line)
+ if m:
+ self.state["parked"] = int(m.group(1))
+ return dict(self.state)
+
+
+def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict:
+ """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in
+ --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back."""
+ mib = info.get("conversation_cache_mib")
+ last = hist[-1] if hist else None
+ return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None,
+ "slots": info.get("conversation_cache_slots"), **parked,
+ "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0),
+ "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0),
+ "last_reused": last.get("reused") if last else None,
+ "last_prompt": last.get("prompt_tokens") if last else None}
+
+
class StrataEngine:
"""The resident engine: `strata --serve` reads `GEN <max_new> <ids>` lines and streams `T <id>` lines, then
`DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough.
@@ -335,6 +405,7 @@ class StrataEngine:
self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL
loading = threading.Event() # set once READY: the narrator below stops
log_start = os.path.getsize(log) if log else 0 # where this start's lines begin (start_failure_hint)
+ self.log_start = log_start # #596: the Monitor's conversation cache reads from here
if log:
threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading),
daemon=True).start()
@@ -993,6 +1064,7 @@ class Service:
# #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system
# turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation
self.effort_end = False
+ self.conv_log = ConvCacheLog() # #596: the parked conversations, from the engine's log
# #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that
# matters); empty = no CORS headers at all, as before
self.cors_origins: list[str] = []
@@ -1329,7 +1401,9 @@ class Service:
engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None,
**dict(getattr(self.engine, "info", {}) or {})}
tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}}
+ parked = self.conv_log.poll(getattr(self.engine, "log_path", None), getattr(self.engine, "log_start", None))
return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12],
+ "conversation_cache": conversation_cache_view(engine, hist, totals, parked),
"requests_kept": len(hist), "totals": totals, "hardware": tel["now"],
"hardware_static":
tel["static"], "history": tel["history"], "time": now}
diff --git a/serve/test_monitor.py b/serve/test_monitor.py
index ad554e000..0c82cb0b5 100644
--- a/serve/test_monitor.py
+++ b/serve/test_monitor.py
@@ -194,5 +194,68 @@ class Monitor(unittest.TestCase):
self.assertEqual(self.request("/web/../server.py")[0], 404)
+class ConversationCacheCard(unittest.TestCase):
+ """#596: /metrics' "conversation_cache": the parked conversations from the engine's log lines, the budget and
+ slots from its INFO line, and how much of the prompts the cache gave back."""
+
+ PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 "
+ "snapshot_bytes=104857600 reused_kv_bytes=0\n")
+ RESTORE = "strata serve: conversation cache: restored 4000 tokens (exact) in 30.0 ms; parked=2 bytes=209715200\n"
+
+ def test_the_log(self):
+ from serve.server import ConvCacheLog
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ log = Path(d) / "strata.log"
+ log.write_text("an earlier run\n" + self.PARK, encoding="utf-8")
+ start = log.stat().st_size # this run starts here: the earlier run's park is not counted
+ c = ConvCacheLog()
+ self.assertEqual(c.poll(str(log), start)["parked"], 0)
+ with open(log, "a", encoding="utf-8") as f:
+ f.write("strata serve: something else\n" + self.PARK + self.RESTORE + "strata serve: conversation ca")
+ st = c.poll(str(log), start)
+ self.assertEqual((st["parked"], st["bytes"], st["parks"], st["restores"]), (2, 209715200, 1, 1))
+ self.assertEqual((st["last_event"], st["last_tokens"]), ("restored", 4000))
+ with open(log, "a", encoding="utf-8") as f: # the cut line is read once it is whole
+ f.write("che: dropped 1 superseded copy of this conversation; parked=1\n")
+ self.assertEqual(c.poll(str(log), start)["parked"], 1)
+ self.assertEqual(c.poll(str(log), log.stat().st_size)["parked"], 0) # the engine started again
+ self.assertEqual(c.poll(None, None)["parked"], 0)
+
+ def test_metrics(self):
+ tok = ByteTokenizer()
+ engine = MockEngine(tok, "Thought.</think>\nHello.", max_context=4096)
+ engine.info = {"conversation_cache_mib": 8192, "conversation_cache_slots": 4}
+ svc = Service(engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
+ httpd = serve(svc, port=0)
+ base = f"http://127.0.0.1:{httpd.server_address[1]}"
+ try:
+ with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
+ c = json.loads(r.read())["conversation_cache"]
+ self.assertEqual((c["enabled"], c["budget_mib"], c["slots"], c["parked"], c["requests"]),
+ (True, 8192, 4, 0, 0))
+ req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"},
+ data=json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode())
+ with urllib.request.urlopen(req, timeout=10) as r:
+ r.read()
+ with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
+ c = json.loads(r.read())["conversation_cache"]
+ self.assertEqual(c["requests"], 1)
+ self.assertGreater(c["last_prompt"], 0)
+ engine.info = {}
+ with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
+ self.assertFalse(json.loads(r.read())["conversation_cache"]["enabled"]) # off: the reuse lines only
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
+ def test_the_card_is_on_the_page(self):
+ web = Path(__file__).parent / "web"
+ html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8")
+ for el in ("cc-card", "cc-slots-text", "cc-mem-text", "cc-facts", "cc-note"):
+ self.assertIn(f'id="{el}"', html)
+ self.assertIn(f'"{el}"', js)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/serve/web/app.css b/serve/web/app.css
index 4e8363d4a..9caa070f2 100644
--- a/serve/web/app.css
+++ b/serve/web/app.css
@@ -115,6 +115,11 @@ main { flex: 1; min-height: 0; display: flex; }
.table-wrap.all { max-height: 420px; overflow-y: auto; }
.req-totals { margin: 0; font-size: var(--st-fs-sm); }
.req-totals:empty { display: none; }
+.cc-card { display: flex; flex-direction: column; gap: var(--st-s-3); }
+.cc-bars { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-2) var(--st-s-6); }
+.cc-bars[hidden] { display: none; }
+.cc-note { margin: 0; }
+.cc-note:empty { display: none; }
.mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); }
.mcp-server { display: flex; flex-direction: column; gap: var(--st-s-2); padding-top: var(--st-s-3); border-top: 1px solid var(--st-line-soft); }
.mcp-server:first-child { padding-top: 0; border-top: 0; }
@@ -155,6 +160,7 @@ main { flex: 1; min-height: 0; display: flex; }
@media (max-width: 1000px) {
.metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.monitor-row { grid-template-columns: 1fr; }
+ .cc-bars { grid-template-columns: 1fr; }
}
@media (max-width: 640px) {
.st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); }
diff --git a/serve/web/app.js b/serve/web/app.js
index 6e8fa6b29..64721b446 100644
--- a/serve/web/app.js
+++ b/serve/web/app.js
@@ -190,9 +190,43 @@ function render(m) {
}
if (live.queued > 0) setPill("queued", `${live.queued} queued`);
if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept);
+ if (tab === "monitor") renderConvCache(m.conversation_cache);
if (tab === "about") renderAbout(eng, hw, st);
}
+// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole
+// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in)
+function since(t) {
+ if (!t) return "";
+ const s = Math.max(0, Date.now() / 1000 - t);
+ return s < 60 ? "just now" : s < 3600 ? `${fmt(s / 60)} min ago` : `${fmt(s / 3600, 1)} h ago`;
+}
+function renderConvCache(c) {
+ $("cc-card").hidden = !c;
+ if (!c) return; // an older server
+ const pct = (a, b) => (b ? `${Math.min(100, (100 * a) / b)}%` : "0%");
+ $("cc-bars").hidden = !c.enabled;
+ if (c.enabled) {
+ $("cc-slots-text").textContent = `${fmt(c.parked)} / ${fmt(c.slots)}`;
+ $("cc-slots-bar").style.width = pct(c.parked, c.slots);
+ const budget = c.budget_mib * 1048576;
+ $("cc-mem-text").textContent = `${gb(c.bytes)} / ${gb(budget)} GB`;
+ $("cc-mem-bar").style.width = pct(c.bytes, budget);
+ }
+ $("cc-sum").textContent = c.requests ? `${fmt(c.requests_reused)} of ${fmt(c.requests)} requests reused part of their prompt` : "";
+ const share = c.prompt_tokens ? ` (${fmt((100 * c.reused_tokens) / c.prompt_tokens)}% of all prompt tokens)` : "";
+ const event = c.last_event ? `${c.last_event === "parked" ? "Parked" : "Restored"} ${fmt(c.last_tokens)} tokens, ${since(c.last_at)}` : null;
+ facts($("cc-facts"), [
+ ["Last request", c.last_prompt != null ? `${fmt(c.last_reused || 0)} of ${fmt(c.last_prompt)} prompt tokens reused` : null],
+ ["Reused since start", c.requests ? `${fmt(c.reused_tokens)} tokens${share}` : null],
+ ["Parked / restored", c.enabled ? `${fmt(c.parks)} / ${fmt(c.restores)}${c.evictions ? ` · ${fmt(c.evictions)} evicted` : ""}` : null],
+ ["Last switch", c.enabled ? event : null],
+ ]);
+ $("cc-note").textContent = c.enabled
+ ? "A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full."
+ : "The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md).";
+}
+
function renderTotals(t) {
if (!t || !t.requests) return "";
const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"});
diff --git a/serve/web/index.html b/serve/web/index.html
index d858d2f08..cf588762a 100644
--- a/serve/web/index.html
+++ b/serve/web/index.html
@@ -125,6 +125,18 @@
</div>
</div>
+ <div class="st-card cc-card" id="cc-card">
+ <div class="req-head"><span class="card-title">Conversation cache</span><span class="muted small" id="cc-sum"></span></div>
+ <div class="cc-bars" id="cc-bars" hidden>
+ <div><div class="bar-row"><span>Parked conversations</span><span class="muted" id="cc-slots-text">&ndash;</span></div>
+ <div class="st-progress"><div class="st-progress__bar" id="cc-slots-bar" style="width:0%"></div></div></div>
+ <div><div class="bar-row"><span>Their memory (RAM)</span><span class="muted" id="cc-mem-text">&ndash;</span></div>
+ <div class="st-progress"><div class="st-progress__bar" id="cc-mem-bar" style="width:0%"></div></div></div>
+ </div>
+ <dl class="facts" id="cc-facts"></dl>
+ <p class="muted small cc-note" id="cc-note"></p>
+ </div>
+
<div class="st-card mcp-card" id="mcp-card" hidden>
<div class="req-head"><span class="card-title">MCP servers</span><span class="muted small" id="mcp-sum"></span></div>
<div class="mcp-list" id="mcp-list"></div>