Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions ds41f-4xgx10-switchless/docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,51 @@ job's driver that holds a want across its parts keeps the service from taking th
candidate 4's start waited 44 minutes so). To bring the kit back: `service.sh stop`, then
`cd ~/ai/dsv41-4x-ring && nohup setsid ./start-tp4.sh serve > logs-tp4/serve-launch.log 2>&1 < /dev/null &`
on rank 0 (ready in ~6 min).

## The `/metrics` endpoint

dsfront answers `GET /metrics` on the same addresses and port as the API, unauthenticated like
`/health`, in the Prometheus text exposition format (`text/plain; version=0.0.4`). The series keep the
`tensorfold:` prefix of the serve they replace, so a scraper already reading the TensorFold counters
reads these unchanged:

| series | type | what it reports |
|---|---|---|
| `tensorfold:requests_running` | gauge | requests in flight in the gate |
| `tensorfold:requests_waiting` | gauge | requests waiting in the gate |
| `tensorfold:generation_tokens_total` | counter | output tokens, added as the engine streams them |
| `tensorfold:prompt_tokens_total` | counter | the full prompt length of each served request |
| `tensorfold:prompt_tokens_cached_total` | counter | the part of that prompt whose KV was reused |
| `tensorfold:time_to_first_token_seconds_sum`, `_count` | summary | time to first token over completed requests |
| `tensorfold:request_prefill_seconds_sum`, `_count` | summary | the engine's own prefill time (prefill start -> first token) over completed requests |

`prompt_tokens_cached_total` is a **subset** of `prompt_tokens_total`, not a counter beside it: it
counts the prompt tokens whose KV was reused, and those sit inside the prompt total. A scraper derives
the prefill rate as `prompt_tokens_total − prompt_tokens_cached_total`; if the two were a partition
instead, that rate would come out inflated by the cache share — on a cache-heavy agent lane, by more
than an order of magnitude. The front end adds the full prompt length to the prompt total and only the
engine's `Done.cached_tokens` to the cached counter, clamped at the update site to the prompt it was
handed ([protocol.md](protocol.md) defines the field), so the relation holds even if an engine ever
reports a reuse length longer than the prompt.

`generation_tokens_total` advances while a request decodes, so it includes the tokens of a request
still in flight; the prompt, cached and TTFT series are recorded once, when the request completes.

`request_prefill_seconds` is the prefill time the **engine** measured (`Done.prefill_us`, prefill started
to first token), not TTFT: TTFT is measured from the front end and also covers the gate and the submit
round trip, so it is the larger of the two and dividing by it understates the prefill rate. A scraper
derives the rate as `d(prompt_tokens_total - prompt_tokens_cached_total) / d(request_prefill_seconds_sum)`
over its window: the computed tokens divided by the time spent computing them. The prompt, cached,
prefill and TTFT series are all recorded once per completed request, so the deltas of one window cover
the same requests.

The counters are per-process and begin at zero when dsfront starts. **A restart resets them all to
zero, together with the session and prefix-cache state**, so a scraper should read a drop to zero as a
restart, not as a traffic drop: they return to zero together, never one without the others.

A scraper that keeps its own baseline across a restart must re-seed it for the same reason: the
first window after a restart divides by a prefill sum that begins at zero, so a baseline carried
over from before the restart reads one absurd rate before the series line up again. Discarding the
first post-restart window is the simple version of that rule.

There is no per-slot or queue-depth gauge beyond the two request gauges.
6 changes: 6 additions & 0 deletions ds41f-4xgx10-switchless/frontend/src/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ impl Gate {
self.st.lock().unwrap().closing = true;
}

/// (in flight, waiting at the gate): the two gauges `/metrics` exports.
pub fn load(&self) -> (u32, u32) {
let s = self.st.lock().unwrap();
(s.in_flight, s.waiting)
}

