use std::collections::HashMap;
use serde_json::{json, Value};
pub const MAX_RECORDS: usize = 8192;
pub const MAX_PATHS: usize = 4096;
pub fn delivers(scope: &str, rec: &Value) -> bool {
let kind = rec.get("kind").and_then(Value::as_str).unwrap_or("");
if kind == "meta" {
return true;
}
let Some(path) = rec.get("path").and_then(Value::as_str) else {
return false;
};
if path == scope {
return true;
}
let Some(rest) = path.strip_prefix(scope) else {
return false;
};
let Some(rest) = rest.strip_prefix('/') else {
return false;
};
if kind == "node" {
!rest.contains('/')
} else {
true
}
}
fn parent_of(path: &str) -> Option<&str> {
path.rsplit_once('/').map(|(p, _)| p)
}
#[derive(Debug, Default, Clone)]
struct NodeLatest {
window: Option<Value>,
epoch: Option<Value>,
}
impl NodeLatest {
fn store(&mut self, rec: Value) {
if rec.get("epoch_complete").and_then(Value::as_bool) == Some(true) {
self.epoch = Some(rec);
} else {
self.window = Some(rec);
}
}
fn merged(&self) -> Option<Value> {
match (&self.window, &self.epoch) {
(None, None) => None,
(Some(v), None) | (None, Some(v)) => Some(v.clone()),
(Some(w), Some(e)) => {
let ts = |v: &Value| v.get("ts").and_then(Value::as_u64).unwrap_or(0);
let (older, newer) = if ts(w) <= ts(e) { (w, e) } else { (e, w) };
let mut out = older.clone();
overlay(&mut out, newer);
if let Some(obj) = out.as_object_mut() {
obj.remove("epoch_complete");
}
Some(out)
}
}
}
}
fn overlay(base: &mut Value, newer: &Value) {
let (Some(base_obj), Some(new_obj)) = (base.as_object_mut(), newer.as_object()) else {
*base = newer.clone();
return;
};
for (k, v) in new_obj {
match (base_obj.get_mut(k), v.as_object()) {
(Some(slot), Some(_)) if slot.is_object() => overlay(slot, v),
_ => {
base_obj.insert(k.clone(), v.clone());
}
}
}
}
#[derive(Debug, Default)]
pub struct RecordStore {
ring: std::collections::VecDeque<Value>,
latest: HashMap<String, NodeLatest>,
meta: Option<Value>,
path_cap_hit: bool,
}
impl RecordStore {
pub fn new() -> Self {
Self::default()
}
pub fn insert_all(&mut self, records: &[Value]) {
for r in records {
self.insert(r.clone());
}
}
pub fn insert(&mut self, rec: Value) {
let kind = rec.get("kind").and_then(Value::as_str).unwrap_or("");
if kind == "meta" {
self.meta = Some(rec);
return;
}
if kind == "node" {
if let Some(path) = rec.get("path").and_then(Value::as_str) {
if let Some(slot) = self.latest.get_mut(path) {
slot.store(rec.clone());
} else if self.latest.len() < MAX_PATHS {
self.latest.entry(path.to_string()).or_default().store(rec.clone());
} else {
self.path_cap_hit = true;
}
}
}
if self.ring.len() >= MAX_RECORDS {
self.ring.pop_front();
}
self.ring.push_back(rec);
}
pub fn meta(&self) -> Option<&Value> {
self.meta.as_ref()
}
pub fn take_path_cap_hit(&mut self) -> bool {
std::mem::take(&mut self.path_cap_hit)
}
pub fn node(&self, path: &str) -> Option<Value> {
self.latest.get(path).and_then(NodeLatest::merged)
}
pub fn children(&self, path: &str) -> Vec<Value> {
let mut kids: Vec<(&str, Value)> = self
.latest
.iter()
.filter(|(p, _)| parent_of(p) == Some(path))
.filter_map(|(p, v)| v.merged().map(|m| (p.as_str(), m)))
.collect();
kids.sort_unstable_by_key(|(p, _)| *p);
kids.into_iter().map(|(_, v)| v).collect()
}
pub fn snapshot(&self, path: &str) -> Value {
json!({
"path": path,
"node": self.node(path).unwrap_or(Value::Null),
"children": self.children(path),
})
}
pub fn history(&self, path: &str, n: usize) -> Vec<&Value> {
let mut out: Vec<&Value> = self
.ring
.iter()
.rev()
.filter(|r| delivers(path, r))
.take(n)
.collect();
out.reverse();
out
}
pub fn all(&self) -> impl Iterator<Item = &Value> {
self.ring.iter()
}
pub fn paths(&self) -> Vec<&str> {
let mut v: Vec<&str> = self.latest.keys().map(String::as_str).collect();
v.sort_unstable();
v
}
}
#[cfg(test)]
mod tests {
use super::*;
fn node(path: &str, tick: u64) -> Value {
json!({ "v": 1, "kind": "node", "path": path, "tick": tick,
"metrics": { "loss": 0.5 }, "work": 10.0 })
}
fn event(path: &str, class: &str) -> Value {
json!({ "v": 1, "kind": "event", "path": path, "class": class,
"sev": "critical", "detail": "x", "count": 1 })
}
#[test]
fn node_records_reach_the_level_and_its_direct_children_only() {
assert!(delivers("root", &node("root", 1)));
assert!(delivers("root", &node("root/exa", 1)));
assert!(!delivers("root", &node("root/exa/rank0", 1)));
assert!(delivers("root/exa", &node("root/exa/rank0", 1)));
assert!(!delivers("root/exa", &node("root", 1)));
}
#[test]
fn alerts_reach_a_root_viewer_from_any_depth() {
assert!(delivers("root", &event("root/exa/rank0", "rank_lost")));
assert!(delivers("root", &event("root", "control_drop")));
assert!(delivers("root/exa", &event("root/exa/rank0", "rank_lost")));
assert!(!delivers("root/exa", &event("root/pascal/rank1", "rank_lost")));
}
#[test]
fn a_string_prefix_is_not_a_path_prefix() {
assert!(!delivers("root/rank10", &node("root/rank1", 1)));
assert!(!delivers("root/exa", &node("root/exabyte/rank0", 1)));
assert!(delivers("root/exa", &node("root/exa/rank0", 1)));
}
#[test]
fn meta_reaches_every_subscriber_and_a_pathless_record_reaches_none() {
let meta = json!({ "v": 1, "kind": "meta", "reductions": {} });
assert!(delivers("root", &meta));
assert!(delivers("root/exa/rank0", &meta));
assert!(!delivers("root", &json!({ "v": 1, "kind": "node" })));
}
#[test]
fn an_unknown_kind_is_delivered_rather_than_dropped() {
let odd = json!({ "v": 1, "kind": "future", "path": "root/exa/rank0" });
assert!(delivers("root", &odd));
}
#[test]
fn snapshot_is_the_level_plus_direct_children() {
let mut s = RecordStore::new();
s.insert_all(&[
node("root", 1),
node("root/exa", 1),
node("root/exa/rank0", 1),
node("root/pascal", 1),
]);
let snap = s.snapshot("root");
assert_eq!(snap["node"]["path"], "root");
let kids: Vec<&str> = snap["children"]
.as_array()
.unwrap()
.iter()
.map(|c| c["path"].as_str().unwrap())
.collect();
assert_eq!(kids, vec!["root/exa", "root/pascal"]);
}
#[test]
fn snapshot_of_an_unreported_path_is_empty_not_an_error() {
let s = RecordStore::new();
let snap = s.snapshot("root/exa");
assert_eq!(snap["node"], Value::Null);
assert!(snap["children"].as_array().unwrap().is_empty());
}
#[test]
fn latest_node_wins_per_path() {
let mut s = RecordStore::new();
s.insert(node("root", 1));
s.insert(node("root", 7));
assert_eq!(s.node("root").unwrap()["tick"], 7);
assert_eq!(s.history("root", 10).len(), 2);
}
#[test]
fn history_matches_what_the_stream_would_deliver() {
let mut s = RecordStore::new();
s.insert_all(&[
node("root", 1),
node("root/exa", 1),
node("root/exa/rank0", 1),
event("root/exa/rank0", "rank_lost"),
]);
let h: Vec<&str> = s
.history("root", 100)
.iter()
.map(|r| r["path"].as_str().unwrap())
.collect();
assert_eq!(h, vec!["root", "root/exa", "root/exa/rank0"]);
assert_eq!(s.history("root", 100)[2]["kind"], "event");
}
#[test]
fn history_returns_the_newest_n_in_arrival_order() {
let mut s = RecordStore::new();
for t in 1..=10 {
s.insert(node("root", t));
}
let h = s.history("root", 3);
let ticks: Vec<u64> = h.iter().map(|r| r["tick"].as_u64().unwrap()).collect();
assert_eq!(ticks, vec![8, 9, 10]);
}
#[test]
fn the_ring_is_bounded_and_drops_oldest() {
let mut s = RecordStore::new();
for t in 0..(MAX_RECORDS as u64 + 50) {
s.insert(node("root", t));
}
assert_eq!(s.ring.len(), MAX_RECORDS);
let h = s.history("root", 1);
assert_eq!(h[0]["tick"], MAX_RECORDS as u64 + 49);
assert_eq!(s.node("root").unwrap()["tick"], MAX_RECORDS as u64 + 49);
}
#[test]
fn the_path_index_is_capped_and_says_so() {
let mut s = RecordStore::new();
for i in 0..MAX_PATHS {
s.insert(node(&format!("root/h{i}"), 1));
}
assert!(!s.take_path_cap_hit(), "no breach yet");
s.insert(node("root/one-too-many", 1));
assert!(s.take_path_cap_hit(), "breach reported");
assert!(!s.take_path_cap_hit(), "and reported only once");
assert_eq!(s.node("root/one-too-many"), None);
s.insert(node("root/h0", 9));
assert_eq!(s.node("root/h0").unwrap()["tick"], 9);
}
#[test]
fn meta_is_retained_for_replay_and_absent_by_default() {
let mut s = RecordStore::new();
assert!(s.meta().is_none());
s.insert(json!({ "v": 1, "kind": "meta", "reductions": { "acc": "mean" } }));
assert_eq!(s.meta().unwrap()["reductions"]["acc"], "mean");
assert!(s.history("root", 10).is_empty());
}
fn epoch_node(path: &str, ts: u64) -> Value {
json!({ "v": 1, "kind": "node", "path": path, "ts": ts, "epoch": 3,
"epoch_complete": true, "work": 1.0, "label": "RTX 5060 Ti",
"metrics": { "loss": 0.4, "accuracy": 0.9 },
"res": { "gpu_util": 84.0, "vram_alloc": 5000.0 } })
}
fn window_node(path: &str, ts: u64, tick: u64) -> Value {
json!({ "v": 1, "kind": "node", "path": path, "ts": ts, "tick": tick,
"work": 10.0, "metrics": { "loss": 0.31, "throughput": 21.0 } })
}
#[test]
fn a_window_report_does_not_blank_the_epoch_fields() {
let mut s = RecordStore::new();
s.insert(epoch_node("root/rank0", 100));
s.insert(window_node("root/rank0", 200, 7));
let n = s.node("root/rank0").unwrap();
assert_eq!(n["metrics"]["loss"], 0.31);
assert_eq!(n["metrics"]["throughput"], 21.0);
assert_eq!(n["tick"], 7);
assert_eq!(n["work"], 10.0);
assert_eq!(n["metrics"]["accuracy"], 0.9);
assert_eq!(n["res"]["gpu_util"], 84.0);
assert_eq!(n["label"], "RTX 5060 Ti");
assert!(n.get("epoch_complete").is_none(), "{n}");
assert!(
s.history("root/rank0", 10)
.iter()
.any(|r| r.get("epoch_complete").and_then(Value::as_bool) == Some(true)),
"the flag stays on the history row",
);
}
#[test]
fn merge_is_by_timestamp_not_arrival() {
let mut s = RecordStore::new();
s.insert(window_node("root/rank0", 200, 7));
s.insert(epoch_node("root/rank0", 100)); let n = s.node("root/rank0").unwrap();
assert_eq!(n["metrics"]["loss"], 0.31, "newer window loss still wins");
assert_eq!(n["metrics"]["accuracy"], 0.9);
assert_eq!(n["res"]["gpu_util"], 84.0);
}
#[test]
fn a_field_absent_from_both_stays_absent() {
let mut s = RecordStore::new();
s.insert(window_node("root/rank0", 100, 1));
s.insert(epoch_node("root/rank0", 200));
let n = s.node("root/rank0").unwrap();
assert!(n["metrics"].get("data_starve").is_none());
assert!(n["res"].get("vram_total").is_none());
}
#[test]
fn history_keeps_both_cadences_as_separate_rows() {
let mut s = RecordStore::new();
s.insert(window_node("root", 100, 1));
s.insert(window_node("root", 200, 2));
s.insert(epoch_node("root", 300));
s.insert(window_node("root", 400, 3));
let h = s.history("root", 10);
assert_eq!(h.len(), 4);
let marks: Vec<bool> = h
.iter()
.map(|r| r.get("epoch_complete").and_then(Value::as_bool) == Some(true))
.collect();
assert_eq!(marks, vec![false, false, true, false], "epoch row is marked");
}
#[test]
fn paths_is_the_sorted_navigation_index() {
let mut s = RecordStore::new();
s.insert_all(&[node("root/pascal", 1), node("root", 1), node("root/exa", 1)]);
assert_eq!(s.paths(), vec!["root", "root/exa", "root/pascal"]);
}
}