use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use arc_swap::ArcSwap;
use nmbrs_metrics::summaries::binomial_summary::BinomialSummary;
use nmbrs_metrics::summaries::ewma::Ewma;
use nmbrs_metrics::summaries::peak_tracker::PeakTracker;
use nmbrs_runtime::observer::PhaseProgressUpdate;
use nmbrs_runtime::scene_tree::{SceneNodeId, SceneTree};
use crate::state::{ActivePhase, LogEntry, LogSeverity, PhaseSummary, RunState};
pub(crate) struct LogLine {
pub seq: u64,
pub entry: LogEntry,
pub margin_body: String,
pub detail_gutter: Option<nmbrs_runtime::wrappers::gutter::GutterSpec>,
}
pub(crate) struct ScrollbackReceiver {
cell: Arc<Mutex<Option<mpsc::Receiver<LogLine>>>>,
rx: Option<mpsc::Receiver<LogLine>>,
}
impl ScrollbackReceiver {
pub(crate) fn try_next(&self) -> Option<LogLine> {
self.rx.as_ref().and_then(|rx| rx.try_recv().ok())
}
}
impl Drop for ScrollbackReceiver {
fn drop(&mut self) {
if let Some(rx) = self.rx.take() {
*self.cell.lock().unwrap_or_else(|e| e.into_inner()) = Some(rx);
}
}
}
#[derive(Debug)]
pub enum RunStateCmd {
OpenTranscript(std::path::PathBuf),
Sysmon(nmbrs_runtime::sysmon::SysmonSample),
InstallTree(SceneTree),
PhaseStarting {
exec_id: u64,
scene_node_id: SceneNodeId,
name: String,
labels: String,
op_templates: usize,
total_cycles: u64,
concurrency: usize,
},
PhaseCompleted {
exec_id: u64,
scene_node_id: SceneNodeId,
name: String,
labels: String,
duration_secs: f64,
},
PhaseFailed {
exec_id: u64,
scene_node_id: SceneNodeId,
name: String,
labels: String,
error: String,
},
OpStarting {
parent: SceneNodeId,
op_name: String,
},
OpMeasure {
parent: nmbrs_runtime::scene_tree::SceneNodeId,
op_name: String,
text: String,
},
OpCompleted {
parent: SceneNodeId,
op_name: String,
duration_secs: f64,
},
OpFailed {
parent: SceneNodeId,
op_name: String,
error: String,
},
PhaseProgress(PhaseProgressUpdate),
AttachPhaseRender(nmbrs_runtime::observer::PhaseRenderHandle),
RunFinished,
Log {
severity: LogSeverity,
tag: crate::state::EventTag,
message: String,
},
LatencyFrame {
min: u64,
p50: u64,
p90: u64,
p99: u64,
p999: u64,
max: u64,
},
SparklineSamples {
ops: Option<f64>,
rows: Option<f64>,
rows_label: Option<String>,
},
SetMeta {
profiler: Option<String>,
limit: Option<String>,
},
FrameAck(mpsc::Sender<()>),
Barrier(mpsc::Sender<()>),
}
#[derive(Clone, Default)]
pub struct FrameSync {
pub force_redraw: Arc<AtomicBool>,
pub pending_acks: Arc<Mutex<Vec<mpsc::Sender<()>>>>,
}
impl FrameSync {
pub fn signal_post_draw(&self) {
self.force_redraw.store(false, Ordering::Release);
let mut q = self.pending_acks.lock().unwrap_or_else(|e| e.into_inner());
for tx in q.drain(..) {
let _ = tx.send(());
}
}
}
#[derive(Clone)]
pub struct RunStateHandle {
snapshot: Arc<ArcSwap<RunState>>,
inbox: mpsc::Sender<RunStateCmd>,
frame_sync: FrameSync,
log_rx: Arc<Mutex<Option<mpsc::Receiver<LogLine>>>>,
log_stream_active: Arc<AtomicBool>,
}
impl RunStateHandle {
pub fn load(&self) -> Arc<RunState> {
self.snapshot.load_full()
}
pub fn send(&self, cmd: RunStateCmd) {
let _ = self.inbox.send(cmd);
}
pub fn flush_frame(&self, timeout: Duration) -> bool {
let (tx, rx) = mpsc::channel::<()>();
if self.inbox.send(RunStateCmd::FrameAck(tx)).is_err() {
return false;
}
rx.recv_timeout(timeout).is_ok()
}
pub fn drain_barrier(&self, timeout: Duration) -> bool {
let (tx, rx) = mpsc::channel::<()>();
if self.inbox.send(RunStateCmd::Barrier(tx)).is_err() {
return false;
}
rx.recv_timeout(timeout).is_ok()
}
pub fn frame_sync(&self) -> FrameSync {
self.frame_sync.clone()
}
pub(crate) fn take_log_stream(&self) -> ScrollbackReceiver {
self.log_stream_active.store(true, Ordering::Release);
let rx = self.log_rx.lock().unwrap_or_else(|e| e.into_inner()).take();
ScrollbackReceiver {
cell: self.log_rx.clone(),
rx,
}
}
}
#[derive(Default)]
pub(crate) struct Transcript {
file: Option<std::io::BufWriter<std::fs::File>>,
pending: Vec<String>,
}
impl Transcript {
fn format(line: &LogLine) -> String {
format!("{:>27} │ {}", line.margin_body, line.entry.message)
}
fn record(&mut self, line: &LogLine) {
let text = Self::format(line);
match &mut self.file {
Some(f) => {
use std::io::Write;
let _ = writeln!(f, "{text}");
let _ = f.flush();
}
None => self.pending.push(text),
}
}
fn open(&mut self, path: &std::path::Path) {
let Ok(f) = std::fs::File::create(path) else {
return;
};
let mut w = std::io::BufWriter::new(f);
use std::io::Write;
for line in self.pending.drain(..) {
let _ = writeln!(w, "{line}");
}
let _ = w.flush();
self.file = Some(w);
}
}
pub fn spawn_run_state_actor(initial: RunState) -> (RunStateHandle, JoinHandle<()>) {
let snapshot = Arc::new(ArcSwap::new(Arc::new(initial.clone())));
let (tx, rx) = mpsc::channel::<RunStateCmd>();
let (log_tx, log_rx) = mpsc::channel::<LogLine>();
let log_rx = Arc::new(Mutex::new(Some(log_rx)));
let log_stream_active = Arc::new(AtomicBool::new(false));
let log_stream_active_for_thread = log_stream_active.clone();
let snapshot_for_thread = snapshot.clone();
let frame_sync = FrameSync::default();
let frame_sync_for_thread = frame_sync.clone();
let handle = std::thread::Builder::new()
.name("run-state-actor".into())
.spawn(move || {
let mut state = initial;
let mut transcript = Transcript::default();
while let Ok(first) = rx.recv() {
handle_cmd(
&mut state,
&frame_sync_for_thread,
&log_tx,
&log_stream_active_for_thread,
&mut transcript,
first,
);
while let Ok(more) = rx.try_recv() {
handle_cmd(
&mut state,
&frame_sync_for_thread,
&log_tx,
&log_stream_active_for_thread,
&mut transcript,
more,
);
}
snapshot_for_thread.store(Arc::new(state.clone()));
}
snapshot_for_thread.store(Arc::new(state));
frame_sync_for_thread.signal_post_draw();
})
.expect("spawn run-state-actor thread");
(
RunStateHandle {
snapshot,
inbox: tx,
frame_sync,
log_rx,
log_stream_active,
},
handle,
)
}
fn handle_cmd(
state: &mut RunState,
frame_sync: &FrameSync,
log_tx: &mpsc::Sender<LogLine>,
log_stream_active: &AtomicBool,
transcript: &mut Transcript,
cmd: RunStateCmd,
) {
match cmd {
RunStateCmd::OpenTranscript(path) => {
transcript.open(&path);
}
RunStateCmd::Barrier(tx) => {
let _ = tx.send(());
}
RunStateCmd::FrameAck(tx) => {
frame_sync
.pending_acks
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(tx);
frame_sync.force_redraw.store(true, Ordering::Release);
}
RunStateCmd::Log {
severity,
tag,
message,
} => {
let entry = LogEntry {
severity,
message,
tag,
at: std::time::SystemTime::now(),
};
{
let stream_entry = entry.clone();
let mut margin_body: Option<String> = None;
let detail_gutter = if stream_entry.tag.attached
== Some(nmbrs_runtime::lifecycle::EventType::PhaseEnd)
&& stream_entry.tag.category == crate::state::EventCategory::Outcome
{
let plain = crate::status_fold::strip_ansi(&stream_entry.message);
let subject = plain
.split('[')
.nth(1)
.map(|rest| rest.split(']').next().unwrap_or("").to_string())
.and_then(|name| {
state
.active_phases
.values()
.find(|a| a.name == name.as_str())
});
if let Some((s, n)) =
subject.and_then(|a| a.render.as_ref()).and_then(|h| h.seq)
{
let sess = state.elapsed_secs();
let leaf = subject.map(|a| (sess - a.session_started).max(0.0));
margin_body = Some(crate::widgets::margin_body(
n,
&format!("[{s}/{n}]"),
leaf,
Some(sess),
));
}
subject
.and_then(|a| a.render.as_ref())
.and_then(|h| h.gutter.load_full())
.map(|arc| (*arc).clone())
} else {
None
};
let seq = state.push_log_entry(entry);
let margin_body = margin_body.unwrap_or_else(|| state.margin_body_stamp());
let line = LogLine {
seq,
entry: stream_entry,
margin_body,
detail_gutter,
};
transcript.record(&line);
if log_stream_active.load(Ordering::Acquire) {
let _ = log_tx.send(line);
}
}
}
RunStateCmd::PhaseCompleted {
exec_id,
scene_node_id,
name,
labels,
duration_secs,
} => {
if log_stream_active.load(Ordering::Acquire)
&& nmbrs_runtime::observer::completed_phase_display()
== nmbrs_runtime::observer::CompletedPhaseDisplay::Full
{
let leaves = state.final_op_leaves(&name, &labels);
for (text, duration_cell) in leaves {
let entry = LogEntry {
severity: crate::state::LogSeverity::Info,
message: text,
tag: nmbrs_runtime::observer::EventTag::at(
nmbrs_runtime::lifecycle::EventType::PhaseEnd,
nmbrs_runtime::observer::EventCategory::Evaluation,
),
at: std::time::SystemTime::now(),
};
let stream_entry = entry.clone();
let seq = state.push_log_entry(entry);
let margin_body = state.margin_body_stamp();
let line = LogLine {
seq,
entry: stream_entry,
margin_body,
detail_gutter: Some(nmbrs_runtime::wrappers::gutter::GutterSpec::Text(
duration_cell,
)),
};
transcript.record(&line);
let _ = log_tx.send(line);
}
}
apply(
state,
RunStateCmd::PhaseCompleted {
exec_id,
scene_node_id,
name,
labels,
duration_secs,
},
);
}
other => apply(state, other),
}
}
fn apply(state: &mut RunState, cmd: RunStateCmd) {
match cmd {
RunStateCmd::Barrier(_) => {}
RunStateCmd::OpenTranscript(_) => {}
RunStateCmd::Sysmon(sample) => {
state.sysmon = Some(sample);
}
RunStateCmd::InstallTree(tree) => {
state.install_tree(tree);
}
RunStateCmd::PhaseStarting {
exec_id,
scene_node_id,
name,
labels,
op_templates,
total_cycles: _,
concurrency,
} => {
state.set_phase_running(scene_node_id, &name, &labels, op_templates);
let key = crate::state::ActivePhaseId::new(exec_id, name.clone(), labels.clone());
let throughput_summary = Arc::new(BinomialSummary::new(60));
let rate_ewma = Arc::new(Ewma::new(Duration::from_secs(1)));
let latency_peak_5s = Arc::new(PeakTracker::max(Duration::from_secs(5)));
let latency_peak_10s = Arc::new(PeakTracker::max(Duration::from_secs(10)));
let session_started = state.elapsed_secs();
state.active_phases.insert(
key,
ActivePhase {
name,
labels,
cursor_name: "?".into(),
cursor_extent: 0,
daemon: false,
rows_consumed: 0,
rows_total: 0,
fibers: concurrency,
started_at: Instant::now(),
session_started,
ops_started: 0,
ops_finished: 0,
ops_ok: 0,
skips: 0,
errors: 0,
retries: 0,
ops_per_sec: 0.0,
adapter_counters: Vec::new(),
rows_per_batch: 0.0,
relevancy: Vec::new(),
throughput_summary,
rate_ewma,
latency_peak_5s,
latency_peak_10s,
render: None,
},
);
state.ops_history.clear();
state.rows_history.clear();
state.rows_sparkline_label = None;
}
RunStateCmd::PhaseCompleted {
exec_id,
scene_node_id,
name,
labels,
duration_secs,
} => {
let key = crate::state::ActivePhaseId::new(exec_id, name.clone(), labels.clone());
let min_ns = state.min_nanos;
let p50_ns = state.p50_nanos;
let p99_ns = state.p99_nanos;
let max_ns = state.max_nanos;
let summary = state
.active_phases
.get(&key)
.map(|a| PhaseSummary {
ops_finished: a.ops_finished,
ops_ok: a.ops_ok,
skips: a.skips,
ops_started: a.ops_started,
errors: a.errors,
retries: a.retries,
fibers: a.fibers,
ops_per_sec: a.ops_per_sec,
min_nanos: min_ns,
p50_nanos: p50_ns,
p99_nanos: p99_ns,
max_nanos: max_ns,
cursor_name: a.cursor_name.clone(),
cursor_extent: a.cursor_extent,
adapter_counters: a.adapter_counters.clone(),
rows_per_batch: a.rows_per_batch,
cursors: std::iter::once((a.cursor_name.clone(), a.ops_finished))
.chain(a.adapter_counters.iter().map(|(n, t, _)| (n.clone(), *t)))
.collect(),
relevancy: a.relevancy.clone(),
throughput_samples: a.throughput_summary.snapshot(),
})
.unwrap_or_default();
state.set_phase_completed(scene_node_id, &name, &labels, duration_secs, summary);
state.active_phases.remove(&key);
}
RunStateCmd::PhaseFailed {
exec_id,
scene_node_id,
name,
labels,
error,
} => {
state.set_phase_failed(scene_node_id, &name, &labels, &error);
state
.active_phases
.remove(&crate::state::ActivePhaseId::new(exec_id, name, labels));
}
RunStateCmd::OpStarting { parent, op_name } => {
state.op_starting(parent, &op_name);
}
RunStateCmd::OpMeasure {
parent,
op_name,
text,
} => {
state.op_measure(parent, &op_name, &text);
}
RunStateCmd::OpCompleted {
parent,
op_name,
duration_secs,
} => {
state.op_completed(parent, &op_name, duration_secs);
}
RunStateCmd::OpFailed {
parent,
op_name,
error,
} => {
state.op_failed(parent, &op_name, &error);
}
RunStateCmd::PhaseProgress(update) => {
if let Some(active) =
state.active_phase_mut(update.exec_id, &update.name, &update.labels)
{
active.cursor_name = update.cursor_name.clone();
active.cursor_extent = update.cursor_extent;
active.daemon = update.daemon;
active.rows_consumed = update.rows_consumed;
active.rows_total = update.rows_total;
active.fibers = update.fibers;
active.ops_started = update.ops_started;
active.ops_finished = update.ops_finished;
active.ops_ok = update.ops_ok;
active.skips = update.skips;
active.errors = update.errors;
active.retries = update.retries;
active.ops_per_sec = update.ops_per_sec;
active.adapter_counters = update
.adapter_counters
.iter()
.map(|(n, t, r)| (n.clone(), *t, *r))
.collect();
active.rows_per_batch = update.rows_per_batch;
active.relevancy = update
.relevancy
.iter()
.map(|r| {
(
r.name.clone(),
r.window_mean,
r.total_mean,
r.total_count,
r.window_len,
)
})
.collect();
active.throughput_summary.record(update.ops_per_sec);
active.rate_ewma.record_now(update.ops_per_sec);
}
}
RunStateCmd::AttachPhaseRender(handle) => {
let key = crate::state::ActivePhaseId::new(
handle.exec_id,
handle.name.as_str(),
handle.labels.as_str(),
);
if let Some(active) = state.active_phases.get_mut(&key) {
active.render = Some(handle);
}
}
RunStateCmd::RunFinished => {
state.finished = true;
}
RunStateCmd::Log { .. } => {
unreachable!("Log is handled in handle_cmd before apply")
}
RunStateCmd::LatencyFrame {
min,
p50,
p90,
p99,
p999,
max,
} => {
state.min_nanos = min;
state.p50_nanos = p50;
state.p90_nanos = p90;
state.p99_nanos = p99;
state.p999_nanos = p999;
state.max_nanos = max;
const HISTORY_CAP: usize = 300; state.min_history.push(min);
state.p50_history.push(p50);
state.p90_history.push(p90);
state.p99_history.push(p99);
state.p999_history.push(p999);
state.max_history.push(max);
let trim = |h: &mut Vec<u64>| {
if h.len() > HISTORY_CAP {
h.remove(0);
}
};
trim(&mut state.min_history);
trim(&mut state.p50_history);
trim(&mut state.p90_history);
trim(&mut state.p99_history);
trim(&mut state.p999_history);
trim(&mut state.max_history);
let now = Instant::now();
for active in state.active_phases.values() {
active.latency_peak_5s.record(max, now);
active.latency_peak_10s.record(max, now);
}
}
RunStateCmd::SparklineSamples {
ops,
rows,
rows_label,
} => {
if let Some(o) = ops {
state.push_ops_sample(o);
}
if let Some(r) = rows {
state.push_rows_sample(r);
}
state.rows_sparkline_label = rows_label;
}
RunStateCmd::SetMeta { profiler, limit } => {
if let Some(p) = profiler {
state.profiler = p;
}
if let Some(l) = limit {
state.limit = l;
}
}
RunStateCmd::FrameAck(_) => {
unreachable!("FrameAck is handled in handle_cmd before apply")
}
}
}
#[cfg(test)]
mod scrollback_stream_tests {
use super::*;
use crate::state::{LogSeverity, RunState};
#[test]
fn stream_delivers_all_lines_past_ring_capacity() {
let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
let rx = handle.take_log_stream();
const N: u64 = 500;
for i in 0..N {
handle.send(RunStateCmd::Log {
severity: LogSeverity::Info,
tag: crate::state::EventTag::default(),
message: format!("line-{i}"),
});
}
let mut got: Vec<(u64, String)> = Vec::new();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while (got.len() as u64) < N && std::time::Instant::now() < deadline {
match rx.try_next() {
Some(line) => got.push((line.seq, line.entry.message)),
None => std::thread::sleep(std::time::Duration::from_millis(2)),
}
}
assert_eq!(
got.len() as u64,
N,
"every log line must be delivered — none dropped despite \
{N} lines arriving before any drain (ring cap is 200)"
);
for (i, (seq, msg)) in got.iter().enumerate() {
assert_eq!(*seq, i as u64 + 1, "seq monotonic + contiguous");
assert_eq!(msg, &format!("line-{i}"), "delivered in order");
}
drop(rx);
drop(handle);
let _ = join.join();
}
#[test]
fn stream_not_fed_until_a_sink_claims_it() {
let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
for i in 0..300u64 {
handle.send(RunStateCmd::Log {
severity: LogSeverity::Info,
tag: crate::state::EventTag::default(),
message: format!("unfed-{i}"),
});
}
std::thread::sleep(std::time::Duration::from_millis(60));
let rx = handle.take_log_stream();
std::thread::sleep(std::time::Duration::from_millis(20));
assert!(
rx.try_next().is_none(),
"an unclaimed stream must not buffer a backlog — no leak when \
no LogOnlySink is draining"
);
handle.send(RunStateCmd::Log {
severity: LogSeverity::Info,
tag: crate::state::EventTag::default(),
message: "after-claim".into(),
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut got = None;
while got.is_none() && std::time::Instant::now() < deadline {
match rx.try_next() {
Some(line) => got = Some(line.entry.message),
None => std::thread::sleep(std::time::Duration::from_millis(2)),
}
}
assert_eq!(
got.as_deref(),
Some("after-claim"),
"lines sent after the claim must flow through the stream"
);
drop(rx);
drop(handle);
let _ = join.join();
}
#[test]
fn stream_receiver_survives_sink_handoff() {
let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
{
let _rx = handle.take_log_stream();
}
for i in 0..3u64 {
handle.send(RunStateCmd::Log {
severity: LogSeverity::Info,
tag: crate::state::EventTag::default(),
message: format!("swap-{i}"),
});
}
let rx = handle.take_log_stream();
let mut got = Vec::new();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while got.len() < 3 && std::time::Instant::now() < deadline {
match rx.try_next() {
Some(line) => got.push(line.entry.message),
None => std::thread::sleep(std::time::Duration::from_millis(2)),
}
}
assert_eq!(
got,
vec!["swap-0", "swap-1", "swap-2"],
"the stream receiver must survive the sink handoff and \
flush the backlog buffered while no sink was draining"
);
drop(rx);
drop(handle);
let _ = join.join();
}
}
#[cfg(test)]
mod transcript_tests {
use super::Transcript;
#[test]
fn buffers_until_opened_then_flushes_in_order() {
let dir = std::env::temp_dir().join(format!(
"nmbrs-transcript-{}-{}",
std::process::id(),
line!()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("transcript.log");
let mut t = Transcript::default();
for msg in ["first", "second"] {
t.record(&super::LogLine {
seq: 0,
entry: crate::state::LogEntry {
severity: crate::state::LogSeverity::Info,
message: msg.into(),
tag: crate::state::EventTag::default(),
at: std::time::SystemTime::now(),
},
margin_body: "m".into(),
detail_gutter: None,
});
}
assert!(!path.exists(), "nothing is written before open");
t.open(&path);
t.record(&super::LogLine {
seq: 2,
entry: crate::state::LogEntry {
severity: crate::state::LogSeverity::Info,
message: "third".into(),
tag: crate::state::EventTag::default(),
at: std::time::SystemTime::now(),
},
margin_body: "m".into(),
detail_gutter: None,
});
let body = std::fs::read_to_string(&path).unwrap();
let msgs: Vec<&str> = body
.lines()
.map(|l| l.rsplit('│').next().unwrap().trim())
.collect();
assert_eq!(
msgs,
vec!["first", "second", "third"],
"buffered lines flush ahead of live ones, in order:\n{body}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn each_line_carries_its_margin_and_divider() {
let rendered = Transcript::format(&super::LogLine {
seq: 0,
entry: crate::state::LogEntry {
severity: crate::state::LogSeverity::Info,
message: "phase done".into(),
tag: crate::state::EventTag::default(),
at: std::time::SystemTime::now(),
},
margin_body: "◷ 12.1s [1/4]".into(),
detail_gutter: None,
});
assert!(rendered.contains("◷ 12.1s [1/4]"), "{rendered}");
assert!(
rendered.contains('│'),
"divider separates gutter from message: {rendered}"
);
assert!(rendered.trim_end().ends_with("phase done"), "{rendered}");
}
}