1use super::app_tool::{ago, gb, mb, s};
11use super::str_arg;
12use super::*;
13
14const DAY_MS: i64 = 86_400_000;
15const EXPORT_BYTES: usize = 200_000;
17const MAX_HOURS: u64 = 336;
18
19pub(super) async fn record(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
20 let view = str_arg(arguments, "view").unwrap_or_else(|| "summary".to_string());
21 let now_ms = agentmux_common::time::now_ms();
22 match view.as_str() {
23 "summary" => {
24 let from = (now_ms - 8 * DAY_MS).max(0).to_string();
25 let rolls = get(cx, &[("kind", "rollup"), ("limit", "200"), ("from_ms", &from)]).await?;
26 let raw = get(cx, &[("kind", "raw"), ("limit", "1")]).await?;
27 let events = get(cx, &[("kind", "events"), ("limit", "500"), ("from_ms", &from)]).await?;
28 let empty = Vec::new();
29 Ok(describe_summary(
30 &rolls["inventory"],
31 raw["lines"].get(0),
32 rolls["lines"].as_array().unwrap_or(&empty),
33 events["lines"].as_array().unwrap_or(&empty),
34 events["matched"].as_u64().map_or(0, |m| m as usize),
35 now_ms,
36 ))
37 }
38 "series" | "export" => {
39 let kind = str_arg(arguments, "kind").unwrap_or_else(|| "rollup".to_string());
40 if !matches!(kind.as_str(), "rollup" | "raw" | "events") {
41 anyhow::bail!("App record: kind is \"rollup\", \"raw\" or \"events\", not {kind:?}");
42 }
43 let raw = kind == "raw";
44 let hours = arguments.get("hours").and_then(Value::as_u64).unwrap_or(24).clamp(1, MAX_HOURS);
45 let limit = match kind.as_str() {
46 "raw" => (hours * 12).min(600),
47 "events" => 500,
48 _ => hours,
49 }
50 .to_string();
51 let from = (now_ms - hours as i64 * 3_600_000).max(0).to_string();
52 let day = str_arg(arguments, "day");
53 let mut query = vec![("kind", kind.as_str()), ("limit", limit.as_str())];
54 match day.as_deref() {
55 Some(day) => query.push(("day", day)),
56 None => query.push(("from_ms", from.as_str())),
57 }
58 let body = get(cx, &query).await?;
59 let lines = body["lines"].as_array().map(Vec::as_slice).unwrap_or_default();
60 let matched = body["matched"].as_u64().map_or(lines.len(), |m| m as usize);
61 Ok(match (view.as_str(), kind.as_str()) {
62 ("export", _) => describe_export(lines, matched),
63 (_, "events") => describe_events(lines, matched, now_ms),
64 _ => describe_series(raw, lines, matched, now_ms),
65 })
66 }
67 other => anyhow::bail!("App record: view is \"summary\", \"series\" or \"export\", not {other:?}"),
68 }
69}
70
71async fn get(cx: &ToolCtx<'_>, query: &[(&str, &str)]) -> Result<Value> {
72 let url = format!("{}/api/v1/app/record", cx.local_url.trim_end_matches('/'));
73 let resp = cx.client.get(&url).header(AUTH_KEY_HEADER, cx.auth_key).query(query).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
74 let status = resp.status();
75 let body: Value = resp.json().await.unwrap_or(Value::Null);
76 if !status.is_success() {
77 anyhow::bail!("App record: {}", body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("srv answered {status}: {body}")));
78 }
79 Ok(body)
80}
81
82fn stat(v: &Value) -> Option<[u64; 4]> {
84 let a = v.as_array()?;
85 Some([a.first()?.as_u64()?, a.get(1)?.as_u64()?, a.get(2)?.as_u64()?, a.get(3)?.as_u64()?])
86}
87
88fn keyed(r: &Value, list: &str, key: &str) -> Option<[u64; 4]> {
90 r[list].as_array()?.iter().find(|p| p[0].as_str() == Some(key)).and_then(|p| stat(&p[1]))
91}
92
93fn parts_of(r: &Value) -> String {
94 let part = |k: &str| keyed(r, "parts", k).map_or(0, |s| s[1]);
95 format!(
96 "core {}, panes {}, agents {}, not placed {}",
97 mb(part("core")),
98 mb(part("panes")),
99 mb(part("agents")),
100 mb(part("not_placed"))
101 )
102}
103
104fn span(ms: u64) -> String {
105 ago(0, &json!(-(ms as i64)))
106}
107
108fn stored(inv: &Value) -> String {
110 let (days, months) = (inv["raw_days"].as_u64().unwrap_or(0), inv["rollup_months"].as_u64().unwrap_or(0));
111 if days == 0 && months == 0 {
112 return "The record on this machine is empty: it starts with the first line five minutes after AgentMux starts.".to_string();
113 }
114 format!(
115 "The record on this machine (it never leaves the computer): five-minute lines for {days} day(s) since {} ({}), hourly rollups for {months} month(s) since {} ({}).",
116 inv["raw_first_day"].as_str().unwrap_or("-"),
117 mb(inv["raw_bytes"].as_u64().unwrap_or(0)),
118 inv["rollup_first_month"].as_str().unwrap_or("-"),
119 mb(inv["rollup_bytes"].as_u64().unwrap_or(0))
120 )
121}
122
123fn latest(line: &Value, now_ms: i64) -> String {
125 let am = &line["am"];
126 let part = |k: &str| am["parts"].as_array().and_then(|p| p.iter().find(|x| x["k"].as_str() == Some(k))).and_then(|x| x["mem"].as_u64()).unwrap_or(0);
127 let mut out = format!(
128 "Newest line, {} ago (srv {}, up {}): AgentMux {} in {} processes (core {}, panes {}, agents {}, not placed {}).",
129 ago(now_ms, &line["t"]),
130 s(line, "v"),
131 span(line["up_s"].as_u64().unwrap_or(0) * 1000),
132 mb(am["total"].as_u64().unwrap_or(0)),
133 am["procs"],
134 mb(part("core")),
135 mb(part("panes")),
136 mb(part("agents")),
137 mb(part("not_placed"))
138 );
139 let m = &line["machine"];
140 if let Some(mem) = m["mem"].as_u64() {
141 out.push_str(&format!(" The machine: {} private", gb(mem)));
142 if let Some(total) = m["mem_total"].as_u64() {
143 out.push_str(&format!(" of {}", gb(total)));
144 }
145 if let Some(free) = m["disk"][0].as_u64() {
146 out.push_str(&format!(", record drive {} free", gb(free)));
147 }
148 out.push('.');
149 }
150 for page in line["pages"].as_array().into_iter().flatten() {
151 out.push('\n');
152 out.push_str(&page_text(page));
153 }
154 out
155}
156
157fn page_text(p: &Value) -> String {
159 let heap = match (p["heap"].as_u64(), p["heap_limit"].as_u64()) {
160 (Some(used), Some(limit)) => format!("JS heap {used} of {limit} MB, "),
161 (Some(used), None) => format!("JS heap {used} MB, "),
162 _ => String::new(),
163 };
164 let finds = p["searches"].as_u64().unwrap_or(0);
165 format!(
166 "Window {} (page up {} min): {heap}{} elements, {} agent pane(s) with {} rows (largest {}){}{}.",
167 s(p, "w"),
168 p["up_min"],
169 p["dom"],
170 p["panes"],
171 p["rows"],
172 p["max_rows"],
173 if finds > 0 { format!(", {finds} find bar(s) open") } else { String::new() },
174 if p["blocked"].as_u64().unwrap_or(0) > 0 { format!(", {} thing(s) holding a recycle back", p["blocked"]) } else { String::new() }
175 )
176}
177
178fn nearest(rolls: &[Value], target_ms: u64) -> Option<&Value> {
180 rolls.iter().min_by_key(|r| r["h"].as_u64().unwrap_or(0).abs_diff(target_ms))
181}
182
183fn trend(rolls: &[Value], now_ms: i64) -> String {
185 let Some(last) = rolls.last() else {
186 return "No hour has been rolled up yet, so there is no trend to read (the first rollup is written when the first full hour ends).".to_string();
187 };
188 let last_h = last["h"].as_u64().unwrap_or(0);
189 let mut out = String::from("AgentMux's total by the hour (median, with min to max):");
190 for back in [0u64, 1, 6, 24, 168] {
191 let target = last_h.saturating_sub(back * 3_600_000);
192 let Some(r) = nearest(rolls, target).filter(|r| r["h"].as_u64().unwrap_or(0).abs_diff(target) < 3_600_000) else { continue };
193 if let Some([min, med, _, max]) = stat(&r["am"]) {
194 let when = if back == 0 { format!("the last hour ({} ago)", ago(now_ms, &r["h"])) } else { format!("{} before it", span(back * 3_600_000)) };
195 out.push_str(&format!("\n- {when}: {} ({} to {})", mb(med), mb(min), mb(max)));
196 }
197 }
198 let Some(then) = nearest(rolls, last_h.saturating_sub(DAY_MS as u64)).filter(|r| r["h"].as_u64().unwrap_or(0) + 3_600_000 <= last_h) else {
199 return out;
200 };
201 let then_h = then["h"].as_u64().unwrap_or(0);
202 let restarts = restarts_since(rolls, then_h);
203 if let (Some(a), Some(b)) = (stat(&then["am"]), stat(&last["am"])) {
204 let delta = b[1] as i64 - a[1] as i64;
205 out.push_str(&format!(
206 "\nOver {}: {}{} ({:+.1}%).{}",
207 span(last_h - then_h),
208 if delta >= 0 { "+" } else { "-" },
209 mb(delta.unsigned_abs()),
210 if a[1] == 0 { 0.0 } else { delta as f64 * 100.0 / a[1] as f64 },
211 if restarts > 0 { format!(" srv restarted {restarts} time(s) in that time, so a drop is a restart, not a fix.") } else { String::new() }
212 ));
213 }
214 out.push_str(&grown(then, last));
215 out
216}
217
218fn last_time(r: &Value) -> (u64, bool) {
220 match r["last_t"].as_u64().filter(|t| *t > 0) {
221 Some(t) => (t, true),
222 None => (r["h"].as_u64().unwrap_or(0), false),
223 }
224}
225
226fn restarts_since(rolls: &[Value], then_h: u64) -> u64 {
231 let inside: u64 = rolls.iter().filter(|r| r["h"].as_u64().unwrap_or(0) > then_h).map(|r| r["restarts"].as_u64().unwrap_or(0)).sum();
232 let between = rolls
233 .windows(2)
234 .filter(|w| w[0]["h"].as_u64().unwrap_or(0) >= then_h)
235 .filter(|w| w[1]["restarts"].as_u64().unwrap_or(0) == 0)
237 .filter(|w| {
238 let ((later, exact_later), (earlier, exact_earlier)) = (last_time(&w[1]), last_time(&w[0]));
239 let gap_s = later.saturating_sub(earlier) / 1000;
240 let room = if exact_later && exact_earlier { 120 } else { 900 };
241 w[1]["up_s"].as_u64().unwrap_or(0) + room < w[0]["up_s"].as_u64().unwrap_or(0) + gap_s
242 })
243 .count() as u64;
244 inside + between
245}
246
247fn grown(then: &Value, now: &Value) -> String {
251 let mut moves: Vec<(String, i64)> = Vec::new();
252 let mut entered: Vec<String> = Vec::new();
253 for list in ["parts", "rows"] {
254 for p in now[list].as_array().into_iter().flatten() {
255 let (Some(key), Some(b)) = (p[0].as_str(), stat(&p[1])) else { continue };
256 match keyed(then, list, key) {
257 Some(a) => moves.push((key.to_string(), b[1] as i64 - a[1] as i64)),
258 None if list == "rows" => entered.push(key.to_string()),
259 None => moves.push((key.to_string(), b[1] as i64)),
260 }
261 }
262 }
263 moves.retain(|(_, d)| *d > 0);
264 moves.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
265 let mut out = if moves.is_empty() {
266 "\nNo part or row that was in the largest six both times grew.".to_string()
267 } else {
268 let list: Vec<String> = moves.iter().take(4).map(|(k, d)| format!("{k} +{}", mb(*d as u64))).collect();
269 format!("\nGrew most (median, same two hours): {}.", list.join(", "))
270 };
271 if !entered.is_empty() {
272 out.push_str(&format!(" Newly among the largest six, with no earlier size known: {}.", entered.join(", ")));
273 }
274 out
275}
276
277fn stalls(events: &[Value], matched: usize, now_ms: i64) -> String {
279 let mut out = String::from("Stalls in that time:");
280 if matched > events.len() {
281 out.push_str(&format!(" (the newest {} of {matched}: the counts and the longest below cover only those; view \"series\" with kind \"events\" and fewer hours shows the rest)", events.len()));
282 }
283 for (kind, what) in [("ui_stall", "the window host's UI thread did not run"), ("srv_stall", "srv's runtime stopped running tasks")] {
284 let mine: Vec<&Value> = events.iter().filter(|e| s(e, "kind") == kind).collect();
285 let Some(longest) = mine.iter().map(|e| e["ms"].as_u64().unwrap_or(0)).max() else {
286 out.push_str(&format!("
287- none where {what}."));
288 continue;
289 };
290 let last = mine.iter().filter_map(|e| e["t"].as_u64()).max().unwrap_or(0);
291 out.push_str(&format!("
292- {} where {what}; the longest {}, the last {} ago.", mine.len(), span(longest), ago(now_ms, &json!(last))));
293 }
294 out
295}
296
297fn is_flag(e: &Value) -> bool {
298 e["kind"].as_str() == Some("flag")
299}
300
301fn flag_words(e: &Value) -> String {
303 let key = e["key"].as_str().unwrap_or("?");
304 let n = |field: &str| e[field].as_u64().unwrap_or(0);
305 let stalled = if key == "ui_stall" { "the window host's UI thread" } else { "srv's runtime" };
306 match e["rule"].as_str().unwrap_or("") {
307 "stalls" => format!("{stalled} stalled {} times for 5 s or more in one hour, the longest {}", n("n"), span(n("worst_ms"))),
308 "long_stall" => format!("{stalled} stalled for {}", span(n("worst_ms"))),
309 "growth" => {
310 let amount = |v: u64| match e["unit"].as_str() {
311 Some("bytes") => mb(v),
312 Some("mb") => format!("{v} MB"),
313 _ => format!("{v} elements"),
314 };
315 let content = e["content_pct"].as_i64().map_or(String::new(), |p| format!("; its rows changed by {p}% in that day"));
316 format!("{key} grew two days running: about +{} a day at {} (the day before +{}){content}", amount(n("rise")), amount(n("level")), amount(n("rise_before")))
317 }
318 other => format!("{other} {key}"),
319 }
320}
321
322fn flags(events: &[Value], now_ms: i64) -> String {
324 let mine: Vec<&Value> = events.iter().filter(|e| is_flag(e)).collect();
325 if mine.is_empty() {
326 return "Flags in that time: none (the rules that read the record found nothing).".to_string();
327 }
328 let mut out = format!("Flags in that time: {} (found by the rules that read the record; view \"series\" with kind \"events\" lists them all). Newest:", mine.len());
329 for e in mine.iter().rev().take(3) {
330 out.push_str(&format!("\n- {} ago: {}", ago(now_ms, &e["t"]), flag_words(e)));
331 }
332 out
333}
334
335pub(super) fn describe_events(events: &[Value], matched: usize, now_ms: i64) -> String {
337 if events.is_empty() {
338 return "The record has no stall in that window.".to_string();
339 }
340 let mut out = String::from(if events.iter().any(is_flag) { "Stalls and flags, oldest first:" } else { "Stalls, oldest first:" });
341 for e in events {
342 let what = if is_flag(e) {
343 format!("flag: {}", flag_words(e))
344 } else if s(e, "kind") == "ui_stall" {
345 let host = e["host_mb"].as_u64().map_or(String::new(), |mb| format!(" (host {mb} MB private)"));
346 format!("the window host's UI thread did not run for {}{host}", span(e["ms"].as_u64().unwrap_or(0)))
347 } else {
348 format!(
349 "srv's runtime stopped for {} (cause {}, worst {} late, {} merged)",
350 span(e["ms"].as_u64().unwrap_or(0)),
351 s(e, "cause"),
352 span(e["worst_ms"].as_u64().unwrap_or(0)),
353 e["n"]
354 )
355 };
356 out.push_str(&format!("
357- {} ago: {what}", ago(now_ms, &e["t"])));
358 }
359 if matched > events.len() {
360 out.push_str(&format!("
361This shows the newest {} of the {matched} in that window; ask for a shorter one to see the rest.", events.len()));
362 }
363 out
364}
365
366pub(super) fn describe_summary(inventory: &Value, newest: Option<&Value>, rolls: &[Value], events: &[Value], matched: usize, now_ms: i64) -> String {
368 let mut out = stored(inventory);
369 if let Some(line) = newest {
370 out.push('\n');
371 out.push_str(&latest(line, now_ms));
372 }
373 out.push('\n');
374 out.push_str(&trend(rolls, now_ms));
375 out.push('\n');
376 out.push_str(&stalls(events, matched, now_ms));
377 out.push('\n');
378 out.push_str(&flags(events, now_ms));
379 out.push_str("\nView \"series\" lists the hours or lines, \"export\" returns them as stored, to attach to a bug.");
380 out
381}
382
383pub(super) fn describe_series(raw: bool, lines: &[Value], matched: usize, now_ms: i64) -> String {
385 if lines.is_empty() {
386 return "The record has nothing in that window yet.".to_string();
387 }
388 let mut out = String::from(if raw { "Five-minute lines, oldest first:" } else { "Hourly rollups (median, with min to max), oldest first:" });
389 for l in lines {
390 if raw {
391 out.push_str(&format!(
392 "\n- {} ago: AgentMux {} in {} processes; machine {} private; srv up {}",
393 ago(now_ms, &l["t"]),
394 mb(l["am"]["total"].as_u64().unwrap_or(0)),
395 l["am"]["procs"],
396 mb(l["machine"]["mem"].as_u64().unwrap_or(0)),
397 span(l["up_s"].as_u64().unwrap_or(0) * 1000)
398 ));
399 } else if let Some([min, med, _, max]) = stat(&l["am"]) {
400 let restarts = l["restarts"].as_u64().unwrap_or(0);
401 out.push_str(&format!(
402 "\n- {} ago: AgentMux {} ({} to {}); {}; srv up {}, {} line(s){}",
403 ago(now_ms, &l["h"]),
404 mb(med),
405 mb(min),
406 mb(max),
407 parts_of(l),
408 span(l["up_s"].as_u64().unwrap_or(0) * 1000),
409 l["n"],
410 if restarts > 0 { format!(", restarted {restarts}x") } else { String::new() }
411 ));
412 }
413 }
414 if matched > lines.len() {
415 out.push_str(&format!("\nThis shows the newest {} of the {matched} lines in that window (one answer holds a limited number); ask for a shorter window (hours or day) to see the rest.", lines.len()));
416 }
417 out
418}
419
420pub(super) fn describe_export(lines: &[Value], matched: usize) -> String {
422 if lines.is_empty() {
423 return "The record has nothing in that window yet.".to_string();
424 }
425 let texts: Vec<String> = lines.iter().map(Value::to_string).collect();
426 let mut kept = 0usize;
427 let mut bytes = 0usize;
428 for t in texts.iter().rev() {
429 if bytes + t.len() + 1 > EXPORT_BYTES {
430 break;
431 }
432 bytes += t.len() + 1;
433 kept += 1;
434 }
435 let cut = texts.len() - kept;
436 let mut note = String::new();
437 if matched > texts.len() {
438 note.push_str(&format!("The window holds {matched} lines and one answer holds {}: the older {} are not here. ", texts.len(), matched - texts.len()));
439 }
440 if cut > 0 {
441 note.push_str(&format!("{cut} older line(s) left out to fit {} KB. ", EXPORT_BYTES / 1000));
442 }
443 if !note.is_empty() {
444 note.push_str("Ask for a shorter window (hours or day) to get them.\n");
445 }
446 format!("{note}{kept} line(s), one JSON object each (numbers and stable keys only):\n{}", texts[cut..].join("\n"))
447}
448
449#[cfg(test)]
450mod tests {
451 use super::*;
452
453 const H: u64 = 3_600_000;
454
455 fn roll(h: u64, total: u64, core: u64, restarts: u64) -> Value {
456 json!({
457 "h": h, "n": 12, "v": "0.60.31", "up_s": 7_200, "restarts": restarts,
458 "am": [total - 10, total, total + 5, total + 10],
459 "parts": [["core", [core, core, core, core]], ["panes", [1, 1, 1, 1]], ["agents", [2, 2, 2, 2]], ["not_placed", [0, 0, 0, 0]]],
460 "rows": [["agent:b1", [core, core, core, core]]]
461 })
462 }
463
464 #[test]
465 fn each_stall_is_listed_with_how_long_it_lasted_and_what_was_seen() {
466 let now = 1_000 * H;
467 let events = vec![
468 json!({ "t": now - 5 * H, "kind": "ui_stall", "ms": 55_000, "host_mb": 310 }),
469 json!({ "t": now - H, "kind": "srv_stall", "ms": 5_300, "worst_ms": 5_200, "n": 2, "cause": "machine" }),
470 ];
471 let text = describe_events(&events, 2, now as i64);
472 assert!(text.contains("5 h 0 min ago: the window host's UI thread did not run for 55 s (host 310 MB private)"), "{text}");
473 assert!(text.contains("60 min ago: srv's runtime stopped for 5 s (cause machine, worst 5 s late, 2 merged)"), "{text}");
474 assert!(describe_events(&[], 0, 0).contains("no stall"));
475 assert!(describe_events(&events, 40, now as i64).contains("newest 2 of the 40"));
476 }
477
478 #[test]
479 fn a_flag_is_said_in_words_among_the_events_and_counted_in_the_summary() {
480 let now = 1_000 * H;
481 let events = vec![
482 json!({ "t": now - 30 * H, "kind": "flag", "rule": "long_stall", "key": "srv_stall", "n": 1, "worst_ms": 42_000 }),
483 json!({ "t": now - 3 * H, "kind": "ui_stall", "ms": 7_000, "host_mb": 310 }),
484 json!({ "t": now - 2 * H, "kind": "flag", "rule": "stalls", "key": "ui_stall", "n": 5, "worst_ms": 9_000 }),
485 json!({ "t": now - H, "kind": "flag", "rule": "growth", "key": "page:main:heap", "unit": "mb", "level": 306, "rise": 72, "rise_before": 70, "content_pct": 0 }),
486 ];
487 let text = describe_events(&events, 4, now as i64);
488 assert!(text.starts_with("Stalls and flags, oldest first:"), "{text}");
489 assert!(text.contains("flag: srv's runtime stalled for 42 s"), "{text}");
490 assert!(text.contains("flag: the window host's UI thread stalled 5 times for 5 s or more in one hour, the longest 9 s"), "{text}");
491 assert!(text.contains("60 min ago: flag: page:main:heap grew two days running: about +72 MB a day at 306 MB (the day before +70 MB); its rows changed by 0% in that day"), "{text}");
492 assert!(stalls(&events, 4, now as i64).contains("- 1 where the window host's UI thread did not run"), "{}", stalls(&events, 4, now as i64));
494 let said = flags(&events, now as i64);
495 assert!(said.starts_with("Flags in that time: 3 "), "{said}");
496 assert!(said.find("page:main:heap").unwrap() < said.find("stalled 5 times").unwrap(), "{said}");
497 assert!(flags(&events[1..2], now as i64).contains("none"));
498 assert!(describe_events(&events[1..2], 1, now as i64).starts_with("Stalls, oldest first:"));
499 }
500
501 #[test]
502 fn the_newest_line_says_what_each_windows_page_holds() {
503 let newest = json!({ "t": 1_000, "v": "0.60.31", "up_s": 60, "am": { "total": 5, "procs": 1, "parts": [] },
504 "pages": [
505 { "w": "main", "heap": 310, "heap_limit": 4096, "dom": 18_200, "panes": 3, "rows": 4_100, "max_rows": 2_050, "searches": 1, "blocked": 2, "up_min": 90 },
506 { "w": "window-3", "dom": 900, "panes": 0, "rows": 0, "max_rows": 0, "searches": 0, "blocked": 0, "up_min": 5 }
507 ] });
508 let text = latest(&newest, 2_000);
509 assert!(text.contains("Window main (page up 90 min): JS heap 310 of 4096 MB, 18200 elements, 3 agent pane(s) with 4100 rows (largest 2050), 1 find bar(s) open, 2 thing(s) holding a recycle back."), "{text}");
510 assert!(text.contains("Window window-3 (page up 5 min): 900 elements, 0 agent pane(s) with 0 rows (largest 0)."), "{text}");
511 }
512
513 #[test]
514 fn an_empty_record_says_so_and_a_young_one_says_there_is_no_trend() {
515 let text = describe_summary(&json!({ "raw_days": 0, "rollup_months": 0 }), None, &[], &[], 0, 1_000);
516 assert!(text.contains("is empty") && text.contains("No hour has been rolled up yet"), "{text}");
517 }
518
519 #[test]
520 fn growth_over_a_day_is_named_with_the_rows_that_grew_and_a_restart_is_said() {
521 let now = 1_000 * H;
522 let mut rolls: Vec<Value> = (0..30).map(|i| roll(now - (31 - i) * H, 1_000_000_000 + i * 10_000_000, 400_000_000 + i * 8_000_000, 0)).collect();
523 for (i, r) in rolls.iter_mut().enumerate() {
525 r["up_s"] = json!(100_000 + i as u64 * 3_600);
526 }
527 rolls[10]["restarts"] = json!(1);
528 let inv = json!({ "raw_days": 3, "raw_bytes": 3_000_000, "raw_first_day": "2026-11-14", "rollup_months": 1, "rollup_bytes": 50_000, "rollup_first_month": "2026-11" });
529 let newest = json!({ "t": now - 120_000, "v": "0.60.31", "up_s": 90_000, "am": { "total": 1_300_000_000u64, "procs": 41, "parts": [{ "k": "core", "mem": 600_000_000u64, "n": 3 }] }, "machine": { "mem": 12_000_000_000u64, "mem_total": 32_000_000_000u64, "disk": [200_000_000_000u64, 500_000_000_000u64] } });
530 let events = vec![
531 json!({ "t": now - 3 * H, "kind": "ui_stall", "ms": 55_000, "host_mb": 310 }),
532 json!({ "t": now - H, "kind": "ui_stall", "ms": 8_000 }),
533 ];
534 let text = describe_summary(&inv, Some(&newest), &rolls, &events, events.len(), now as i64);
535 assert!(text.contains("- 2 where the window host's UI thread did not run; the longest 55 s, the last 60 min ago."), "{text}");
536 assert!(text.contains("- none where srv's runtime stopped running tasks."), "{text}");
537 assert!(text.contains("five-minute lines for 3 day(s) since 2026-11-14") && text.contains("hourly rollups for 1 month(s)"), "{text}");
538 assert!(text.contains("Newest line, 2 min ago (srv 0.60.31, up 25 h 0 min): AgentMux 1239.8 MB in 41 processes"), "{text}");
539 assert!(text.contains("Over 24 h 0 min: +228.9 MB (+22.9%)"), "{text}");
540 assert!(text.contains("srv restarted 1 time(s)"), "{text}");
541 assert!(text.contains("Grew most") && text.contains("core +183.1 MB") && text.contains("agent:b1 +183.1 MB"), "{text}");
542 }
543
544 #[test]
545 fn stall_totals_say_when_the_window_held_more_stalls_than_were_read() {
546 let events = vec![json!({ "t": 5_000, "kind": "ui_stall", "ms": 9_000 })];
547 let cut = describe_summary(&json!({ "raw_days": 0, "rollup_months": 0 }), None, &[], &events, 1_200, 10_000);
548 assert!(cut.contains("Stalls in that time: (the newest 1 of 1200"), "{cut}");
549 assert!(cut.contains("cover only those"), "{cut}");
550 let whole = describe_summary(&json!({ "raw_days": 0, "rollup_months": 0 }), None, &[], &events, 1, 10_000);
551 assert!(whole.contains("Stalls in that time:\n- 1 where"), "{whole}");
552 }
553
554 #[test]
555 fn a_row_new_to_the_top_six_has_an_unknown_earlier_size_not_a_growth_from_zero() {
556 let mut then = roll(0, 1_000_000_000, 400_000_000, 0);
557 let mut now = roll(24 * H, 1_000_000_000, 400_000_000, 0);
558 then["rows"] = json!([["agent:b1", [100, 100, 100, 100]]]);
559 now["rows"] = json!([["agent:b1", [150, 150, 150, 150]], ["np:node-exe", [9_000_000, 9_000_000, 9_000_000, 9_000_000]]]);
560 let text = grown(&then, &now);
561 assert!(text.contains("agent:b1 +50 bytes") || text.contains("agent:b1 +0.0 MB"), "{text}");
562 assert!(text.contains("no earlier size known: np:node-exe"), "{text}");
563 assert!(!text.contains("np:node-exe +"), "{text}");
564 }
565
566 #[test]
567 fn a_restart_between_two_hours_is_found_by_the_uptime_that_did_not_keep_up() {
568 let at = |h: u64, up_s: u64| {
570 let mut r = roll(h * H, 1_000_000_000, 400_000_000, 0);
571 r["up_s"] = json!(up_s);
572 r["last_t"] = json!(h * H + 55 * 60_000);
573 r
574 };
575 let steady = vec![at(0, 6_900), at(1, 10_500), at(2, 14_100)];
577 assert_eq!(restarts_since(&steady, 0), 0);
578 let restarted = vec![at(0, 6_900), at(1, 10_500), at(2, 3_000)];
580 assert_eq!(restarts_since(&restarted, 0), 1);
581 let mut inside = vec![at(0, 6_900), at(1, 10_500), at(2, 1_200)];
583 inside[2]["restarts"] = json!(1);
584 assert_eq!(restarts_since(&inside, 0), 1);
585 let mut two = vec![at(0, 6_900), at(1, 2_000), at(2, 5_600), at(3, 1_200)];
587 two[3]["restarts"] = json!(1);
588 assert_eq!(restarts_since(&two, 0), 2);
589 let mut sparse = vec![at(0, 6_900), at(1, 7_500)];
592 sparse[1]["last_t"] = json!(55 * 60_000 + 10 * 60_000);
593 assert_eq!(restarts_since(&sparse, 0), 0);
594 let old = |h: u64, up_s: u64| json!({ "h": h * H, "up_s": up_s, "restarts": 0 });
596 assert_eq!(restarts_since(&[old(0, 6_900), old(1, 10_500)], 0), 0);
597 assert_eq!(restarts_since(&[old(0, 6_900), old(1, 2_000)], 0), 1);
598 assert_eq!(restarts_since(&restarted, 2 * H), 0);
600 }
601
602 #[test]
603 fn a_series_lists_each_hour_with_its_parts_and_an_export_keeps_the_newest_lines_that_fit() {
604 let now = 100 * H;
605 let rolls = vec![roll(now - 2 * H, 1_000_000_000, 400_000_000, 0), roll(now - H, 1_010_000_000, 410_000_000, 2)];
606 let text = describe_series(false, &rolls, 2, now as i64);
607 assert!(!text.contains("of the 2 lines"), "{text}");
608 assert!(text.contains("2 h 0 min ago") && text.contains("core 381.5 MB") && text.contains("restarted 2x"), "{text}");
609 assert_eq!(describe_series(true, &[], 0, 0), "The record has nothing in that window yet.");
610 let cut = describe_series(false, &rolls, 400, now as i64);
612 assert!(cut.contains("newest 2 of the 400 lines in that window"), "{cut}");
613
614 let big: Vec<Value> = (0..400).map(|i| json!({ "h": i, "pad": "x".repeat(1_000) })).collect();
615 let text = describe_export(&big, 400);
616 assert!(text.contains("older line(s) left out to fit 200 KB"), "{}", &text[..120]);
617 assert!(!text.contains("The window holds"), "the route cut nothing");
618 let cut_by_route = describe_export(&big[..3], 900);
619 assert!(cut_by_route.starts_with("The window holds 900 lines and one answer holds 3: the older 897 are not here."), "{cut_by_route}");
620 assert!(text.len() < EXPORT_BYTES + 400, "{}", text.len());
621 assert!(text.contains("\"h\":399") && !text.contains("\"h\":0,"), "the newest lines are kept");
622 }
623}