Add a live statistics dashboard over persistent history
Replace the four-row stats modal with a real dashboard — our own angle on the reference's ephemeral request monitor: because our context lives in SQLite we can aggregate over ALL history, not just the last N requests. Backend: - Usage carries the engine's prompt_ms/decode_ms (from DONE); a token- weighted in-memory PerfMeter in ChatService records every served request (complete + stream) and exposes decode/prefill tok/s. - store::Stats grows total_tokens, tool_calls (json_array_length over assistant tool_calls_json), a per-session breakdown (busiest first) and a per-UTC-day token series; all over existing columns, no schema change, still behind the Store trait. - GET /api/stats returns the store aggregates flattened plus a live engine status (model, max_context, busy) and the perf gauge. Frontend (mobile-first, vanilla, i18n catalog): - Overview cards: engine state dot + model + context, decode speed (run average) + prefill, total/prompt/completion tokens, sessions + messages, tool calls, requests served. - Daily stacked prompt/completion bar chart (continuous zero-filled UTC window, last 30 days) and per-session token-share bars. - Polls every 2s while open, re-renders only on change; closes via button, backdrop or Escape. Tests: new store breakdown test + extended stats integration assertions (124 passed, 2 ignored). Verified live on the real engine: decode/prefill gauge populated from DONE timings; dashboard renders on desktop.
This commit is contained in:
1 parent
e79ee0e20e
commit
765c197b95
11 files changed
+642
-42
No files matched your search
+92
-8
@@ -8,6 +8,7 @@
|
||||
//! while the HTTP handler just forwards what the task puts on the channel.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
use futures::Stream;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
@@ -27,11 +28,58 @@ use super::types::{
|
||||
pub struct ChatService {
|
||||
engine: Arc<Engine>,
|
||||
fmt: Arc<dyn Formatter>,
|
||||
perf: Arc<StdMutex<PerfMeter>>,
|
||||
}
|
||||
|
||||
/// A running, token-weighted performance gauge over the requests served since
|
||||
/// startup (in-memory, like the reference monitor's retained requests). Powers
|
||||
/// the "average decode speed" headline without per-message schema churn.
|
||||
#[derive(Debug, Default, Clone, Copy, serde::Serialize)]
|
||||
pub struct PerfSnapshot {
|
||||
pub requests: u64,
|
||||
pub decode_tps: Option<f64>,
|
||||
pub prefill_tps: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PerfMeter {
|
||||
requests: u64,
|
||||
decode_tokens: u64,
|
||||
decode_ms: f64,
|
||||
prompt_tokens: u64,
|
||||
prompt_ms: f64,
|
||||
}
|
||||
|
||||
impl PerfMeter {
|
||||
fn record(&mut self, u: &Usage) {
|
||||
self.requests += 1;
|
||||
if let Some(d) = u.decode_ms.filter(|d| *d > 0.0) {
|
||||
self.decode_tokens += u.completion_tokens as u64;
|
||||
self.decode_ms += d;
|
||||
}
|
||||
if let Some(p) = u.prompt_ms.filter(|p| *p > 0.0) {
|
||||
self.prompt_tokens += u.prompt_tokens as u64;
|
||||
self.prompt_ms += p;
|
||||
}
|
||||
}
|
||||
fn snapshot(&self) -> PerfSnapshot {
|
||||
PerfSnapshot {
|
||||
requests: self.requests,
|
||||
decode_tps: (self.decode_ms > 0.0)
|
||||
.then(|| self.decode_tokens as f64 / (self.decode_ms / 1000.0)),
|
||||
prefill_tps: (self.prompt_ms > 0.0)
|
||||
.then(|| self.prompt_tokens as f64 / (self.prompt_ms / 1000.0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatService {
|
||||
pub fn new(engine: Arc<Engine>, fmt: Arc<dyn Formatter>) -> Self {
|
||||
Self { engine, fmt }
|
||||
Self {
|
||||
engine,
|
||||
fmt,
|
||||
perf: Arc::new(StdMutex::new(PerfMeter::default())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_name(&self) -> &str {
|
||||
@@ -43,6 +91,24 @@ impl ChatService {
|
||||
self.fmt.count_tokens(text)
|
||||
}
|
||||
|
||||
/// Running performance gauge (average decode/prefill speed since startup).
|
||||
pub fn perf(&self) -> PerfSnapshot {
|
||||
self.perf
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.snapshot()
|
||||
}
|
||||
|
||||
/// The engine's context window (tokens).
|
||||
pub fn max_context(&self) -> u32 {
|
||||
self.engine.ready().max_context
|
||||
}
|
||||
|
||||
/// True when no request holds the engine wires.
|
||||
pub fn is_idle(&self) -> bool {
|
||||
self.engine.is_idle()
|
||||
}
|
||||
|
||||
/// One-shot completion.
|
||||
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
|
||||
let mut prompt = self.build_prompt_blocking(req).await?;
|
||||
@@ -84,6 +150,16 @@ impl ChatService {
|
||||
finish_reason(&outcome, prompt.max_new)
|
||||
};
|
||||
|
||||
let usage = usage_of(
|
||||
&outcome,
|
||||
prompt.ids.len() as u32,
|
||||
outcome.tokens.len() as u32,
|
||||
);
|
||||
self.perf
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.record(&usage);
|
||||
|
||||
Ok(ChatResponse {
|
||||
id: completion_id(),
|
||||
object: "chat.completion",
|
||||
@@ -101,11 +177,7 @@ impl ChatService {
|
||||
},
|
||||
finish_reason: finish,
|
||||
}],
|
||||
usage: usage_of(
|
||||
&outcome,
|
||||
prompt.ids.len() as u32,
|
||||
outcome.tokens.len() as u32,
|
||||
),
|
||||
usage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -128,6 +200,7 @@ impl ChatService {
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<ChatChunk>();
|
||||
let engine = self.engine.clone();
|
||||
let fmt = self.fmt.clone();
|
||||
let perf = self.perf.clone();
|
||||
|
||||
let (p_ids, p_max, p_sampling, p_temp) = (
|
||||
prompt.ids,
|
||||
@@ -229,6 +302,16 @@ impl ChatService {
|
||||
.unwrap_or(out.tokens.len() as u32),
|
||||
Err(_) => 0,
|
||||
};
|
||||
let (pms, dms) = gen
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|o| o.done.as_ref())
|
||||
.map(|d| (Some(d.prompt_ms), Some(d.decode_ms)))
|
||||
.unwrap_or((None, None));
|
||||
let usage = Usage::new(prompt_len, completion).with_timings(pms, dms);
|
||||
perf.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.record(&usage);
|
||||
send(
|
||||
&tx,
|
||||
&id,
|
||||
@@ -236,7 +319,7 @@ impl ChatService {
|
||||
&model,
|
||||
Delta::default(),
|
||||
Some(finish),
|
||||
Some(Usage::new(prompt_len, completion)),
|
||||
Some(usage),
|
||||
);
|
||||
|
||||
if let Err(e) = gen {
|
||||
@@ -378,7 +461,8 @@ fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
|
||||
|
||||
fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
|
||||
match &outcome.done {
|
||||
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion)),
|
||||
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion))
|
||||
.with_timings(Some(d.prompt_ms), Some(d.decode_ms)),
|
||||
None => Usage::new(prompt_len, completion),
|
||||
}
|
||||
}
|
||||
|
||||
+32
-3
@@ -13,9 +13,10 @@ use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
|
||||
use futures::StreamExt;
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::routes::{AppState, Error};
|
||||
use super::service::PerfSnapshot;
|
||||
use super::types::{
|
||||
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
|
||||
FinishReason, FunctionCall, Role, ToolCall, Usage,
|
||||
@@ -189,8 +190,36 @@ pub(crate) async fn get_messages(
|
||||
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
|
||||
}
|
||||
|
||||
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> {
|
||||
Ok(Json(with_store(&st, |s| s.stats()).await?))
|
||||
/// The stats dashboard payload: persistent history aggregates (from the store)
|
||||
/// plus a live engine status and the since-startup performance gauge, in one
|
||||
/// JSON object so the GUI renders the whole view from a single poll.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct StatsResponse {
|
||||
#[serde(flatten)]
|
||||
totals: Stats,
|
||||
engine: EngineStatus,
|
||||
perf: PerfSnapshot,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct EngineStatus {
|
||||
model: String,
|
||||
max_context: u32,
|
||||
busy: bool,
|
||||
}
|
||||
|
||||
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsResponse>, Error> {
|
||||
let totals = with_store(&st, |s| s.stats()).await?;
|
||||
let engine = EngineStatus {
|
||||
model: st.service.model_name().to_string(),
|
||||
max_context: st.service.max_context(),
|
||||
busy: !st.service.is_idle(),
|
||||
};
|
||||
Ok(Json(StatsResponse {
|
||||
totals,
|
||||
engine,
|
||||
perf: st.service.perf(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn role_of(s: &str) -> Role {
|
||||
|
||||
@@ -150,6 +150,13 @@ pub struct Usage {
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
pub total_tokens: u32,
|
||||
/// Engine prefill time (ms), when reported. Non-standard extras; OpenAI
|
||||
/// clients ignore them, the GUI uses them for performance stats.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_ms: Option<f64>,
|
||||
/// Engine decode time (ms), when reported.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub decode_ms: Option<f64>,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
@@ -158,8 +165,17 @@ impl Usage {
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
prompt_ms: None,
|
||||
decode_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach engine timings (prefill/decode ms) for performance statistics.
|
||||
pub fn with_timings(mut self, prompt_ms: Option<f64>, decode_ms: Option<f64>) -> Self {
|
||||
self.prompt_ms = prompt_ms.filter(|v| *v > 0.0);
|
||||
self.decode_ms = decode_ms.filter(|v| *v > 0.0);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Why generation stopped (OpenAI spelling).
|
||||
|
||||
Reference in new issue
Block a user