Expose native generation activity and DONE metrics

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 05:11:02 +02:00
parent d179dc4d0b
commit 85bacce3b7
8 changed files with 350 additions and 3 deletions
+77
View File
@@ -59,6 +59,7 @@ pub fn router(state: AppState) -> Router {
.route("/health", get(health))
.route("/ready", get(ready))
.route("/status", get(status))
.route("/metrics", get(metrics))
.route("/v1/responses", post(responses::create))
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
@@ -72,6 +73,28 @@ async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
async fn metrics(State(state): State<AppState>) -> Json<serde_json::Value> {
let worker = *state.worker.read().await;
let generation = worker.metrics;
let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity);
let queue_used = state
.generation
.as_ref()
.map(|sender| sender.max_capacity() - sender.capacity());
Json(serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
"model": state.model,
"worker": worker.state,
"active": generation.active_since.is_some(),
"active_elapsed_ms": generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64),
"queue_capacity": queue_capacity,
"queue_used": queue_used,
"generation": generation,
"done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms),
}))
}
async fn ready(State(state): State<AppState>) -> (StatusCode, Json<StatusResponse>) {
let worker = *state.worker.read().await;
let inference_ready = worker.state == WorkerState::Ready
@@ -110,3 +133,57 @@ fn status_body(
max_context: worker.max_context,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = mpsc::channel(2);
let state = AppState {
generation: Some(sender.clone()),
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
let initial_metrics = metrics(State(state.clone())).await.0;
assert_eq!(initial_metrics["active"], false);
assert!(initial_metrics["done_decode_tokens_per_second"].is_null());
let (result, _rx) = tokio::sync::oneshot::channel();
sender
.send(GenerationCommand {
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
temperature: None,
top_p: None,
},
result: crate::worker::GenerationResult::Buffered(result),
})
.await
.unwrap();
state.worker.write().await.metrics.start();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/metrics", listener.local_addr().unwrap());
let router = router(state.clone());
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let response = reqwest::get(url).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "application/json");
let body: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(body["active"], true);
assert!(body["active_elapsed_ms"].is_u64());
assert_eq!(body["generation"]["started"], 1);
assert_eq!(body["queue_capacity"], 2);
assert_eq!(body["queue_used"], 1);
assert!(body["generation"].get("active_since").is_none());
assert_eq!(
serde_json::to_value(status(State(state.clone())).await.0).unwrap(),
initial_status
);
receiver.recv().await.unwrap();
assert_eq!(metrics(State(state)).await.0["queue_used"], 0);
server.abort();
}
}
+1 -1
View File
@@ -144,7 +144,7 @@ mod tests {
let server =
tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let client = reqwest::Client::new();
for path in ["/status", "/ready", "/v1/responses", "/unknown"] {
for path in ["/status", "/metrics", "/ready", "/v1/responses", "/unknown"] {
let response = client
.post(format!("{url}{path}"))
.body("not json")
+1
View File
@@ -18,6 +18,7 @@ pub mod kar_quality;
pub mod kar_sample;
pub mod kar_stream_encode;
pub mod kar_writer;
pub mod metrics;
pub mod model;
pub mod model_pipeline;
pub mod prepare_preview;
+120
View File
@@ -0,0 +1,120 @@
//! Payload-free engine telemetry, scoped to one control-plane process.
use std::time::Instant;
use serde::Serialize;
use crate::wire::{Done, Finish};
#[derive(Clone, Copy, Default, Serialize)]
pub struct GenerationMetrics {
#[serde(skip)]
pub active_since: Option<Instant>,
pub started: u64,
pub completed: u64,
pub cancelled: u64,
pub failed_or_interrupted: u64,
pub done_generated_tokens: u64,
pub done_prompt_tokens: u64,
pub done_decode_ms: f64,
pub done_prefill_ms: f64,
pub last_done: Option<GenerationSummary>,
}
#[derive(Clone, Copy, Serialize)]
pub struct GenerationSummary {
pub generated_tokens: u64,
pub prompt_tokens: u64,
pub prefill_ms: f64,
pub decode_ms: f64,
pub decode_tokens_per_second: Option<f64>,
pub finish: &'static str,
pub reused_tokens: Option<u64>,
pub drafts_accepted: Option<u64>,
pub drafts_offered: Option<u64>,
pub expert_hits: Option<u64>,
pub expert_lookups: Option<u64>,
}
pub fn token_rate(tokens: u64, milliseconds: f64) -> Option<f64> {
let rate = tokens as f64 / milliseconds * 1000.0;
(milliseconds > 0.0 && rate.is_finite()).then_some(rate)
}
impl GenerationMetrics {
pub fn start(&mut self) {
self.started = self.started.saturating_add(1);
self.active_since = Some(Instant::now());
}
pub fn fail(&mut self) {
if self.active_since.take().is_some() {
self.failed_or_interrupted = self.failed_or_interrupted.saturating_add(1);
}
}
pub fn finish(&mut self, done: &Done, disconnected: bool) {
self.active_since = None;
if disconnected || done.finish == Finish::Cancel {
self.cancelled = self.cancelled.saturating_add(1);
} else {
self.completed = self.completed.saturating_add(1);
}
self.done_generated_tokens = self.done_generated_tokens.saturating_add(done.generated);
self.done_prompt_tokens = self.done_prompt_tokens.saturating_add(done.prompt_tokens);
// Parser rejects negative/nonfinite individual timings; cap sum overflow.
self.done_decode_ms = (self.done_decode_ms + done.decode_ms).min(f64::MAX);
self.done_prefill_ms = (self.done_prefill_ms + done.prompt_ms).min(f64::MAX);
self.last_done = Some(GenerationSummary {
generated_tokens: done.generated,
prompt_tokens: done.prompt_tokens,
prefill_ms: done.prompt_ms,
decode_ms: done.decode_ms,
decode_tokens_per_second: token_rate(done.generated, done.decode_ms),
finish: match done.finish {
Finish::Stop => "stop",
Finish::Length => "length",
Finish::Cancel => "cancel",
},
reused_tokens: done.reused,
drafts_accepted: done.drafts_accepted,
drafts_offered: done.drafts_offered,
expert_hits: done.expert_hits,
expert_lookups: done.expert_lookups,
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unavailable_rates_are_null_and_disconnected_done_is_cancelled() {
assert_eq!(token_rate(10, 0.0), None);
assert_eq!(token_rate(10, f64::MIN_POSITIVE), None);
assert_eq!(token_rate(10, 20.0), Some(500.0));
let crate::wire::Event::Done(done) = crate::wire::parse_line("DONE 2 3 1.0 4.0 stop")
.unwrap()
.unwrap()
else {
panic!()
};
let mut metrics = GenerationMetrics::default();
metrics.start();
metrics.finish(&done, true);
metrics.fail();
assert_eq!(
(
metrics.completed,
metrics.cancelled,
metrics.failed_or_interrupted
),
(0, 1, 0)
);
assert_eq!(metrics.last_done.unwrap().finish, "stop");
assert_eq!(
token_rate(metrics.done_generated_tokens, metrics.done_decode_ms),
Some(500.0)
);
}
}
+72 -2
View File
@@ -59,6 +59,7 @@ pub enum WorkerState {
pub struct WorkerStatus {
pub state: WorkerState,
pub max_context: Option<usize>,
pub metrics: crate::metrics::GenerationMetrics,
}
impl Default for WorkerStatus {
@@ -66,6 +67,7 @@ impl Default for WorkerStatus {
Self {
state: WorkerState::Unconfigured,
max_context: None,
metrics: Default::default(),
}
}
}
@@ -250,7 +252,7 @@ async fn run_session(
match command {
Some(command) => {
tokio::select! {
result = generate(&mut stdin, &mut lines, command, max_context) => {
result = generate(&mut stdin, &mut lines, command, max_context, status) => {
if let Err(error) = result {
eprintln!("Strata engine protocol failed: {error}");
update(status, WorkerState::Failed, None).await;
@@ -277,6 +279,7 @@ async fn generate(
lines: &mut tokio::io::Lines<BufReader<tokio::process::ChildStdout>>,
mut command: GenerationCommand,
max_context: usize,
status: &RwLock<WorkerStatus>,
) -> Result<(), String> {
if command.result.is_closed() {
return Ok(());
@@ -301,6 +304,7 @@ async fn generate(
return Ok(());
}
};
status.write().await.metrics.start();
let pipe = stdin.as_mut().ok_or("engine stdin is closed")?;
pipe.write_all(request.as_bytes())
.await
@@ -328,10 +332,18 @@ async fn generate(
.ok_or("engine exited before a terminal line")?;
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
status.write().await.metrics.fail();
send_failure(command.result, message).await;
return Ok(());
}
Some(event @ Event::Done(_)) => {
if let Event::Done(done) = &event {
status
.write()
.await
.metrics
.finish(done, stopped || command.result.is_closed());
}
match command.result {
GenerationResult::Buffered(sender) => {
events.push(event);
@@ -374,7 +386,12 @@ fn parse_ready(line: &str) -> Option<usize> {
}
async fn update(status: &RwLock<WorkerStatus>, state: WorkerState, max_context: Option<usize>) {
*status.write().await = WorkerStatus { state, max_context };
let mut status = status.write().await;
if state != WorkerState::Ready {
status.metrics.fail();
}
status.state = state;
status.max_context = max_context;
}
async fn stop(child: &mut Child, stdin: &mut Option<ChildStdin>) {
@@ -511,6 +528,16 @@ mod tests {
assert_eq!(events[1], Event::Token(31));
assert_eq!(events[2], Event::Token(32));
assert!(matches!(events[3], Event::Done(_)));
let metrics = status.read().await.metrics;
assert_eq!(metrics.started, 1);
assert_eq!(metrics.completed, 1);
assert_eq!(metrics.done_generated_tokens, 2);
assert_eq!(metrics.done_prompt_tokens, 2);
assert_eq!(
metrics.last_done.unwrap().decode_tokens_per_second,
Some(1000.0)
);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
@@ -532,6 +559,20 @@ mod tests {
.unwrap_err()
.contains("exceed context")
);
assert_eq!(status.read().await.metrics.started, 1);
let (invalid, result) = command(vec![99], 1);
commands_tx.send(invalid).await.unwrap();
assert_eq!(result.await.unwrap().unwrap_err(), "unexpected request");
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
@@ -577,6 +618,7 @@ mod tests {
})
.await
.unwrap();
assert!(status.read().await.metrics.active_since.is_some());
drop(result_rx);
let (result_tx, result_rx) = oneshot::channel();
commands_tx
@@ -597,6 +639,13 @@ mod tests {
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
@@ -663,6 +712,13 @@ mod tests {
.unwrap()
.unwrap();
assert_eq!(next[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(metrics.started, metrics.completed, metrics.cancelled),
(2, 1, 1)
);
assert_eq!(metrics.failed_or_interrupted, 0);
assert!(metrics.active_since.is_none());
assert_eq!(status.read().await.state, WorkerState::Ready);
stop_tx.send(true).unwrap();
timeout(Duration::from_secs(5), task)
@@ -716,6 +772,9 @@ mod tests {
.unwrap();
assert_eq!(status.read().await.state, WorkerState::Stopping);
assert!(result_rx.await.is_err());
let metrics = status.read().await.metrics;
assert_eq!(metrics.failed_or_interrupted, 1);
assert!(metrics.active_since.is_none());
std::fs::remove_file(marker).unwrap();
}
@@ -903,6 +962,17 @@ mod tests {
.unwrap()
.unwrap();
assert_eq!(events[0], Event::Token(42));
let metrics = status.read().await.metrics;
assert_eq!(
(
metrics.started,
metrics.completed,
metrics.failed_or_interrupted
),
(2, 1, 1)
);
assert_eq!(metrics.cancelled, 0);
assert!(metrics.active_since.is_none());
assert_eq!(
std::fs::read_to_string(root.join("boots"))
.unwrap()
+39
View File
@@ -1,5 +1,44 @@
# Responses contract status
## Engine activity metrics
`GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional
bearer key as `/status`. This is a native JSON endpoint, not Prometheus text.
`/status` remains a stable discovery response. Metrics require the new binary;
the preserved console trial has not been upgraded to this feature.
- `active` and `active_elapsed_ms` cover an admitted generation from the attempt
to write `GEN` until engine `DONE`, `ERR`, or supervisor interruption. They
do not indicate GPU utilization or HTTP response completion.
- `queue_capacity` and `queue_used` describe the bounded command channel
(including reserved capacity), excluding the active command and HTTP handlers
waiting to enqueue. An unconfigured channel reports null. These snapshots
are observations, not an admission or safe-restart guarantee.
- `generation.started` counts admitted attempts. Context/validation rejections,
abandoned queued requests and requests rejected during restart are excluded.
`completed` counts non-cancelled DONEs, including length stops. `cancelled`
counts DONEs with cancel finish or a disconnected consumer. `failed_or_interrupted`
counts started attempts without DONE, including engine ERR, protocol failure,
expired cancellation drain and shutdown. Each attempt enters one terminal
bucket. Engine completion does not imply valid JSON/tool calls or task success.
- `done_generated_tokens`, `done_prompt_tokens`, `done_decode_ms`, and
`done_prefill_ms` sum engine DONE values, including cancelled generations.
Counts for failed attempts are unknown and excluded. Prompt counts are engine
input counts, not necessarily newly evaluated tokens. Integer totals saturate
at u64 max and timing totals at the largest finite f64.
- `done_decode_tokens_per_second` is total DONE tokens divided by total DONE
decode seconds. `last_done` exposes the last DONE's counts, milliseconds,
decode rate, raw finish reason, optional reused-token/draft/expert counters.
Unavailable counters and zero-duration/nonfinite rates are null. There is no
instantaneous token speed, prefill rate, TTFT, percentile or quality score.
Counters survive supervised child restarts and reset when the control-plane
process restarts. They contain no prompts, generated text, token IDs or keys.
Updates happen at generation boundaries; no per-token metrics lock is added.
Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support
observation; paired workload and quality measurements remain necessary for any
performance claim.
The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open.
The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility.
+29
View File
@@ -569,3 +569,32 @@ soak still remain; hosted Actions has not run.
Hosted CI and independent security review remain pending. This feature does
not add TLS, multi-user isolation or hot key rotation; loopback plus SSH
remains the console transport boundary.
## Native generation metrics — 2026-10-04
- STRA-18 adds a separate authenticated JSON `/metrics` endpoint. It reports
admitted generation activity, bounded channel occupancy, completion/cancellation/
failure counters, last DONE telemetry and weighted DONE decode rate. `/status`
stays unchanged for console discovery. No prompts, generated text or token IDs
are captured; metrics update only at generation boundaries.
- **124 Rust library tests** passed, along with formatting, Clippy all-targets
with warnings denied and a static Linux musl release build. Existing mock
worker checks now assert active state, cancellation and subsequent generation,
ERR without restart, context rejection exclusion, shutdown interruption and
counters surviving crash/restart. Token events and terminal ordering remain
identical to the fixtures (tolerance zero); no model parameters changed.
- A real HTTP CPU fixture verifies JSON schema, queue occupancy and stable
discovery. Rate tests cover zero duration, overflow and disconnected DONE.
The existing Linux auth smoke now checks protected and authenticated metrics,
initial null/zero values, and auth-off access. This extended smoke passed on
rnr5090 using a temporary process with no engine/GPU and is already included
by the existing CI smoke step. Hosted GitHub Actions have not run.
- Retained combined feature preview: 17,228,336 bytes, SHA-256
`389d7784c065f978a8b1d0a064b4f3b619e03c6a65895c64b89d278c383df798`.
It supersedes the previous feature preview only. The GPU trial binary and
SSH tunnel remain untouched; PID 4031422/start ticks 558428413 were confirmed.
The trial does not expose the new metrics until a deliberate future upgrade.
- Remote smoke files were removed, ephemeral test keys/configs were cleaned by
the smoke harness, and release cleanup freed 93.8 MiB. The reusable debug build
and private final preview remain. Independent QA and real-model telemetry
qualification are pending; this change claims no speedup or soak stability.
+11
View File
@@ -61,9 +61,19 @@ def main():
auth = (('Authorization', 'Bearer ' + token),)
assert request('/status')[0] == 401
assert request('/ready')[0] == 401
assert request('/metrics')[0] == 401
status = request('/status', auth)
assert status[0] == 200 and json.loads(status[2])['model'] == 'auth-cpu-smoke'
assert request('/ready', auth)[0] == 503
metrics = request('/metrics', auth)
assert metrics[0] == 200
observed = json.loads(metrics[2])
assert observed['schema_version'] == 1
assert observed['active'] is False and observed['active_elapsed_ms'] is None
assert observed['queue_capacity'] is None and observed['queue_used'] is None
assert observed['generation']['started'] == 0
assert observed['generation']['last_done'] is None
assert observed['done_decode_tokens_per_second'] is None
assert request('/v1/responses', auth, b'not-json')[0] == 400
finally:
process.terminate()
@@ -106,6 +116,7 @@ def main():
assert process.poll() is None and time.monotonic() < deadline
time.sleep(0.02)
assert request('/v1/responses', body=b'not-json')[0] == 400
assert request('/metrics')[0] == 200
finally:
process.terminate()
try: