Skip to main content

nmbrs_tui/
inspector_server.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Out-of-band introspection endpoint.
5//!
6//! Spawned at run start (TUI mode and tui=off both eligible)
7//! on a dedicated OS thread — never as a tokio task. Listens
8//! on a Unix domain socket under
9//! `${XDG_RUNTIME_DIR:-/tmp}/nmbrs-<pid>.sock`. The endpoint
10//! reads via [`crate::run_state_actor::RunStateHandle::load`]
11//! (a single atomic op), so it stays responsive even when
12//! tokio is wedged or the executor's drain loop is stuck.
13//!
14//! See SRD-02 §"Display and Diagnostic Decoupling" — this is
15//! the "poke and prod the machine while it's stuck" surface
16//! that section calls out as a first-class deliverable.
17//!
18//! ## Wire protocol
19//!
20//! Each connection handles exactly one request, then closes
21//! (HTTP/1.0-style — stateless, easy to reason about). Client
22//! writes a single line ending in `\n`; server replies with
23//! formatted text terminated by `\n` then closes the socket.
24//!
25//! ## Commands
26//!
27//! - `commands` — newline-separated list of command names.
28//!   Used by the inspector REPL for tab autocomplete.
29//! - `help` — human-readable help with one line per command.
30//! - `meta` — workload, scenario, adapter, profiler, limit.
31//! - `pid` — server process id (as a sanity check).
32//! - `snapshot` — multi-section dump combining `meta`,
33//!   `phases`, `latency`, and recent `log` entries.
34//! - `phases` — full phase list with status markers.
35//! - `active` — currently-running phases with live counters.
36//! - `latency` — current percentile readings.
37//! - `tree` — scenario tree as indented text.
38//! - `log [N]` — last N log entries (default 20, max 200).
39//! - `controls` — list every dynamic control declared in the
40//!   live component tree.
41//! - `set <name> <value> [source=<id>]` — write a dynamic
42//!   control via the session root walk-up (SRD 23).
43//! - `metrics` — list every `(family, label_set)` pair currently
44//!   present in the live component tree.
45//! - `metric <selector>` — read current values for matching
46//!   metric instance(s) using a Prometheus-style selector.
47
48use std::io::{BufRead, BufReader, Write};
49#[cfg(unix)]
50use std::os::unix::net::{UnixListener, UnixStream};
51// Windows has supported AF_UNIX sockets since Windows 10 1803,
52// but std doesn't expose them there — `uds_windows` mirrors the
53// std API surface we use (bind/incoming/connect/timeouts).
54use std::path::PathBuf;
55use std::sync::Arc;
56use std::sync::RwLock as StdRwLock;
57use std::thread;
58#[cfg(windows)]
59use uds_windows::{UnixListener, UnixStream};
60
61use crate::run_state_actor::RunStateHandle;
62use crate::state::{EntryKind, LogSeverity, PhaseStatus, RunState};
63
64use nmbrs_metrics::component::{self, Component};
65use nmbrs_metrics::controls::{ControlOrigin, SetError};
66use nmbrs_metrics::labels::Labels;
67use nmbrs_metrics::selector::Selector;
68use nmbrs_metrics::snapshot::MetricValue;
69
70/// Compute the socket path for the current process. Honors
71/// `XDG_RUNTIME_DIR` when set (per the freedesktop runtime
72/// convention) and falls back to `/tmp` otherwise. The pid is
73/// part of the filename so multiple concurrent nmbrs runs don't
74/// collide and the inspector can disambiguate them.
75pub fn socket_path_for(pid: u32) -> PathBuf {
76    let dir = std::env::var_os("XDG_RUNTIME_DIR")
77        .map(PathBuf::from)
78        .unwrap_or_else(|| {
79            if cfg!(windows) {
80                // No `/tmp` on Windows — use the real temp dir.
81                // Must stay in agreement with the REPL's
82                // `discover_sockets` scan dir.
83                std::env::temp_dir()
84            } else {
85                PathBuf::from("/tmp")
86            }
87        });
88    dir.join(format!("nmbrs-{pid}.sock"))
89}
90
91/// Spawn the inspector server thread. Returns the socket path
92/// it bound to (so the runner can log it) and a `JoinHandle`
93/// that the caller may keep or drop. The thread closes
94/// gracefully when its `RunStateHandle` clone is the only
95/// remaining sender — i.e. when the run has fully torn down.
96///
97/// `runtime` is an optional [`tokio::runtime::Handle`] captured
98/// at spawn time. When present, async control writes (`set
99/// <name> <value>`) run via `runtime.block_on(...)` on the
100/// per-connection thread; the inspector itself stays sync.
101/// When `None` (e.g. test harnesses without a tokio runtime),
102/// the `set` command rejects with `ERR no_runtime` and reads
103/// keep working.
104///
105/// On bind failure the function returns `Err` and the run
106/// continues without an inspector (this is a diagnostic
107/// affordance, not a critical path).
108pub fn spawn(
109    state: RunStateHandle,
110    runtime: Option<tokio::runtime::Handle>,
111) -> std::io::Result<(PathBuf, thread::JoinHandle<()>)> {
112    let path = socket_path_for(std::process::id());
113    spawn_at(path, state, runtime)
114}
115
116/// Variant of [`spawn`] that binds a caller-chosen path.
117/// Useful for tests (unique tempfile paths so parallel tests
118/// don't collide) and any future deployment where the runtime
119/// directory convention isn't appropriate.
120pub fn spawn_at(
121    path: PathBuf,
122    state: RunStateHandle,
123    runtime: Option<tokio::runtime::Handle>,
124) -> std::io::Result<(PathBuf, thread::JoinHandle<()>)> {
125    // Best-effort cleanup of any stale socket from a previous
126    // run that crashed without removing its file. A live socket
127    // bound by another process won't unlink — that just makes
128    // our bind fail below, which is correct.
129    let _ = std::fs::remove_file(&path);
130
131    let listener = UnixListener::bind(&path)?;
132    // Non-blocking is unnecessary here: each accept blocks until
133    // a client connects, and per-connection work runs on a
134    // freshly-spawned thread. The listener thread itself is
135    // dedicated.
136
137    let path_for_thread = path.clone();
138    let handle = thread::Builder::new()
139        .name("inspector-server".into())
140        .spawn(move || {
141            run_accept_loop(listener, state, runtime, path_for_thread);
142        })?;
143
144    Ok((path, handle))
145}
146
147fn run_accept_loop(
148    listener: UnixListener,
149    state: RunStateHandle,
150    runtime: Option<tokio::runtime::Handle>,
151    path: PathBuf,
152) {
153    for incoming in listener.incoming() {
154        match incoming {
155            Ok(stream) => {
156                let state_for_conn = state.clone();
157                let runtime_for_conn = runtime.clone();
158                // One short-lived OS thread per connection.
159                // Connections are bounded by client count
160                // (always 1-2 inspector REPLs in practice);
161                // spinning up a fresh thread keeps the
162                // accept-loop dispatching even if a handler
163                // hangs on a slow write.
164                let _ = thread::Builder::new()
165                    .name("inspector-conn".into())
166                    .spawn(move || {
167                        let _ =
168                            handle_connection(stream, &state_for_conn, runtime_for_conn.as_ref());
169                    });
170            }
171            Err(_) => {
172                // Listener errored — typically only if the
173                // socket file was removed externally. Bail
174                // out of the accept loop; the runner can
175                // notice via the JoinHandle.
176                break;
177            }
178        }
179    }
180    // Best-effort cleanup of the socket file on shutdown.
181    let _ = std::fs::remove_file(&path);
182}
183
184fn handle_connection(
185    stream: UnixStream,
186    state: &RunStateHandle,
187    runtime: Option<&tokio::runtime::Handle>,
188) -> std::io::Result<()> {
189    let mut reader = BufReader::new(stream.try_clone()?);
190    let mut request = String::new();
191    if reader.read_line(&mut request)? == 0 {
192        return Ok(()); // empty connection
193    }
194    let response = dispatch(request.trim(), state, runtime);
195    let mut stream = stream;
196    stream.write_all(response.as_bytes())?;
197    if !response.ends_with('\n') {
198        stream.write_all(b"\n")?;
199    }
200    stream.flush()?;
201    // Caller closes stream by drop.
202    Ok(())
203}
204
205/// Inspector command dispatch surface. Public to the crate so
206/// the in-process nb-shell prompt (`crate::prompt_state`) can
207/// invoke the same commands the unix-socket inspector accepts,
208/// without re-implementing the parser.
209pub(crate) fn dispatch(
210    line: &str,
211    state: &RunStateHandle,
212    runtime: Option<&tokio::runtime::Handle>,
213) -> String {
214    // Split on first whitespace: command + tail (used by `log N`).
215    let mut parts = line.splitn(2, char::is_whitespace);
216    let cmd = parts.next().unwrap_or("").to_ascii_lowercase();
217    let tail = parts.next().unwrap_or("").trim();
218
219    match cmd.as_str() {
220        "" => "ERR empty command — try `help`".into(),
221        "commands" => COMMAND_NAMES.join("\n"),
222        "help" => render_help(),
223        "pid" => format!("{}", std::process::id()),
224        "meta" => render_meta(&state.load()),
225        "snapshot" => render_snapshot(&state.load()),
226        "phases" => render_phases(&state.load()),
227        "active" => render_active(&state.load()),
228        "latency" => render_latency(&state.load()),
229        "tree" => render_tree(&state.load()),
230        "log" => {
231            let n: usize = tail.parse().ok().unwrap_or(20).min(200);
232            render_log(&state.load(), n)
233        }
234        "controls" => render_controls(),
235        "set" => render_set(tail, runtime),
236        "metrics" => render_metrics(),
237        "metric" => render_metric(tail),
238        "readout" => render_readout(&state.load(), tail),
239        other => format!("ERR unknown command '{other}' — try `help`"),
240    }
241}
242
243/// Canonical command names. `pub` so both the in-process
244/// nb-shell prompt (`crate::prompt_state`) and the nmbrs CLI's
245/// `attach --command` completion power Tab against the same
246/// set the unix-socket inspector accepts.
247pub const COMMAND_NAMES: &[&str] = &[
248    "commands", "help", "meta", "pid", "snapshot", "phases", "active", "latency", "tree", "log",
249    "controls", "set", "metrics", "metric", "readout",
250];
251
252fn render_help() -> String {
253    let mut s = String::from("nmbrs inspector — out-of-band introspection\n\n");
254    let lines: &[(&str, &str)] = &[
255        (
256            "commands",
257            "list command names (one per line) — used for autocomplete",
258        ),
259        ("help", "this message"),
260        ("meta", "workload, scenario, adapter, profiler, limit"),
261        ("pid", "server process id"),
262        (
263            "snapshot",
264            "combined dump: meta + phases + latency + recent log",
265        ),
266        ("phases", "all phases with status markers"),
267        ("active", "currently-running phases with live counters"),
268        ("latency", "current latency percentiles (ns)"),
269        ("tree", "scenario tree as indented text"),
270        ("log [N]", "last N log entries (default 20, max 200)"),
271        (
272            "controls",
273            "list every dynamic control in the live component tree",
274        ),
275        (
276            "set <name> <value> [source=<id>]",
277            "write a dynamic control (default source=inspector)",
278        ),
279        (
280            "metrics",
281            "list every (family, labels) pair in the live tree",
282        ),
283        (
284            "metric <selector>",
285            "read matching metric instance(s) — Prometheus-style selector",
286        ),
287        (
288            "readout [name]",
289            "render the SRD-63 readout of the given name (default `phase_status`) \
290                       against the latest active phase; ANSI-stripped plain text",
291        ),
292    ];
293    for (name, descr) in lines {
294        s.push_str(&format!("  {:<36} {}\n", name, descr));
295    }
296    s
297}
298
299fn render_meta(state: &RunState) -> String {
300    let mut s = String::new();
301    s.push_str(&format!("workload : {}\n", state.workload_file));
302    s.push_str(&format!("scenario : {}\n", state.scenario_name));
303    s.push_str(&format!("adapter  : {}\n", state.adapter));
304    s.push_str(&format!("profiler : {}\n", state.profiler));
305    s.push_str(&format!("limit    : {}\n", state.limit));
306    s.push_str(&format!("elapsed  : {:.2}s\n", state.elapsed_secs()));
307    s.push_str(&format!("finished : {}\n", state.finished));
308    if let Some(sink) = nmbrs_runtime::log_sink::global() {
309        let dropped = sink.dropped_count();
310        if dropped > 0 {
311            s.push_str(&format!("log lines dropped: {dropped} (sink overflow)\n"));
312        }
313    }
314    s
315}
316
317fn render_phases(state: &RunState) -> String {
318    if state.phases.is_empty() {
319        return "(no phases)".into();
320    }
321    let mut s = String::new();
322    for p in &state.phases {
323        let indent = " ".repeat(p.depth);
324        let marker = match &p.status {
325            PhaseStatus::Pending => "[  ]",
326            PhaseStatus::Running => "[..]",
327            PhaseStatus::Completed => "[ok]",
328            PhaseStatus::Failed(_) => "[!!]",
329        };
330        let kind = match p.kind {
331            EntryKind::Phase => "phase",
332            EntryKind::Scope => "scope",
333            EntryKind::Root => "root",
334        };
335        let labels = if p.labels.is_empty() {
336            String::new()
337        } else {
338            format!(" ({})", p.labels)
339        };
340        let dur = p
341            .duration_secs
342            .map(|d| format!(" {d:.2}s"))
343            .unwrap_or_default();
344        s.push_str(&format!(
345            "{indent}{marker} {kind:5} {}{labels}{dur}\n",
346            p.name
347        ));
348    }
349    s
350}
351
352fn render_active(state: &RunState) -> String {
353    if state.active_phases.is_empty() {
354        return "(no active phases)".into();
355    }
356    let mut entries: Vec<_> = state.active_phases.values().collect();
357    entries.sort_by(|a, b| a.name.cmp(&b.name).then(a.labels.cmp(&b.labels)));
358
359    let mut s = String::new();
360    for a in entries {
361        let labels = if a.labels.is_empty() {
362            String::new()
363        } else {
364            format!(" ({})", a.labels)
365        };
366        s.push_str(&format!("phase: {}{labels}\n", a.name));
367        s.push_str(&format!(
368            "  cursor       : {} ({}/{})\n",
369            a.cursor_name, a.ops_finished, a.cursor_extent
370        ));
371        s.push_str(&format!("  fibers       : {}\n", a.fibers));
372        s.push_str(&format!("  ops/sec      : {:.1}\n", a.ops_per_sec));
373        s.push_str(&format!("  ops_started  : {}\n", a.ops_started));
374        s.push_str(&format!("  ops_finished : {}\n", a.ops_finished));
375        s.push_str(&format!("  ops_ok       : {}\n", a.ops_ok));
376        s.push_str(&format!("  errors       : {}\n", a.errors));
377        s.push_str(&format!("  retries      : {}\n", a.retries));
378        if !a.adapter_counters.is_empty() {
379            s.push_str("  adapter:\n");
380            for (n, t, r) in &a.adapter_counters {
381                s.push_str(&format!("    {n:<14} total={t} rate={r:.1}/s\n"));
382            }
383        }
384        if !a.relevancy.is_empty() {
385            s.push_str("  relevancy:\n");
386            for (n, w, t, c, l) in &a.relevancy {
387                s.push_str(&format!(
388                    "    {n:<14} window={w:.4} total={t:.4} count={c} window_len={l}\n"
389                ));
390            }
391        }
392    }
393    s
394}
395
396fn render_latency(state: &RunState) -> String {
397    let mut s = String::from("current latency (ns):\n");
398    s.push_str(&format!("  min   : {}\n", state.min_nanos));
399    s.push_str(&format!("  p50   : {}\n", state.p50_nanos));
400    s.push_str(&format!("  p90   : {}\n", state.p90_nanos));
401    s.push_str(&format!("  p99   : {}\n", state.p99_nanos));
402    s.push_str(&format!("  p999  : {}\n", state.p999_nanos));
403    s.push_str(&format!("  max   : {}\n", state.max_nanos));
404    s
405}
406
407fn render_tree(state: &RunState) -> String {
408    if state.phases.is_empty() {
409        return "(no scenario tree)".into();
410    }
411    // Same shape as `phases` for now — the tree is already a
412    // DFS-flattened list with `depth`. Distinguishes scope
413    // headers visually so the indent structure reads cleanly.
414    let mut s = String::new();
415    for p in &state.phases {
416        let indent = " ".repeat(p.depth);
417        match p.kind {
418            EntryKind::Scope => {
419                s.push_str(&format!("{indent}· {}\n", p.labels));
420            }
421            EntryKind::Phase => {
422                let labels = if p.labels.is_empty() {
423                    String::new()
424                } else {
425                    format!(" ({})", p.labels)
426                };
427                let status = match &p.status {
428                    PhaseStatus::Pending => "○",
429                    PhaseStatus::Running => "▶",
430                    PhaseStatus::Completed => "✓",
431                    PhaseStatus::Failed(_) => "✗",
432                };
433                s.push_str(&format!("{indent}{status} {}{labels}\n", p.name));
434            }
435            EntryKind::Root => {}
436        }
437    }
438    s
439}
440
441fn render_log(state: &RunState, n: usize) -> String {
442    if state.log_messages.is_empty() {
443        return "(no log entries)".into();
444    }
445    let start = state.log_messages.len().saturating_sub(n);
446    let mut s = String::new();
447    for entry in &state.log_messages[start..] {
448        let tag = match entry.severity {
449            LogSeverity::Debug => "DBG",
450            LogSeverity::Info => "INF",
451            LogSeverity::Warn => "WRN",
452            LogSeverity::Error => "ERR",
453        };
454        s.push_str(&format!("{tag} {}\n", entry.message));
455    }
456    s
457}
458
459fn render_snapshot(state: &RunState) -> String {
460    let mut s = String::new();
461    s.push_str("=== meta ===\n");
462    s.push_str(&render_meta(state));
463    s.push_str("\n=== phases ===\n");
464    s.push_str(&render_phases(state));
465    s.push_str("\n=== active ===\n");
466    s.push_str(&render_active(state));
467    s.push_str("\n=== latency ===\n");
468    s.push_str(&render_latency(state));
469    s.push_str("\n=== recent log (last 20) ===\n");
470    s.push_str(&render_log(state, 20));
471    s
472}
473
474// ─── Controls (SRD 23) ───────────────────────────────────────
475
476/// One row in the `controls` listing. Matches the structure of
477/// `nmbrs-web::routes::list_controls` but rendered as text.
478fn render_controls() -> String {
479    let Some(root) = nmbrs_runtime::polydat_nodes::runtime_context::session_root_handle() else {
480        return "(no session)".into();
481    };
482    let mut rows: Vec<String> = Vec::new();
483    for comp in component::find(&root, &Selector::new()) {
484        let Ok(guard) = comp.read() else {
485            continue;
486        };
487        let path = labels_to_path(guard.effective_labels());
488        for ctl in guard.controls().list() {
489            let scope = match ctl.branch_scope() {
490                nmbrs_metrics::controls::BranchScope::Local => "local",
491                nmbrs_metrics::controls::BranchScope::Subtree => "subtree",
492            };
493            let final_marker = match ctl.final_scope() {
494                Some(s) => format!("final@{s}"),
495                None => "-".to_string(),
496            };
497            rows.push(format!(
498                "{path} | {name} | {ty} | {value} | rev={rev} | scope={scope} | {final_marker}",
499                path = if path.is_empty() {
500                    "<root>"
501                } else {
502                    path.as_str()
503                },
504                name = ctl.name(),
505                ty = ctl.value_type_name(),
506                value = ctl.value_string(),
507                rev = ctl.rev(),
508            ));
509        }
510    }
511    if rows.is_empty() {
512        return "(no controls declared)".into();
513    }
514    rows.sort();
515    rows.join("\n")
516}
517
518fn labels_to_path(labels: &Labels) -> String {
519    labels
520        .iter()
521        .map(|(k, v)| format!("{k}={v}"))
522        .collect::<Vec<_>>()
523        .join(",")
524}
525
526/// `set <name> <value> [source=<id>]`. Mirrors the web route
527/// `POST /api/control/{name}`. The server thread is sync; we
528/// drive the async `erased.set_f64(...)` via the captured tokio
529/// runtime handle, blocking the per-connection thread (NOT the
530/// async runtime worker pool) until the applier completes.
531fn render_set(tail: &str, runtime: Option<&tokio::runtime::Handle>) -> String {
532    let mut tokens = tail.split_whitespace();
533    let Some(name) = tokens.next() else {
534        return "ERR parse: missing name. Usage: set <name> <value> [source=<id>]".into();
535    };
536    let Some(value_str) = tokens.next() else {
537        return "ERR parse: missing value. Usage: set <name> <value> [source=<id>]".into();
538    };
539    let value: f64 = match value_str.parse() {
540        Ok(v) => v,
541        Err(_) => return format!("ERR parse: value '{value_str}' is not a number"),
542    };
543    let mut source = "inspector".to_string();
544    for extra in tokens {
545        if let Some(s) = extra.strip_prefix("source=") {
546            source = s.to_string();
547        } else {
548            return format!("ERR parse: unexpected token '{extra}'");
549        }
550    }
551
552    let Some(rt) = runtime else {
553        return "ERR no_runtime: inspector server has no tokio runtime handle; \
554                control writes are unavailable"
555            .into();
556    };
557    let Some(root) = nmbrs_runtime::polydat_nodes::runtime_context::session_root_handle() else {
558        return format!("ERR no_session: no active session; cannot resolve control '{name}'");
559    };
560
561    let erased = {
562        let Ok(guard) = root.read() else {
563            return "ERR session_poisoned: session root RwLock is poisoned".to_string();
564        };
565        match guard.find_control_erased_up(name) {
566            Some(e) => e,
567            None => {
568                return format!("ERR not_found: no control named '{name}' via walk-up");
569            }
570        }
571    };
572
573    let origin = ControlOrigin::Api { source };
574    let name_owned = name.to_string();
575    // block_on runs the future on the per-connection thread — we
576    // are NOT inside the tokio runtime, so this is safe (no
577    // worker-thread starvation). The future itself runs on the
578    // tokio runtime via the captured handle.
579    match rt.block_on(async move { erased.set_f64(value, origin).await }) {
580        Ok(rev) => format!("OK {name_owned} rev={rev} value={value}"),
581        Err(e) => match &e {
582            SetError::ValidationFailed(m) => format!("ERR validation_failed: {m}"),
583            SetError::ApplyFailed(fs) => {
584                let joined = fs
585                    .iter()
586                    .map(|f| format!("#{}: {}", f.applier_index, f.message))
587                    .collect::<Vec<_>>()
588                    .join("; ");
589                format!("ERR apply_failed: {joined}")
590            }
591            SetError::FinalViolation { scope } => {
592                format!("ERR final_violation: control is final at scope '{scope}'")
593            }
594        },
595    }
596}
597
598// ─── Metrics enumeration / query ─────────────────────────────
599
600/// `(family_name, label_set)` tuple used for the `metrics`
601/// listing. Walks the live tree, collecting every metric instance
602/// the live instrument sets currently expose plus every reified
603/// control gauge.
604struct MetricInstance {
605    family: String,
606    labels: Labels,
607    value: MetricValue,
608}
609
610/// Walk the component tree and return one [`MetricInstance`] per
611/// `(family, label_set)` pair currently present. Reads via the
612/// non-draining `capture_current` so the inspector never disturbs
613/// the cadence reporter's accumulators.
614///
615/// This is the canonical "list every (family, labels) pair across
616/// the live component tree" helper for diagnostic surfaces. The
617/// scheduler's own walk uses `capture_tree(_current)` and merges
618/// into snapshots; we just flatten the same trees into a value
619/// list.
620fn walk_live_metrics(root: &Arc<StdRwLock<Component>>) -> Vec<MetricInstance> {
621    let mut out = Vec::new();
622    for (_, set) in component::capture_tree_current(root) {
623        for family in set.families() {
624            for metric in family.metrics() {
625                let Some(point) = metric.point() else {
626                    continue;
627                };
628                out.push(MetricInstance {
629                    family: family.name().to_string(),
630                    labels: metric.labels().clone(),
631                    value: point.value().clone(),
632                });
633            }
634        }
635    }
636    out
637}
638
639fn render_metrics() -> String {
640    let Some(root) = nmbrs_runtime::polydat_nodes::runtime_context::session_root_handle() else {
641        return "(no session)".into();
642    };
643    let instances = walk_live_metrics(&root);
644    if instances.is_empty() {
645        return "(no metrics)".into();
646    }
647    let mut rows: Vec<String> = instances
648        .iter()
649        .map(|m| format!("{}{}", m.family, m.labels.to_prometheus()))
650        .collect();
651    rows.sort();
652    rows.dedup();
653    rows.join("\n")
654}
655
656/// Parsed selector from `metric <selector>`. Family `None` means
657/// the wildcard `*`; otherwise the family name must match exactly.
658struct MetricSelector {
659    family: Option<String>,
660    label_eq: Vec<(String, String)>,
661}
662
663impl MetricSelector {
664    fn parse(input: &str) -> Result<Self, String> {
665        let s = input.trim();
666        if s.is_empty() {
667            return Err("missing selector. Usage: metric <family>{k=v,...}".into());
668        }
669        let (family_part, body) = match s.find('{') {
670            Some(idx) => {
671                let (f, rest) = s.split_at(idx);
672                if !rest.ends_with('}') {
673                    return Err("selector body must be wrapped in {...}".into());
674                }
675                (f, &rest[1..rest.len() - 1])
676            }
677            None => (s, ""),
678        };
679        let family = match family_part.trim() {
680            "" => return Err("missing family. Usage: metric <family>{k=v,...}".into()),
681            "*" => None,
682            other => {
683                if !other
684                    .chars()
685                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')
686                {
687                    return Err(format!("invalid family '{other}'"));
688                }
689                Some(other.to_string())
690            }
691        };
692        let mut label_eq: Vec<(String, String)> = Vec::new();
693        for piece in body.split(',') {
694            let p = piece.trim();
695            if p.is_empty() {
696                continue;
697            }
698            let Some((k, v)) = p.split_once('=') else {
699                return Err(format!("expected k=v in selector body, got '{p}'"));
700            };
701            let k = k.trim();
702            let v = v.trim();
703            if k.is_empty() || v.is_empty() {
704                return Err(format!("empty key or value in '{p}'"));
705            }
706            label_eq.push((k.to_string(), v.to_string()));
707        }
708        Ok(Self { family, label_eq })
709    }
710
711    fn matches(&self, family: &str, labels: &Labels) -> bool {
712        if let Some(ref name) = self.family
713            && name != family
714        {
715            return false;
716        }
717        for (k, v) in &self.label_eq {
718            if labels.get(k) != Some(v.as_str()) {
719                return false;
720            }
721        }
722        true
723    }
724}
725
726fn render_metric(tail: &str) -> String {
727    let sel = match MetricSelector::parse(tail) {
728        Ok(s) => s,
729        Err(e) => return format!("ERR parse: {e}"),
730    };
731    let Some(root) = nmbrs_runtime::polydat_nodes::runtime_context::session_root_handle() else {
732        return "(no session)".into();
733    };
734    let mut hits: Vec<&MetricInstance> = Vec::new();
735    let instances = walk_live_metrics(&root);
736    for inst in &instances {
737        if sel.matches(&inst.family, &inst.labels) {
738            hits.push(inst);
739        }
740    }
741
742    let header = format!(
743        "{}{}",
744        sel.family.as_deref().unwrap_or("*"),
745        if sel.label_eq.is_empty() {
746            String::new()
747        } else {
748            let inner = sel
749                .label_eq
750                .iter()
751                .map(|(k, v)| format!("{k}={v}"))
752                .collect::<Vec<_>>()
753                .join(",");
754            format!("{{{inner}}}")
755        },
756    );
757    if hits.is_empty() {
758        return format!("{header}\n  (no matches)");
759    }
760
761    let mut out = String::new();
762    out.push_str(&header);
763    out.push('\n');
764    // Sort matches for stable output.
765    hits.sort_by(|a, b| {
766        a.family
767            .cmp(&b.family)
768            .then_with(|| a.labels.to_prometheus().cmp(&b.labels.to_prometheus()))
769    });
770    for inst in &hits {
771        let line = format_metric_line(inst);
772        out.push_str("  ");
773        out.push_str(&line);
774        out.push('\n');
775    }
776    out
777}
778
779/// Render one `MetricInstance` as a single line under its
780/// selector header. Latency/time metrics get ms-scaled
781/// percentiles; other histograms keep raw nanos. Counters and
782/// gauges show their current value.
783fn format_metric_line(inst: &MetricInstance) -> String {
784    let labels = inst.labels.to_prometheus();
785    let prefix = format!("{}{}", inst.family, labels);
786    match &inst.value {
787        MetricValue::Counter(c) => format!("{prefix} = {} (counter)", c.cumulative),
788        MetricValue::Gauge(g) => format!("{prefix} = {} (gauge)", g.value),
789        MetricValue::Histogram(h) => {
790            let ms_mode = is_latency_family(&inst.family);
791            let scale = |v: u64| {
792                if ms_mode {
793                    v as f64 / 1_000_000.0
794                } else {
795                    v as f64
796                }
797            };
798            let unit = if ms_mode { "ms" } else { "raw" };
799            let p50 = h.reservoir.value_at_quantile(0.50);
800            let p99 = h.reservoir.value_at_quantile(0.99);
801            let max = h.reservoir.max();
802            let mean = h.reservoir.mean();
803            let mean_scaled = if ms_mode { mean / 1_000_000.0 } else { mean };
804            format!(
805                "{prefix} count={} mean={:.3}{unit} p50={:.3}{unit} p99={:.3}{unit} max={:.3}{unit}",
806                h.count,
807                mean_scaled,
808                scale(p50),
809                scale(p99),
810                scale(max),
811            )
812        }
813        MetricValue::BucketedHistogram(h) => {
814            format!(
815                "{prefix} count={} buckets={} (histogram)",
816                h.count,
817                h.buckets.len()
818            )
819        }
820        MetricValue::Info(_) => format!("{prefix} = 1 (info)"),
821        MetricValue::StateSet(s) => {
822            let active: Vec<&str> = s
823                .states
824                .iter()
825                .filter(|(_, a)| *a)
826                .map(|(n, _)| n.as_str())
827                .collect();
828            format!(
829                "{prefix} states={} active=[{}]",
830                s.states.len(),
831                active.join(",")
832            )
833        }
834    }
835}
836
837/// Heuristic: family names containing `time` or `latency` are
838/// treated as nanosecond timers and rendered in ms. Anything else
839/// keeps raw units.
840fn is_latency_family(family: &str) -> bool {
841    let f = family.to_ascii_lowercase();
842    f.contains("time") || f.contains("latency")
843}
844
845/// Render an SRD-63 readout against the latest active phase
846/// (or, if none is running, the most recently completed
847/// phase). Default readout is `phase_status`. ANSI escapes
848/// are stripped — the inspector socket is plain text.
849///
850/// Inspector is a read-only out-of-band surface; this
851/// command is the canonical way for tooling / scripts to
852/// scrape the same status the TUI shows, without parsing
853/// terminal output.
854fn render_readout(state: &RunState, tail: &str) -> String {
855    use nmbrs_runtime::readouts as ro;
856    use ro::ReadoutContext;
857
858    let name = if tail.is_empty() {
859        "phase_status"
860    } else {
861        tail.trim()
862    };
863    let Some(handle) = ro::Registry::lookup(name) else {
864        let known = ro::Registry::all_names().join(", ");
865        return format!("ERR unknown readout '{name}' — known: {known}\n");
866    };
867
868    // Pick a context: prefer the first active phase; else
869    // the most recently completed phase.
870    let active = state.first_active().cloned();
871    let phase = state
872        .phases
873        .iter()
874        .rev()
875        .find(|p| {
876            p.kind == crate::state::EntryKind::Phase
877                && (matches!(p.status, crate::state::PhaseStatus::Running)
878                    || active.is_some()
879                    || matches!(p.status, crate::state::PhaseStatus::Completed))
880        })
881        .cloned();
882    let Some(phase) = phase else {
883        return format!("(no phase to render `{name}` against)\n");
884    };
885
886    let ctx_box: Box<dyn ReadoutContext> = if let Some(a) = active {
887        Box::new(crate::readout_panel::PhaseRowContext::live(&phase, &a, 0))
888    } else {
889        Box::new(crate::readout_panel::PhaseRowContext::terminal(&phase))
890    };
891
892    // Fire the readout directly (no binder — the inspector
893    // wants the raw render, not the user's TUI-side focus
894    // overrides).
895    let mut sink_buf = String::new();
896    {
897        let mut buf = ro::buf::StringBuf::new(&mut sink_buf);
898        handle.render(
899            &*ctx_box,
900            ro::Lod::Labeled,
901            ro::ContentMode::Value,
902            &ro::ReadoutOptions::new(),
903            &mut buf,
904        );
905    }
906    let plain = ro::snapshot::strip_ansi(&sink_buf);
907    if plain.is_empty() {
908        format!("(readout `{name}` produced no output for current phase state)\n")
909    } else if plain.ends_with('\n') {
910        plain
911    } else {
912        format!("{plain}\n")
913    }
914}
915
916// Silence unused-import linting from the always-held Arc when
917// the file is read in isolation.
918#[allow(dead_code)]
919fn _arc_kept_alive(_: Arc<RunState>) {}
920
921// =========================================================================
922// Tests
923// =========================================================================
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    #[test]
930    fn metric_selector_parse_simple_family_only() {
931        let s = MetricSelector::parse("cycles").unwrap();
932        assert_eq!(s.family.as_deref(), Some("cycles"));
933        assert!(s.label_eq.is_empty());
934    }
935
936    #[test]
937    fn metric_selector_parse_with_labels() {
938        let s = MetricSelector::parse("cycles_servicetime{phase=pvs_query,table=fknn}").unwrap();
939        assert_eq!(s.family.as_deref(), Some("cycles_servicetime"));
940        assert_eq!(s.label_eq.len(), 2);
941        assert_eq!(
942            s.label_eq[0],
943            ("phase".to_string(), "pvs_query".to_string())
944        );
945        assert_eq!(s.label_eq[1], ("table".to_string(), "fknn".to_string()));
946    }
947
948    #[test]
949    fn metric_selector_parse_wildcard_family() {
950        let s = MetricSelector::parse("*{phase=load}").unwrap();
951        assert!(s.family.is_none());
952        assert_eq!(s.label_eq.len(), 1);
953    }
954
955    #[test]
956    fn metric_selector_parse_rejects_empty() {
957        assert!(MetricSelector::parse("").is_err());
958        assert!(MetricSelector::parse("{}").is_err());
959        assert!(MetricSelector::parse("foo{bad}").is_err());
960        assert!(MetricSelector::parse("foo{=v}").is_err());
961        assert!(MetricSelector::parse("foo{k=}").is_err());
962    }
963
964    #[test]
965    fn metric_selector_match_family_and_labels() {
966        let s = MetricSelector::parse("cycles{phase=load}").unwrap();
967        let mut l = Labels::empty();
968        l = l.with("phase", "load").with("k", "10");
969        assert!(s.matches("cycles", &l));
970        assert!(!s.matches("ops", &l));
971        let other = Labels::of("phase", "verify");
972        assert!(!s.matches("cycles", &other));
973    }
974
975    #[test]
976    fn metric_selector_wildcard_matches_any_family() {
977        let s = MetricSelector::parse("*{phase=load}").unwrap();
978        let l = Labels::of("phase", "load");
979        assert!(s.matches("anything", &l));
980        assert!(s.matches("cycles", &l));
981    }
982
983    #[test]
984    fn is_latency_family_heuristic() {
985        assert!(is_latency_family("cycles_servicetime"));
986        assert!(is_latency_family("op_latency"));
987        assert!(is_latency_family("response_time"));
988        assert!(!is_latency_family("cycles"));
989        assert!(!is_latency_family("errors"));
990    }
991
992    /// Push 8d: the `readout` command rejects an unknown
993    /// readout name with an ERR + the list of registered
994    /// names.
995    #[test]
996    fn readout_unknown_name_returns_err_with_known_list() {
997        let state = RunState::new("test.yaml", "fake", "stdout");
998        let out = render_readout(&state, "not_a_real_readout");
999        assert!(
1000            out.starts_with("ERR unknown readout"),
1001            "unexpected output: {out}"
1002        );
1003        assert!(
1004            out.contains("phase_status"),
1005            "should list known names: {out}"
1006        );
1007    }
1008
1009    /// With no phase to render against, the command returns
1010    /// a placeholder line instead of empty output. Avoids
1011    /// the inspector returning a blank reply that scripts
1012    /// can't distinguish from a transport error.
1013    #[test]
1014    fn readout_with_no_phase_returns_placeholder() {
1015        let state = RunState::new("test.yaml", "fake", "stdout");
1016        let out = render_readout(&state, "phase_outcome");
1017        assert!(out.contains("no phase"), "expected placeholder, got: {out}");
1018    }
1019}