pub fn status(&self, connected: bool) -> String {
let s = self.st.lock().unwrap();
format!(
Expand Down
87 changes: 86 additions & 1 deletion ds41f-4xgx10-switchless/frontend/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ pub struct ServerConfig {
pub vision_addr: Option<String>,
}

/// Monotonic counters for /metrics (sparkDash reads them as `tensorfold:*`).
///
/// `CACHED_TOTAL` counts the prompt tokens whose KV was reused, and those sit *inside*
/// `PROMPT_TOTAL` (see `Done::cached_tokens`): sparkDash derives prefill as `prompt - cached`,
/// so the two are a subset relation, never a partition. The clamp at the update site keeps that
/// true even if an engine ever reports a reuse length past the prompt it was handed.
static GEN_TOTAL: AtomicU64 = AtomicU64::new(0);
static PROMPT_TOTAL: AtomicU64 = AtomicU64::new(0);
static CACHED_TOTAL: AtomicU64 = AtomicU64::new(0);
static TTFT_US_SUM: AtomicU64 = AtomicU64::new(0);
static TTFT_COUNT: AtomicU64 = AtomicU64::new(0);
/// Prefill time as the engine measured it (`Done::prefill_us`: prefill started -> first token),
/// over completed requests. TTFT is not that quantity (it also covers the gate and the submit round
/// trip), so the prefill rate divides the computed tokens, `prompt - cached`, by these.
static PREFILL_US_SUM: AtomicU64 = AtomicU64::new(0);
static PREFILL_COUNT: AtomicU64 = AtomicU64::new(0);

pub struct App {
pub cfg: ServerConfig,
pub tok: Arc<Tokenizer>,
Expand Down Expand Up @@ -108,6 +125,7 @@ impl App {
pub fn router(app: Arc<App>) -> Router {
Router::new()
.route("/health", get(health))
.route("/metrics", get(metrics))
.route("/v1/models", get(models))
.route("/v1/chat/completions", post(chat))
.layer(axum::extract::DefaultBodyLimit::max(64 * 1024 * 1024))
Expand Down Expand Up @@ -180,6 +198,63 @@ async fn health(State(app): State<Arc<App>>) -> Response {
}
}

/// The `/metrics` body: the two gauges, the counters and the summaries, in the Prometheus text
/// exposition format. Built from the statics alone, so a test reads the exposition without a server.
fn metrics_body(running: u32, waiting: u32) -> String {
format!(
"# TYPE tensorfold:requests_running gauge\ntensorfold:requests_running {running}\n\
# TYPE tensorfold:requests_waiting gauge\ntensorfold:requests_waiting {waiting}\n\
# TYPE tensorfold:generation_tokens_total counter\ntensorfold:generation_tokens_total {}\n\
# TYPE tensorfold:prompt_tokens_total counter\ntensorfold:prompt_tokens_total {}\n\
# TYPE tensorfold:prompt_tokens_cached_total counter\ntensorfold:prompt_tokens_cached_total {}\n\
# TYPE tensorfold:time_to_first_token_seconds summary\ntensorfold:time_to_first_token_seconds_sum {}\ntensorfold:time_to_first_token_seconds_count {}\n\
# TYPE tensorfold:request_prefill_seconds summary\ntensorfold:request_prefill_seconds_sum {}\ntensorfold:request_prefill_seconds_count {}\n",
GEN_TOTAL.load(Ordering::Relaxed), PROMPT_TOTAL.load(Ordering::Relaxed), CACHED_TOTAL.load(Ordering::Relaxed),
TTFT_US_SUM.load(Ordering::Relaxed) as f64 / 1e6, TTFT_COUNT.load(Ordering::Relaxed),
PREFILL_US_SUM.load(Ordering::Relaxed) as f64 / 1e6, PREFILL_COUNT.load(Ordering::Relaxed)
)
}

/// Load gauges for the pipeline scheduler and sparkDash, under the names the TensorFold serve used
/// (`tensorfold:requests_running`, `tensorfold:requests_waiting`). Unauthenticated, like /health.
async fn metrics(State(app): State<Arc<App>>) -> Response {
let (running, waiting) = app.gate.load();
(StatusCode::OK, [("content-type", "text/plain; version=0.0.4")], metrics_body(running, waiting)).into_response()
}

#[cfg(test)]
mod metrics_tests {
use super::*;

/// Every series a scraper reads is present and every sample is a number: a missing or misnamed
/// series is how a dashboard silently shows nothing.
#[test]
fn the_exposition_has_every_series() {
let body = metrics_body(2, 1);
let series = [
"tensorfold:requests_running 2",
"tensorfold:requests_waiting 1",
"tensorfold:generation_tokens_total ",
"tensorfold:prompt_tokens_total ",
"tensorfold:prompt_tokens_cached_total ",
"tensorfold:time_to_first_token_seconds_sum ",
"tensorfold:time_to_first_token_seconds_count ",
"tensorfold:request_prefill_seconds_sum ",
"tensorfold:request_prefill_seconds_count ",
];
for want in series {
assert!(body.contains(want), "{want} missing from /metrics:\n{body}");
}
let samples: Vec<&str> = body.lines().filter(|l| l.starts_with("tensorfold:")).collect();
assert_eq!(samples.len(), series.len(), "/metrics:\n{body}");
for line in samples {
let (name, value) = line.rsplit_once(' ').expect("a sample line has a value");
assert!(value.parse::<f64>().is_ok(), "not a number: {line}");
assert!(name.starts_with("tensorfold:"), "unprefixed series: {line}");
}
}
}

async fn models(State(app): State<Arc<App>>, headers: HeaderMap) -> Response {
if let Err(r) = check_auth(&app, &headers) {
return r;
Expand Down Expand Up @@ -525,6 +600,7 @@ impl Gen {
match ev {
EngineEvent::Tokens(t) => {
self.first_token.get_or_insert_with(Instant::now);
GEN_TOTAL.fetch_add(t.ids.len() as u64, Ordering::Relaxed);
for &id in &t.ids {
self.ids.push(id);
if self.stopped.is_some() {
Expand Down Expand Up @@ -593,9 +669,18 @@ impl Gen {
_ => 0,
};
self.app.sessions.lock().unwrap().finish(self.session_id, &self.prompt_text, &self.prompt_ids, &self.ids, &self.app.tok);
let usage = Usage { prompt: self.prompt_ids.len(), cached: d.cached_tokens, completion: self.kept, reasoning };
// cached is the reused prefix of the prompt, not an extra counter: sparkDash
// derives prefill as prompt - cached, so clamp instead of letting it exceed.
let prompt = self.prompt_ids.len();
let usage = Usage { prompt, cached: d.cached_tokens.min(prompt as u32), completion: self.kept, reasoning };
let total = self.t0.elapsed().as_secs_f64();
let ttft = self.first_token.map_or(total, |t| (t - self.t0).as_secs_f64());
PROMPT_TOTAL.fetch_add(usage.prompt as u64, Ordering::Relaxed);
CACHED_TOTAL.fetch_add(usage.cached as u64, Ordering::Relaxed);
TTFT_US_SUM.fetch_add((ttft * 1e6) as u64, Ordering::Relaxed);
TTFT_COUNT.fetch_add(1, Ordering::Relaxed);
PREFILL_US_SUM.fetch_add(d.prefill_us, Ordering::Relaxed);
PREFILL_COUNT.fetch_add(1, Ordering::Relaxed);
if let Some(dir) = &self.app.cfg.dump_dir {
// the output's ids: the first `kept` count as output, the rest came after a stop
let rec = json!({"req_id": self.req_id, "ids": self.ids, "kept": self.kept, "finish": finish.as_str(),
Expand Down