1use std::collections::{HashMap, HashSet};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use crate::backend::net_counters::NetCounters;
14use sysinfo::{DiskRefreshKind, Disks, MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate};
15
16use crate::backend::blockcontroller::pidregistry;
17use crate::backend::blockcontroller::process_tree;
18#[cfg(target_os = "windows")]
19use crate::backend::own_instance;
20use crate::backend::rpc_types::TimeSeriesData;
21use crate::backend::wconfig::ConfigState;
22use crate::backend::mps::Broker;
23use crate::backend::sampler::{Scheduler, SourceId, SourceSpec};
24
25const BYTES_PER_GB: f64 = 1_073_741_824.0;
26const BYTES_PER_MB: f64 = 1_048_576.0;
27const PERSIST_COUNT: usize = 1024;
28pub const SAMPLE_WINDOW_KEY: &str = "sample:window_ms";
30const DEFAULT_INTERVAL_SECS: f64 = 1.0;
31const MIN_INTERVAL_SECS: f64 = 0.2;
32const MAX_INTERVAL_SECS: f64 = 2.0;
33const DISK_FULL_REFRESH: Duration = Duration::from_secs(30);
40
41const SCHEDULER_COALESCE_MS: u64 = 50;
43const PANE_JANITOR_MS: u64 = 30_000;
46const NEVER_STRETCHED: u64 = u64::MAX / 4;
48const HOLDER_TELEMETRY: &str = "telemetry";
49const HOLDER_JANITOR: &str = "pane-janitor";
50const HOLDER_BADGES: &str = "pane-badges";
51
52#[cfg(windows)]
91fn suspend_aware_now_ms() -> u64 {
92 unsafe { windows_sys::Win32::System::SystemInformation::GetTickCount64() }
94}
95
96#[cfg(not(windows))]
97fn suspend_aware_now_ms() -> u64 {
98 #[cfg(any(target_os = "linux", target_os = "android"))]
99 const CLOCK: libc::clockid_t = libc::CLOCK_BOOTTIME;
100 #[cfg(not(any(target_os = "linux", target_os = "android")))]
101 const CLOCK: libc::clockid_t = libc::CLOCK_MONOTONIC;
102
103 let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
104 if unsafe { libc::clock_gettime(CLOCK, &mut ts) } != 0 {
106 return 0;
110 }
111 (ts.tv_sec as u64) * 1_000 + (ts.tv_nsec as u64) / 1_000_000
112}
113
114static PROCESS_START_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
117
118pub fn mark_process_start() {
121 let _ = PROCESS_START_MS.set(suspend_aware_now_ms());
122}
123
124pub fn uptime_secs() -> u64 {
130 let start = *PROCESS_START_MS.get_or_init(suspend_aware_now_ms);
131 suspend_aware_now_ms().saturating_sub(start) / 1_000
132}
133
134#[cfg(target_os = "windows")]
136const ATTRIBUTION_INTERVAL: Duration = Duration::from_secs(30);
137#[cfg(target_os = "windows")]
141const ATTRIBUTION_URGENT_THRESHOLD_GB: f64 = 2.0;
142#[cfg(target_os = "windows")]
145const ATTRIBUTION_URGENT_COOLDOWN: Duration = Duration::from_secs(10);
146#[cfg(target_os = "windows")]
148const ATTRIBUTION_OTHER_TOP_N: usize = 5;
149#[cfg(target_os = "windows")]
160const ATTRIBUTION_MAX_PIDS_PER_BLOCK: usize = 4096;
161
162#[cfg(target_os = "windows")]
168struct ProcSample {
169 pid: u32,
170 name: String,
171 commit_mb: f64,
172 own: bool,
177}
178
179#[cfg(target_os = "windows")]
180struct AttributionResult {
181 agentmux_mb: f64,
182 panes_mb: f64,
183 other_mb: f64,
184 other_top: Vec<(String, f64)>,
186}
187
188#[cfg(target_os = "windows")]
198fn classify_commit_attribution(
199 samples: &[ProcSample],
200 pane_pids: &HashSet<u32>,
201 top_n: usize,
202) -> AttributionResult {
203 let mut agentmux_mb = 0.0;
204 let mut panes_mb = 0.0;
205 let mut other_by_name: HashMap<String, f64> = HashMap::new();
206 for s in samples {
207 if s.own && s.name.to_ascii_lowercase().starts_with("agentmux") {
208 agentmux_mb += s.commit_mb;
209 } else if pane_pids.contains(&s.pid) {
210 panes_mb += s.commit_mb;
211 } else {
212 *other_by_name.entry(s.name.clone()).or_insert(0.0) += s.commit_mb;
213 }
214 }
215 let mut other: Vec<(String, f64)> = other_by_name.into_iter().collect();
216 other.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
217 let other_mb: f64 = other.iter().map(|(_, mb)| mb).sum();
218 other.truncate(top_n);
219 AttributionResult {
220 agentmux_mb,
221 panes_mb,
222 other_mb,
223 other_top: other,
224 }
225}
226
227#[cfg(target_os = "windows")]
239const HANDLE_WARN_AGENTMUX: u32 = 20_000;
240#[cfg(target_os = "windows")]
241const HANDLE_WARN_EXTERNAL: u32 = 50_000;
242#[cfg(target_os = "windows")]
243const HANDLE_TOP_N: usize = 3;
244#[cfg(target_os = "windows")]
254const HANDLE_WARN_COOLDOWN: Duration = Duration::from_secs(600);
255
256#[cfg(target_os = "windows")]
258struct HandleSample {
259 pid: u32,
260 name: String,
261 handles: u32,
262}
263
264#[cfg(target_os = "windows")]
265struct HandleAnomaly {
266 pid: u32,
267 name: String,
268 handles: u32,
269 is_agentmux: bool,
273}
274
275#[cfg(target_os = "windows")]
280fn classify_handle_anomalies(samples: &[HandleSample]) -> Vec<HandleAnomaly> {
281 let mut anomalies: Vec<HandleAnomaly> = samples
282 .iter()
283 .filter_map(|s| {
284 let is_agentmux = s.name.to_ascii_lowercase().starts_with("agentmux");
285 let threshold = if is_agentmux { HANDLE_WARN_AGENTMUX } else { HANDLE_WARN_EXTERNAL };
286 (s.handles >= threshold).then(|| HandleAnomaly {
287 pid: s.pid,
288 name: s.name.clone(),
289 handles: s.handles,
290 is_agentmux,
291 })
292 })
293 .collect();
294 anomalies.sort_by(|a, b| b.handles.cmp(&a.handles));
295 anomalies
296}
297
298#[cfg(target_os = "windows")]
306fn filter_anomalies_for_warn(
307 anomalies: &[HandleAnomaly],
308 last_warned: &mut HashMap<u32, Instant>,
309 now: Instant,
310 cooldown: Duration,
311) -> Vec<usize> {
312 let current: HashSet<u32> = anomalies.iter().map(|a| a.pid).collect();
313 last_warned.retain(|pid, _| current.contains(pid));
314
315 let mut warn = Vec::new();
316 for (i, anomaly) in anomalies.iter().enumerate() {
317 let due = match last_warned.get(&anomaly.pid) {
318 Some(&at) => now.duration_since(at) >= cooldown,
319 None => true,
320 };
321 if due {
322 last_warned.insert(anomaly.pid, now);
323 warn.push(i);
324 }
325 }
326 warn
327}
328
329#[cfg(target_os = "windows")]
333static LAST_HANDLE_WARN: std::sync::OnceLock<std::sync::Mutex<HashMap<u32, Instant>>> =
334 std::sync::OnceLock::new();
335
336#[cfg(target_os = "windows")]
342pub(crate) fn process_handle_count(pid: u32) -> Option<u32> {
343 use windows_sys::Win32::Foundation::CloseHandle;
344 use windows_sys::Win32::System::Threading::{
345 GetProcessHandleCount, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
346 };
347 unsafe {
348 let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
349 if h.is_null() {
350 return None;
351 }
352 let mut count: u32 = 0;
353 let ok = GetProcessHandleCount(h, &mut count);
354 CloseHandle(h);
355 (ok != 0).then_some(count)
356 }
357}
358
359#[cfg(target_os = "windows")]
370fn log_memory_attribution(sys: &mut sysinfo::System, commit_used_gb: f64, commit_total_gb: f64) {
371 sys.refresh_processes_specifics(
378 ProcessesToUpdate::All,
379 true, ProcessRefreshKind::nothing().with_memory(),
381 );
382
383 let mut pane_pids: HashSet<u32> = HashSet::new();
384 for (block_id, pid) in pidregistry::get_all() {
385 let tree = process_tree::collect_descendants(
386 sys,
387 Pid::from(pid as usize),
388 ATTRIBUTION_MAX_PIDS_PER_BLOCK,
389 );
390 if tree.len() == ATTRIBUTION_MAX_PIDS_PER_BLOCK {
391 tracing::warn!(
392 block_id = %block_id,
393 cap = ATTRIBUTION_MAX_PIDS_PER_BLOCK,
394 "log_memory_attribution: block's descendant PID tree hit the cap — \
395 some processes may be misclassified into \"other\" instead of \"panes\""
396 );
397 }
398 pane_pids.extend(tree.into_iter().map(|pid| pid.as_u32()));
399 }
400
401 let nodes: Vec<own_instance::ProcNode> = sys
405 .processes()
406 .iter()
407 .map(|(pid, proc)| own_instance::ProcNode {
408 pid: pid.as_u32(),
409 parent: proc.parent().map(|p| p.as_u32()),
410 is_agentmux: proc.name().to_string_lossy().to_ascii_lowercase().starts_with("agentmux"),
411 started_at_ms: Some(proc.start_time().saturating_mul(1000)),
412 })
413 .collect();
414 let own_pids = own_instance::own_instance_pids(&nodes, std::process::id());
415 let samples: Vec<ProcSample> = sys
416 .processes()
417 .iter()
418 .map(|(pid, proc)| ProcSample {
419 pid: pid.as_u32(),
420 name: proc.name().to_string_lossy().into_owned(),
421 commit_mb: proc.virtual_memory() as f64 / BYTES_PER_MB,
422 own: own_pids.contains(&pid.as_u32()),
423 })
424 .collect();
425
426 let result = classify_commit_attribution(&samples, &pane_pids, ATTRIBUTION_OTHER_TOP_N);
427
428 let other_top_str = result
429 .other_top
430 .iter()
431 .map(|(name, mb)| format!("{}:{:.0}MB", name, mb))
432 .collect::<Vec<_>>()
433 .join(", ");
434
435 let attributed_gb = (result.agentmux_mb + result.panes_mb + result.other_mb) / 1024.0;
447 let unattributed_gb = (commit_used_gb - attributed_gb).max(0.0);
448
449 let handle_samples: Vec<HandleSample> = samples
453 .iter()
454 .filter_map(|s| {
455 process_handle_count(s.pid).map(|handles| HandleSample {
456 pid: s.pid,
457 name: s.name.clone(),
458 handles,
459 })
460 })
461 .collect();
462 let mut top_handles: Vec<&HandleSample> = handle_samples.iter().collect();
463 top_handles.sort_by(|a, b| b.handles.cmp(&a.handles));
464 let handles_top_str = top_handles
465 .iter()
466 .take(HANDLE_TOP_N)
467 .map(|s| format!("{}:{}:{}", s.name, s.pid, s.handles))
468 .collect::<Vec<_>>()
469 .join(", ");
470
471 let anomalies = classify_handle_anomalies(&handle_samples);
472 let warn_indices = {
473 let mut last = LAST_HANDLE_WARN
474 .get_or_init(|| std::sync::Mutex::new(HashMap::new()))
475 .lock()
476 .unwrap();
477 filter_anomalies_for_warn(&anomalies, &mut last, Instant::now(), HANDLE_WARN_COOLDOWN)
478 };
479 for i in warn_indices {
480 let anomaly = &anomalies[i];
481 if anomaly.is_agentmux {
482 tracing::warn!(
483 target: "mem_attribution",
484 pid = anomaly.pid,
485 name = %anomaly.name,
486 handles = anomaly.handles,
487 "possible handle leak in an AgentMux process — a healthy baseline is under ~1K; \
488 run `handle64 -s -p <pid>` for the type breakdown (a huge Section count is the \
489 known leak signature, docs/status/STATUS_SRV_SECTION_HANDLE_LEAK_2026_08_08.md)"
490 );
491 } else {
492 tracing::warn!(
493 target: "mem_attribution",
494 pid = anomaly.pid,
495 name = %anomaly.name,
496 handles = anomaly.handles,
497 "external process handle-count anomaly (Audiosrv-class OS leak?) — if commit is \
498 also climbing unattributed, restarting that process/service reclaims it \
499 (docs/status/STATUS_PF_COMMIT_GROWTH_INVESTIGATION_2026_07_24.md §16)"
500 );
501 }
502 }
503
504 let (tracker_blocks, tracker_pids) = crate::backend::process_tracker::registry::global()
513 .map(|r| r.stats())
514 .unwrap_or((0, 0));
515 let (reaper_candidates, reaper_first_seen, reaper_reaped_cumulative) =
516 crate::backend::sweep_stats::last_sweep_stats();
517
518 tracing::info!(
519 target: "mem_attribution",
520 commit_used_gb = format!("{:.2}", commit_used_gb),
521 commit_total_gb = format!("{:.2}", commit_total_gb),
522 agentmux_mb = format!("{:.0}", result.agentmux_mb),
523 panes_mb = format!("{:.0}", result.panes_mb),
524 other_mb = format!("{:.0}", result.other_mb),
525 other_top = %other_top_str,
526 unattributed_gb = format!("{:.2}", unattributed_gb),
527 handles_top = %handles_top_str,
528 process_count = samples.len(),
529 tracker_blocks = tracker_blocks,
530 tracker_pids = tracker_pids,
531 reaper_candidates = reaper_candidates,
532 reaper_first_seen = reaper_first_seen,
533 reaper_reaped_cumulative = reaper_reaped_cumulative,
534 "commit attribution"
535 );
536}
537
538fn get_cpu_data(sys: &sysinfo::System, values: &mut HashMap<String, f64>) {
540 let cpus = sys.cpus();
541 if cpus.is_empty() {
542 return;
543 }
544 let total: f64 = cpus.iter().map(|c| c.cpu_usage() as f64).sum::<f64>() / cpus.len() as f64;
546 values.insert("cpu".to_string(), total);
547 for (idx, cpu) in cpus.iter().enumerate() {
549 values.insert(format!("cpu:{}", idx), cpu.cpu_usage() as f64);
550 }
551}
552
553fn get_mem_data(sys: &sysinfo::System, values: &mut HashMap<String, f64>) {
555 let total = sys.total_memory() as f64 / BYTES_PER_GB;
556 let used = sys.used_memory() as f64 / BYTES_PER_GB;
557 let available = sys.available_memory() as f64 / BYTES_PER_GB;
558 let free = sys.free_memory() as f64 / BYTES_PER_GB;
559 values.insert("mem:total".to_string(), total);
560 values.insert("mem:used".to_string(), used);
561 values.insert("mem:available".to_string(), available);
562 values.insert("mem:free".to_string(), free);
563}
564
565fn get_commit_data(_values: &mut HashMap<String, f64>) {
569 #[cfg(target_os = "windows")]
570 {
571 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
572 let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
573 mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
574 if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 {
575 let total_gb = mem.ullTotalPageFile as f64 / BYTES_PER_GB;
576 let avail_gb = mem.ullAvailPageFile as f64 / BYTES_PER_GB;
577 _values.insert("mem:commit:used".to_string(), total_gb - avail_gb);
578 _values.insert("mem:commit:total".to_string(), total_gb);
579 }
580 }
581}
582
583pub fn available_commit_gb() -> Option<f64> {
589 #[cfg(target_os = "windows")]
590 {
591 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
592 let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
593 mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
594 if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 {
595 return Some(mem.ullAvailPageFile as f64 / BYTES_PER_GB);
596 }
597 }
598 None
599}
600
601fn get_pagefile_volume_data(_values: &mut HashMap<String, f64>) {
628 #[cfg(target_os = "windows")]
629 {
630 let (drive, system_managed) = agentmux_common::pagefile::pagefile_watch_target();
631 if let Some((free_gb, total_gb)) = agentmux_common::pagefile::drive_free_total_gb(drive) {
632 _values.insert("disk:watch:free_gb".to_string(), free_gb);
633 _values.insert("disk:watch:total_gb".to_string(), total_gb);
634 if total_gb > 0.0 {
635 _values.insert(
636 "disk:watch:free_pct".to_string(),
637 (free_gb / total_gb) * 100.0,
638 );
639 }
640 _values.insert(
641 "disk:pagefile_system_managed".to_string(),
642 if system_managed { 1.0 } else { 0.0 },
643 );
644 _values.insert(format!("disk:vol:{}:\\:watch", drive), 1.0);
651 let is_system_drive = std::env::var("SystemDrive")
659 .ok()
660 .and_then(|s| s.chars().next())
661 .map(|c| c.to_ascii_uppercase() == drive)
662 .unwrap_or(false);
663 _values.insert(
664 format!("disk:vol:{}:\\:is_system_drive", drive),
665 if is_system_drive { 1.0 } else { 0.0 },
666 );
667 }
668 }
669}
670
671#[cfg(all(test, target_os = "windows"))]
672mod handle_anomaly_tests {
673 use super::*;
674
675 fn hsample(pid: u32, name: &str, handles: u32) -> HandleSample {
676 HandleSample { pid, name: name.to_string(), handles }
677 }
678
679 #[test]
680 fn healthy_baselines_trip_nothing() {
681 let samples = vec![
682 hsample(1, "agentmux-srv.exe", 950),
683 hsample(2, "svchost.exe", 3_000),
684 hsample(3, "chrome.exe", 11_000),
685 ];
686 assert!(classify_handle_anomalies(&samples).is_empty());
687 }
688
689 #[test]
690 fn agentmux_process_trips_at_the_lower_threshold() {
691 let samples = vec![
695 hsample(1, "agentmux-srv-0.54.10-windows.x64.exe", HANDLE_WARN_AGENTMUX),
696 hsample(2, "chrome.exe", HANDLE_WARN_AGENTMUX + 5_000),
697 ];
698 let anomalies = classify_handle_anomalies(&samples);
699 assert_eq!(anomalies.len(), 1);
700 assert!(anomalies[0].is_agentmux);
701 assert_eq!(anomalies[0].pid, 1);
702 }
703
704 #[test]
705 fn external_process_trips_only_at_the_higher_threshold() {
706 let samples = vec![hsample(9, "svchost.exe", 85_000)];
708 let anomalies = classify_handle_anomalies(&samples);
709 assert_eq!(anomalies.len(), 1);
710 assert!(!anomalies[0].is_agentmux);
711 }
712
713 #[test]
714 fn anomalies_are_sorted_worst_first() {
715 let samples = vec![
716 hsample(1, "agentmux-srv.exe", 25_000),
717 hsample(2, "svchost.exe", 85_000),
718 ];
719 let anomalies = classify_handle_anomalies(&samples);
720 assert_eq!(anomalies[0].pid, 2);
721 assert_eq!(anomalies[1].pid, 1);
722 }
723
724 #[test]
725 fn own_process_handle_count_is_queryable_and_nonzero() {
726 let count = process_handle_count(std::process::id());
729 assert!(count.is_some_and(|c| c > 0), "got {count:?}");
730 }
731
732 #[test]
751 fn refresh_processes_specifics_does_not_leak_a_handle_per_call() {
752 let pid = std::process::id();
753 let mut sys = sysinfo::System::new();
754 let mut refresh = |n: u32| {
755 for _ in 0..n {
756 sys.refresh_processes_specifics(ProcessesToUpdate::All, false, ProcessRefreshKind::nothing());
757 }
758 };
759 refresh(5);
763 const CALLS: u32 = 100; const WINDOWS: usize = 20;
766 let mut growth = Vec::new();
767 for _ in 0..WINDOWS {
768 let before = process_handle_count(pid).expect("own handle count must be queryable");
769 refresh(CALLS);
770 let after = process_handle_count(pid).expect("own handle count must be queryable");
771 let grew_by = after.saturating_sub(before);
772 if grew_by < CALLS / 2 {
773 return;
774 }
775 growth.push(grew_by);
776 }
777 panic!("handle count grew by {growth:?} over {WINDOWS} windows of {CALLS} refresh_processes_specifics calls: a per-call handle leak (the CreateToolhelp32Snapshot bug fixed in sysinfo 0.35.0 leaked a handle per call)");
778 }
779
780 fn anomaly(pid: u32) -> HandleAnomaly {
781 HandleAnomaly { pid, name: format!("proc{pid}.exe"), handles: 99_999, is_agentmux: false }
782 }
783
784 #[test]
785 fn cooldown_warns_immediately_on_first_sight_then_suppresses() {
786 let mut last = HashMap::new();
787 let t0 = Instant::now();
788 let cooldown = Duration::from_secs(600);
789 let anomalies = vec![anomaly(1)];
790
791 assert_eq!(filter_anomalies_for_warn(&anomalies, &mut last, t0, cooldown), vec![0]);
792 let t1 = t0 + Duration::from_secs(30);
794 assert!(filter_anomalies_for_warn(&anomalies, &mut last, t1, cooldown).is_empty());
795 let t2 = t0 + cooldown;
797 assert_eq!(filter_anomalies_for_warn(&anomalies, &mut last, t2, cooldown), vec![0]);
798 }
799
800 #[test]
801 fn cooldown_is_per_pid_not_global() {
802 let mut last = HashMap::new();
803 let t0 = Instant::now();
804 let cooldown = Duration::from_secs(600);
805
806 assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t0, cooldown), vec![0]);
807 let t1 = t0 + Duration::from_secs(30);
810 let both = vec![anomaly(1), anomaly(2)];
811 assert_eq!(filter_anomalies_for_warn(&both, &mut last, t1, cooldown), vec![1]);
812 }
813
814 #[test]
815 fn recovered_pid_recrossing_the_threshold_warns_immediately() {
816 let mut last = HashMap::new();
817 let t0 = Instant::now();
818 let cooldown = Duration::from_secs(600);
819
820 assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t0, cooldown), vec![0]);
821 let t1 = t0 + Duration::from_secs(30);
824 assert!(filter_anomalies_for_warn(&[], &mut last, t1, cooldown).is_empty());
825 assert!(last.is_empty(), "healthy pid's entry must be pruned");
826 let t2 = t0 + Duration::from_secs(60);
829 assert_eq!(filter_anomalies_for_warn(&[anomaly(1)], &mut last, t2, cooldown), vec![0]);
830 }
831}
832
833#[cfg(all(test, target_os = "windows"))]
834mod commit_attribution_tests {
835 use super::*;
836
837 fn sample(pid: u32, name: &str, commit_mb: f64) -> ProcSample {
838 ProcSample { pid, name: name.to_string(), commit_mb, own: true }
839 }
840
841 fn foreign(pid: u32, name: &str, commit_mb: f64) -> ProcSample {
842 ProcSample { pid, name: name.to_string(), commit_mb, own: false }
843 }
844
845 #[test]
846 fn another_instances_agentmux_processes_are_other_not_ours() {
847 let samples = vec![
850 sample(201, "agentmux-srv-0.59.31-windows.x64.exe", 90.0),
851 sample(202, "agentmux-cef.exe", 300.0),
852 foreign(101, "agentmux-srv-0.59.30-windows.x64.exe", 120.0),
853 foreign(102, "agentmux-cef.exe", 900.0),
854 ];
855 let result = classify_commit_attribution(&samples, &HashSet::new(), 5);
856 assert_eq!(result.agentmux_mb, 390.0, "only this instance's processes");
857 assert_eq!(result.other_mb, 1020.0, "the other instance is counted, under other");
858 assert_eq!(result.panes_mb, 0.0);
859 }
860
861 #[test]
862 fn buckets_agentmux_by_name_regardless_of_pane_membership() {
863 let samples = vec![sample(100, "agentmux-cef.exe", 500.0)];
867 let mut pane_pids = HashSet::new();
868 pane_pids.insert(100);
869 let result = classify_commit_attribution(&samples, &pane_pids, 5);
870 assert_eq!(result.agentmux_mb, 500.0);
871 assert_eq!(result.panes_mb, 0.0);
872 }
873
874 #[test]
875 fn buckets_pane_pids_by_membership_not_name() {
876 let samples = vec![sample(200, "node.exe", 300.0), sample(201, "conhost.exe", 10.0)];
879 let mut pane_pids = HashSet::new();
880 pane_pids.insert(200);
881 pane_pids.insert(201);
882 let result = classify_commit_attribution(&samples, &pane_pids, 5);
883 assert_eq!(result.panes_mb, 310.0);
884 assert_eq!(result.agentmux_mb, 0.0);
885 assert!(result.other_top.is_empty());
886 }
887
888 #[test]
889 fn everything_else_falls_to_other_ranked_and_capped() {
890 let samples = vec![
891 sample(1, "chrome.exe", 800.0),
892 sample(2, "Code.exe", 600.0),
893 sample(3, "Docker Desktop.exe", 1200.0),
894 sample(4, "explorer.exe", 150.0),
895 ];
896 let result = classify_commit_attribution(&samples, &HashSet::new(), 2);
897 assert_eq!(result.other_mb, 800.0 + 600.0 + 1200.0 + 150.0);
899 assert_eq!(result.other_top.len(), 2);
901 assert_eq!(result.other_top[0].0, "Docker Desktop.exe");
902 assert_eq!(result.other_top[1].0, "chrome.exe");
903 }
904
905 #[test]
906 fn aggregates_other_by_name_before_ranking_so_a_multi_process_app_is_not_split_below_the_cutoff() {
907 let samples = vec![
914 sample(1, "chrome.exe", 100.0),
915 sample(2, "chrome.exe", 100.0),
916 sample(3, "chrome.exe", 100.0),
917 sample(4, "chrome.exe", 100.0),
918 sample(5, "single_app.exe", 250.0),
919 ];
920 let result = classify_commit_attribution(&samples, &HashSet::new(), 1);
921 assert_eq!(result.other_mb, 650.0);
922 assert_eq!(result.other_top.len(), 1);
923 assert_eq!(result.other_top[0], ("chrome.exe".to_string(), 400.0));
924 }
925
926 #[test]
927 fn name_match_is_case_insensitive() {
928 let samples = vec![sample(1, "AgentMux-Srv.exe", 42.0)];
929 let result = classify_commit_attribution(&samples, &HashSet::new(), 5);
930 assert_eq!(result.agentmux_mb, 42.0);
931 }
932
933 #[test]
934 fn empty_process_list_yields_zeroed_result() {
935 let result = classify_commit_attribution(&[], &HashSet::new(), 5);
936 assert_eq!(result.agentmux_mb, 0.0);
937 assert_eq!(result.panes_mb, 0.0);
938 assert_eq!(result.other_mb, 0.0);
939 assert!(result.other_top.is_empty());
940 }
941
942 #[test]
950 fn log_memory_attribution_runs_against_the_real_process_table_without_panicking() {
951 let mut sys = sysinfo::System::new_all();
952 log_memory_attribution(&mut sys, 0.0, 0.0); assert!(
954 sys.processes().len() > 1,
955 "expected the real process table to have picked up more than just this test binary"
956 );
957 }
958}
959
960pub(crate) struct NetState {
962 prev_sent: u64,
963 prev_recv: u64,
964 prev_time: Option<Instant>,
965}
966
967impl NetState {
968 pub(crate) fn new() -> Self {
969 Self {
970 prev_sent: 0,
971 prev_recv: 0,
972 prev_time: None,
973 }
974 }
975
976 fn get_net_data(&mut self, totals: (u64, u64), values: &mut HashMap<String, f64>) {
978 self.get_net_data_at(Instant::now(), totals, values);
979 }
980
981 pub(crate) fn get_net_data_at(&mut self, now: Instant, (total_sent, total_recv): (u64, u64), values: &mut HashMap<String, f64>) {
984 if let Some(prev_time) = self.prev_time {
985 let elapsed = now.duration_since(prev_time).as_secs_f64();
986 if elapsed > 0.0 {
987 let sent_rate = (total_sent.saturating_sub(self.prev_sent)) as f64 / elapsed / BYTES_PER_MB;
988 let recv_rate = (total_recv.saturating_sub(self.prev_recv)) as f64 / elapsed / BYTES_PER_MB;
989 values.insert("net:bytessent".to_string(), sent_rate);
990 values.insert("net:bytesrecv".to_string(), recv_rate);
991 values.insert("net:bytestotal".to_string(), sent_rate + recv_rate);
992 }
993 }
994
995 self.prev_sent = total_sent;
996 self.prev_recv = total_recv;
997 self.prev_time = Some(now);
998 }
999}
1000
1001fn get_disk_data(disks: &Disks, elapsed_secs: f64, values: &mut HashMap<String, f64>) {
1005 let mut seen_mounts: HashSet<&std::path::Path> = HashSet::new();
1014 for disk in disks.list() {
1015 let mount = disk.mount_point();
1016 if !seen_mounts.insert(mount) {
1017 continue;
1018 }
1019 let total = disk.total_space();
1020 if total == 0 {
1021 continue;
1022 }
1023 let mount_str = mount.to_string_lossy();
1024 values.insert(
1025 format!("disk:vol:{}:free_gb", mount_str),
1026 disk.available_space() as f64 / BYTES_PER_GB,
1027 );
1028 values.insert(
1029 format!("disk:vol:{}:total_gb", mount_str),
1030 total as f64 / BYTES_PER_GB,
1031 );
1032 }
1033
1034 if elapsed_secs <= 0.0 {
1035 return;
1036 }
1037 let (total_read, total_write) = disks.list().iter().fold((0u64, 0u64), |(r, w), disk| {
1038 let u = disk.usage();
1039 (r + u.read_bytes, w + u.written_bytes)
1040 });
1041 let read_rate = total_read as f64 / elapsed_secs / BYTES_PER_MB;
1042 let write_rate = total_write as f64 / elapsed_secs / BYTES_PER_MB;
1043 values.insert("disk:read".to_string(), read_rate);
1044 values.insert("disk:write".to_string(), write_rate);
1045 values.insert("disk:total".to_string(), read_rate + write_rate);
1046}
1047
1048#[cfg(not(target_os = "windows"))]
1056fn pick_watch_mount<'a>(mounts: &[&'a std::path::Path], target: &std::path::Path) -> Option<&'a std::path::Path> {
1057 mounts
1058 .iter()
1059 .filter(|m| target.starts_with(m))
1060 .max_by_key(|m| m.as_os_str().len())
1061 .copied()
1062}
1063
1064#[cfg(not(target_os = "windows"))]
1074fn get_watch_volume_data(disks: &Disks, values: &mut HashMap<String, f64>) {
1075 let data_dir = crate::backend::base::get_mux_data_dir();
1076 let mounts: Vec<&std::path::Path> = disks.list().iter().map(|d| d.mount_point()).collect();
1077 let root = std::path::Path::new("/");
1078 let watch = pick_watch_mount(&mounts, &data_dir).unwrap_or(root);
1079
1080 write_watch_summary(watch, watch == root, values);
1081}
1082
1083#[cfg(not(target_os = "windows"))]
1094fn write_watch_summary(mount: &std::path::Path, is_system_drive: bool, values: &mut HashMap<String, f64>) {
1095 let mount_str = mount.to_string_lossy();
1096 let (Some(free_gb), Some(total_gb)) = (
1097 values.get(&format!("disk:vol:{mount_str}:free_gb")).copied(),
1098 values.get(&format!("disk:vol:{mount_str}:total_gb")).copied(),
1099 ) else {
1100 return;
1101 };
1102 if total_gb <= 0.0 {
1103 return;
1104 }
1105
1106 values.insert("disk:watch:free_gb".to_string(), free_gb);
1107 values.insert("disk:watch:total_gb".to_string(), total_gb);
1108 values.insert("disk:watch:free_pct".to_string(), (free_gb / total_gb) * 100.0);
1109 values.insert(format!("disk:vol:{mount_str}:watch"), 1.0);
1110 values.insert(
1111 format!("disk:vol:{mount_str}:is_system_drive"),
1112 if is_system_drive { 1.0 } else { 0.0 },
1113 );
1114}
1115
1116fn get_interval_secs(config_watcher: &ConfigState) -> f64 {
1118 let val = config_watcher.get_settings().telemetry_interval;
1119 if val <= 0.0 {
1120 return DEFAULT_INTERVAL_SECS;
1121 }
1122 val.clamp(MIN_INTERVAL_SECS, MAX_INTERVAL_SECS)
1123}
1124
1125pub async fn run_sysinfo_loop(
1131 broker: Arc<Broker>,
1132 config_watcher: Arc<ConfigState>,
1133 conn_name: String,
1134 panes: crate::backend::sampler::panes::PaneSampler,
1135 stop: Arc<AtomicBool>,
1136) {
1137 let kind = sysinfo::RefreshKind::everything().without_processes();
1139 let mut sys = sysinfo::System::new_with_specifics(kind);
1140 let mut networks = NetCounters::new();
1141 let mut net_state = NetState::new();
1142 let mut disks = Disks::new_with_refreshed_list();
1143 let mut last_disk_full_refresh = Instant::now();
1144 let mut last_tick = Instant::now();
1145 #[cfg(target_os = "windows")]
1148 let mut last_attribution = Instant::now()
1149 .checked_sub(ATTRIBUTION_INTERVAL)
1150 .unwrap_or_else(Instant::now);
1151 #[cfg(target_os = "windows")]
1152 let mut last_urgent_attribution: Option<Instant> = None;
1153
1154 let mut peaks = crate::backend::blockstats_detail::Peaks::default();
1156
1157 let epoch = Instant::now();
1164 let since_epoch = |t: Instant| t.duration_since(epoch).as_millis() as u64;
1165 let min_interval_ms = (MIN_INTERVAL_SECS * 1000.0) as u64;
1166 let mut sched = Scheduler::new(
1167 vec![
1168 SourceSpec { id: SourceId::Machine, min_interval_ms, budget_ms: NEVER_STRETCHED, needs: &[] },
1172 SourceSpec { id: SourceId::Panes, min_interval_ms, budget_ms: 400, needs: &[] },
1173 ],
1174 SCHEDULER_COALESCE_MS,
1175 );
1176 let mut watched = false;
1177 let mut late_ticks = crate::backend::sampler::late_tick::LateTickLog::default();
1178 let mut current_interval = get_interval_secs(&config_watcher);
1179 sched.lease(HOLDER_TELEMETRY, SourceId::Machine, (current_interval * 1000.0) as u64, None, 0);
1180 sched.lease(HOLDER_JANITOR, SourceId::Panes, PANE_JANITOR_MS, None, 0);
1181 sched.finished(SourceId::Machine, 0, 0);
1183 sched.finished(SourceId::Panes, 0, 0);
1184
1185 tracing::info!("sysinfo loop started for conn:{}", conn_name);
1186
1187 while !stop.load(Ordering::Relaxed) {
1188 let now_ms = since_epoch(Instant::now());
1189 let new_interval = get_interval_secs(&config_watcher);
1190 if (new_interval - current_interval).abs() > 0.001 {
1191 current_interval = new_interval;
1192 tracing::info!("sysinfo interval changed to {}s", current_interval);
1193 }
1194 let interval_ms = (current_interval * 1000.0) as u64;
1195 sched.lease(HOLDER_TELEMETRY, SourceId::Machine, interval_ms, None, now_ms);
1196 let has_viewers = broker.has_subscribers(crate::backend::mps::EVENT_BLOCK_STATS);
1197 if has_viewers {
1198 sched.lease(HOLDER_BADGES, SourceId::Panes, interval_ms, None, now_ms);
1199 } else {
1200 sched.release_source(HOLDER_BADGES, SourceId::Panes, now_ms);
1201 }
1202 if has_viewers != watched {
1203 watched = has_viewers;
1204 tracing::debug!(watched, "sysinfo: pane stats {}", if watched { "have a viewer" } else { "have no viewer" });
1205 }
1206 let planned = sched.planned_wakeup(now_ms).unwrap_or(now_ms + interval_ms);
1207 let wake = sched.next_wakeup(now_ms).unwrap_or(now_ms + interval_ms);
1208 if wake > now_ms {
1209 tokio::time::sleep_until(tokio::time::Instant::from_std(epoch + Duration::from_millis(wake))).await;
1210 }
1211 let woke_ms = since_epoch(Instant::now());
1212 if let Some(late) = late_ticks.check(planned, woke_ms) {
1213 tracing::warn!(late_ms = late.late_ms, also_late = late.also, "sysinfo: a tick ran late; a chart breaks after 3 s without a sample");
1214 }
1215 let due = sched.due(woke_ms);
1216
1217 if due.contains(&SourceId::Machine) {
1218 let run_started = Instant::now();
1219 let mut pagefile_values = HashMap::new();
1222 sys.refresh_cpu_usage();
1223 sys.refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
1225 let net_totals = networks.totals();
1226 if last_disk_full_refresh.elapsed() >= DISK_FULL_REFRESH {
1227 disks.refresh(true);
1228 last_disk_full_refresh = Instant::now();
1229 } else {
1230 for disk in disks.list_mut() {
1231 disk.refresh_specifics(DiskRefreshKind::nothing().with_io_usage());
1232 }
1233 }
1234 get_pagefile_volume_data(&mut pagefile_values);
1235
1236 let now_instant = Instant::now();
1237 let elapsed_secs = now_instant.duration_since(last_tick).as_secs_f64();
1238 last_tick = now_instant;
1239
1240 let mut values = pagefile_values;
1241 values.insert(SAMPLE_WINDOW_KEY.to_string(), elapsed_secs * 1000.0);
1243 get_cpu_data(&sys, &mut values);
1244 crate::backend::sampler::own_processes::sample_into(sys.cpus().len(), &mut values);
1245 get_mem_data(&sys, &mut values);
1246 get_commit_data(&mut values);
1247 net_state.get_net_data(net_totals, &mut values);
1248 get_disk_data(&disks, elapsed_secs, &mut values);
1249 crate::backend::gpu::add_compact_values(&mut values);
1250 #[cfg(not(target_os = "windows"))]
1254 get_watch_volume_data(&disks, &mut values);
1255
1256 #[cfg(target_os = "windows")]
1267 {
1268 let commit_avail_gb = match (values.get("mem:commit:total"), values.get("mem:commit:used")) {
1269 (Some(total), Some(used)) => Some(total - used),
1270 _ => None,
1271 };
1272 let due_periodic = now_instant.duration_since(last_attribution) >= ATTRIBUTION_INTERVAL;
1273 let due_urgent = commit_avail_gb.is_some_and(|gb| gb < ATTRIBUTION_URGENT_THRESHOLD_GB)
1274 && last_urgent_attribution
1275 .is_none_or(|t| now_instant.duration_since(t) >= ATTRIBUTION_URGENT_COOLDOWN);
1276 if due_periodic || due_urgent {
1277 let commit_used_gb = *values.get("mem:commit:used").unwrap_or(&0.0);
1278 let commit_total_gb = *values.get("mem:commit:total").unwrap_or(&0.0);
1279 log_memory_attribution(&mut sys, commit_used_gb, commit_total_gb);
1280 last_attribution = now_instant;
1281 if due_urgent {
1282 last_urgent_attribution = Some(now_instant);
1283 }
1284 }
1285 }
1286
1287 let now = agentmux_common::time::now_ms();
1288
1289 let ts_data = TimeSeriesData { ts: now, values, uptime_secs: Some(uptime_secs()) };
1290
1291 broker.publish_event::<crate::backend::mps_events::SysInfo>(&ts_data, vec![conn_name.clone()], PERSIST_COUNT);
1292 sched.finished(SourceId::Machine, since_epoch(run_started), run_started.elapsed().as_millis() as u64);
1293 }
1294
1295 if due.contains(&SourceId::Panes) {
1296 let run_started = Instant::now();
1297 let now = agentmux_common::time::now_ms();
1298 let registered = pidregistry::get_all();
1304 let asked = Instant::now();
1305 match panes() {
1306 Ok(stats) => {
1307 peaks.retain(|id| stats.iter().any(|s| s.block_id == id));
1308 for s in &stats {
1309 let mut values = HashMap::new();
1310 if let Some(cpu) = s.cpu_pct {
1311 values.insert("cpu".to_string(), cpu);
1312 }
1313 values.insert("mem".to_string(), s.mem as f64);
1314 values.insert("pids".to_string(), f64::from(s.pids));
1315 let peak = peaks.observe(&s.block_id, s.shell, s.mem);
1316 values.insert("mem:peak".to_string(), peak as f64);
1317 let block_ts = TimeSeriesData { ts: now, values, uptime_secs: None };
1319 broker.publish_event::<crate::backend::mps_events::BlockStats>(
1320 &block_ts,
1321 vec![format!("block:{}", s.block_id)],
1322 0,
1323 );
1324 }
1325 }
1326 Err(e) => tracing::debug!(error = %e, "sysinfo: pane stats sample failed"),
1327 }
1328 if let Some(live) = crate::backend::tower::sampler::Tower::global().live_pids_since(asked) {
1334 for (block_id, pid) in registered {
1335 if !live.contains(&pid) {
1336 pidregistry::unregister(&block_id);
1337 tracing::warn!(
1338 block_id = %block_id,
1339 "sysinfo: evicted dead root PID — process exited without normal cleanup"
1340 );
1341 }
1342 }
1343 }
1344 sched.finished(SourceId::Panes, since_epoch(run_started), run_started.elapsed().as_millis() as u64);
1345 }
1346 }
1347}
1348
1349#[cfg(test)]
1350mod uptime_tests {
1351 use super::*;
1352
1353 #[test]
1361 fn uptime_is_monotonic_and_the_start_marker_is_idempotent() {
1362 mark_process_start();
1363 let first = uptime_secs();
1364 mark_process_start();
1365 let second = uptime_secs();
1366 assert!(second >= first, "uptime went backwards: {second} < {first}");
1367 }
1368
1369 #[test]
1373 fn suspend_aware_clock_is_nonzero_and_never_decreases() {
1374 let a = suspend_aware_now_ms();
1375 let b = suspend_aware_now_ms();
1376 assert!(a > 0, "suspend-aware clock returned 0 — clock_gettime failed?");
1377 assert!(b >= a, "suspend-aware clock went backwards: {b} < {a}");
1378 assert!(a < 10 * 365 * 24 * 60 * 60 * 1_000, "implausible ms reading: {a}");
1381 }
1382
1383 #[test]
1387 fn uptime_secs_is_emitted_when_present_and_omitted_when_absent() {
1388 let with = TimeSeriesData { ts: 5, values: HashMap::new(), uptime_secs: Some(42) };
1389 let v = serde_json::to_value(&with).expect("serialize");
1390 assert_eq!(v["uptime_secs"], serde_json::json!(42));
1391
1392 let without = TimeSeriesData { ts: 5, values: HashMap::new(), uptime_secs: None };
1393 let v = serde_json::to_value(&without).expect("serialize");
1394 assert!(
1395 v.get("uptime_secs").is_none(),
1396 "block-stats/CPU-stream payload shape must be byte-for-byte unchanged"
1397 );
1398 }
1399
1400 #[test]
1403 fn payload_without_uptime_still_deserializes() {
1404 let json = serde_json::json!({ "ts": 7, "values": { "cpu": 1.5 } });
1405 let parsed: TimeSeriesData = serde_json::from_value(json).expect("deserialize");
1406 assert_eq!(parsed.ts, 7);
1407 assert_eq!(parsed.uptime_secs, None);
1408 }
1409}
1410
1411#[cfg(all(test, not(target_os = "windows")))]
1412mod watch_volume_tests {
1413 use super::*;
1414 use std::path::Path;
1415
1416 #[test]
1420 fn longest_prefix_wins_over_root() {
1421 let mounts = [Path::new("/"), Path::new("/home"), Path::new("/boot")];
1422 let got = pick_watch_mount(&mounts, Path::new("/home/yas/.agentmux"));
1423 assert_eq!(got, Some(Path::new("/home")));
1424 }
1425
1426 #[test]
1427 fn falls_back_to_root_when_nothing_more_specific_matches() {
1428 let mounts = [Path::new("/"), Path::new("/boot")];
1429 let got = pick_watch_mount(&mounts, Path::new("/home/yas/.agentmux"));
1430 assert_eq!(got, Some(Path::new("/")));
1431 }
1432
1433 #[test]
1434 fn exact_mount_matches_itself() {
1435 let mounts = [Path::new("/"), Path::new("/data")];
1436 assert_eq!(pick_watch_mount(&mounts, Path::new("/data")), Some(Path::new("/data")));
1437 }
1438
1439 #[test]
1442 fn sibling_mount_is_not_a_prefix() {
1443 let mounts = [Path::new("/home2")];
1444 assert_eq!(pick_watch_mount(&mounts, Path::new("/home/yas")), None);
1445 }
1446
1447 #[test]
1448 fn empty_mount_list_yields_none() {
1449 assert_eq!(pick_watch_mount(&[], Path::new("/home/yas")), None);
1450 }
1451
1452 #[test]
1456 fn partial_volume_emits_no_summary() {
1457 let mut values: HashMap<String, f64> = HashMap::new();
1458 values.insert("disk:vol:/:total_gb".to_string(), 100.0);
1460 write_watch_summary(Path::new("/"), true, &mut values);
1461 assert!(!values.keys().any(|k| k.starts_with("disk:watch:")));
1462 }
1463
1464 #[test]
1465 fn zero_capacity_volume_emits_no_summary() {
1466 let mut values: HashMap<String, f64> = HashMap::new();
1467 values.insert("disk:vol:/:free_gb".to_string(), 0.0);
1468 values.insert("disk:vol:/:total_gb".to_string(), 0.0);
1469 write_watch_summary(Path::new("/"), true, &mut values);
1470 assert!(!values.keys().any(|k| k.starts_with("disk:watch:")));
1471 }
1472
1473 #[test]
1476 fn summary_matches_the_per_volume_figures() {
1477 let mut values: HashMap<String, f64> = HashMap::new();
1478 values.insert("disk:vol:/home:free_gb".to_string(), 35.0);
1479 values.insert("disk:vol:/home:total_gb".to_string(), 350.0);
1480 write_watch_summary(Path::new("/home"), false, &mut values);
1481
1482 assert_eq!(values["disk:watch:free_gb"], 35.0);
1483 assert_eq!(values["disk:watch:total_gb"], 350.0);
1484 assert!((values["disk:watch:free_pct"] - 10.0).abs() < 1e-9);
1485 assert_eq!(values["disk:vol:/home:watch"], 1.0);
1486 assert_eq!(values["disk:vol:/home:is_system_drive"], 0.0);
1487 }
1488
1489 #[test]
1490 fn root_watch_volume_is_marked_as_the_system_drive() {
1491 let mut values: HashMap<String, f64> = HashMap::new();
1492 values.insert("disk:vol:/:free_gb".to_string(), 1.9);
1493 values.insert("disk:vol:/:total_gb".to_string(), 345.0);
1494 write_watch_summary(Path::new("/"), true, &mut values);
1495 assert_eq!(values["disk:vol:/:is_system_drive"], 1.0);
1496 assert!(values["disk:watch:free_pct"] < 1.0);
1498 }
1499}