ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! AI Training and Inference Workload Monitoring
//!
//! This module provides real-time monitoring capabilities for AI/ML workloads including:
//! - Training metrics (epochs, steps, loss, accuracy)
//! - Inference metrics (throughput, latency, batch size)
//! - Multi-GPU/TPU distributed training tracking
//! - Cloud provider integration (AWS, Azure, GCP)
//! - Framework detection (PyTorch, TensorFlow, JAX, ONNX)
//!
//! # Examples
//!
//! ## Monitor Training Workload
//!
//! ```no_run
//! use ironmonitor::ai_workload::{AiWorkloadMonitor, WorkloadType};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut monitor = AiWorkloadMonitor::new()?;
//!
//! // Detect AI workloads
//! let workloads = monitor.detect_workloads()?;
//! for workload in &workloads {
//!     println!("Detected {} workload: PID {} - {}",
//!         workload.workload_type,
//!         workload.pid,
//!         workload.framework
//!     );
//!     
//!     if let Some(training) = &workload.training_metrics {
//!         println!("  Epoch: {}/{}", training.current_epoch, training.total_epochs);
//!         println!("  Loss: {:.4}", training.current_loss);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Monitor Inference Latency
//!
//! ```no_run
//! use ironmonitor::ai_workload::AiWorkloadMonitor;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut monitor = AiWorkloadMonitor::new()?;
//!
//! let workloads = monitor.detect_workloads()?;
//! for workload in workloads.iter().filter(|w| w.is_inference()) {
//!     if let Some(inference) = &workload.inference_metrics {
//!         println!("Inference workload PID {}:", workload.pid);
//!         println!("  Throughput: {:.2} samples/sec", inference.throughput);
//!         println!("  Latency: p50={:.2}ms, p95={:.2}ms, p99={:.2}ms",
//!             inference.latency_p50_ms,
//!             inference.latency_p95_ms,
//!             inference.latency_p99_ms
//!         );
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// AI/ML Framework
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AiFramework {
    PyTorch,
    TensorFlow,
    JAX,
    ONNX,
    TensorRT,
    MXNet,
    Keras,
    Caffe,
    Unknown,
}

impl std::fmt::Display for AiFramework {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::PyTorch => write!(f, "PyTorch"),
            Self::TensorFlow => write!(f, "TensorFlow"),
            Self::JAX => write!(f, "JAX"),
            Self::ONNX => write!(f, "ONNX"),
            Self::TensorRT => write!(f, "TensorRT"),
            Self::MXNet => write!(f, "MXNet"),
            Self::Keras => write!(f, "Keras"),
            Self::Caffe => write!(f, "Caffe"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Workload type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkloadType {
    Training,
    Inference,
    DataPreprocessing,
    FineTuning,
    Evaluation,
    Unknown,
}

impl std::fmt::Display for WorkloadType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Training => write!(f, "Training"),
            Self::Inference => write!(f, "Inference"),
            Self::DataPreprocessing => write!(f, "Data Preprocessing"),
            Self::FineTuning => write!(f, "Fine-tuning"),
            Self::Evaluation => write!(f, "Evaluation"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Training metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingMetrics {
    /// Current epoch number
    pub current_epoch: u32,
    /// Total epochs
    pub total_epochs: u32,
    /// Current step within epoch
    pub current_step: u32,
    /// Total steps per epoch
    pub steps_per_epoch: u32,
    /// Current training loss
    pub current_loss: f64,
    /// Current validation loss (if available)
    pub validation_loss: Option<f64>,
    /// Training accuracy (0-1)
    pub training_accuracy: Option<f64>,
    /// Validation accuracy (0-1)
    pub validation_accuracy: Option<f64>,
    /// Learning rate
    pub learning_rate: Option<f64>,
    /// Gradient norm
    pub gradient_norm: Option<f64>,
    /// Last checkpoint path
    pub last_checkpoint: Option<PathBuf>,
    /// Estimated time remaining in seconds
    pub eta_seconds: Option<u64>,
}

/// Inference metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InferenceMetrics {
    /// Samples processed per second
    pub throughput: f64,
    /// Batch size
    pub batch_size: u32,
    /// P50 latency in milliseconds
    pub latency_p50_ms: f64,
    /// P95 latency in milliseconds
    pub latency_p95_ms: f64,
    /// P99 latency in milliseconds
    pub latency_p99_ms: f64,
    /// Average latency in milliseconds
    pub latency_avg_ms: f64,
    /// Total samples processed
    pub total_samples: u64,
    /// Model name/path
    pub model_name: Option<String>,
}

/// Distributed training configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributedConfig {
    /// World size (total number of processes). `None` where the launcher's
    /// configuration does not state it.
    pub world_size: Option<u32>,
    /// Rank of this process. TensorFlow has no global rank, only an index
    /// within a role, so it is `None` there.
    pub rank: Option<u32>,
    /// Local rank (GPU index on this node), `None` when `LOCAL_RANK` is unset
    pub local_rank: Option<u32>,
    /// Backend (nccl, gloo, mpi), `None` when the environment does not name it
    pub backend: Option<String>,
    /// Master address
    pub master_addr: Option<String>,
    /// Master port
    pub master_port: Option<u16>,
}

/// TPU configuration
///
/// Every field the environment may omit is an `Option`. `num_cores` used to fall
/// back to `8` — a v2-8's core count, so a pod whose `TPU_NUM_CORES` was unset
/// was described as a specific, entirely plausible accelerator. `tpu_type` and
/// `topology` fell back to the string `"unknown"`, which `resolve.rs` rejects as
/// a value precisely because it reads as one.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TpuConfig {
    /// TPU type (v2, v3, v4, v5), or `None` when `TPU_TYPE` was not set.
    pub tpu_type: Option<String>,
    /// Number of TPU cores, or `None` when `TPU_NUM_CORES` was not set or did
    /// not parse.
    pub num_cores: Option<u32>,
    /// TPU topology (e.g., "2x2" for v2-8, "4x4" for v3-32), or `None` when
    /// `TPU_TOPOLOGY` was not set.
    pub topology: Option<String>,
    /// TPU zone (for cloud TPUs)
    pub zone: Option<String>,
    /// TPU project (for cloud TPUs)
    pub project: Option<String>,
}

/// Cloud provider
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CloudProvider {
    AWS,
    Azure,
    GCP,
    /// Not produced by any reader. Nothing observable in a process environment
    /// shows that a host is on-premise, so a host with no cloud evidence is
    /// `Unknown`. The variant is kept so the enum does not change.
    OnPremise,
    Unknown,
}

/// AI workload information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiWorkload {
    /// Process ID
    pub pid: u32,
    /// Process name
    pub name: String,
    /// Command line
    pub cmdline: String,
    /// Framework being used
    pub framework: AiFramework,
    /// Workload type
    pub workload_type: WorkloadType,
    /// Training metrics (if applicable)
    pub training_metrics: Option<TrainingMetrics>,
    /// Inference metrics (if applicable)
    pub inference_metrics: Option<InferenceMetrics>,
    /// GPU indices this process is attributed to. `None` where attribution does not run
    /// on this platform, or where it could not be read. `Some` with an empty list is a
    /// reading that found no GPU. Used to be an empty `Vec` on every platform that did not
    /// attribute, which read as "uses no GPU".
    pub gpu_indices: Option<Vec<usize>>,
    /// TPU configuration (if applicable)
    pub tpu_config: Option<TpuConfig>,
    /// Distributed configuration
    pub distributed_config: Option<DistributedConfig>,
    /// Cloud provider. `Unknown` unless the environment names one.
    pub cloud_provider: CloudProvider,
    /// The process environment, or `None` when it was not read. `Some` with an
    /// empty map is a process that really has no variables; the two must not be
    /// conflated.
    pub env_vars: Option<HashMap<String, String>>,
    /// Start time, or `None` when it was not read. Nothing here reads the
    /// process start time yet, so it is `None` on every platform. It used to be
    /// the time of the scan, which made every process look as if it started
    /// now.
    pub start_time: Option<std::time::SystemTime>,
}

impl AiWorkload {
    /// Check if this is a training workload
    pub fn is_training(&self) -> bool {
        matches!(
            self.workload_type,
            WorkloadType::Training | WorkloadType::FineTuning
        )
    }

    /// Check if this is an inference workload
    pub fn is_inference(&self) -> bool {
        self.workload_type == WorkloadType::Inference
    }

    /// Get progress percentage for training
    pub fn training_progress_percent(&self) -> Option<f32> {
        self.training_metrics.as_ref().map(|m| {
            if m.total_epochs == 0 {
                0.0
            } else {
                let epoch_progress =
                    m.current_epoch as f32 + (m.current_step as f32 / m.steps_per_epoch as f32);
                (epoch_progress / m.total_epochs as f32 * 100.0).min(100.0)
            }
        })
    }
}

/// AI workload monitor
pub struct AiWorkloadMonitor {
    /// Last detected workloads
    workloads: Vec<AiWorkload>,
    /// Update interval in seconds
    update_interval: u64,
    /// Last update time
    last_update: std::time::Instant,
}

impl AiWorkloadMonitor {
    /// Create a new AI workload monitor
    pub fn new() -> Result<Self> {
        Ok(Self {
            workloads: Vec::new(),
            update_interval: 5, // Default 5 second update
            last_update: std::time::Instant::now(),
        })
    }

    /// Create with custom update interval
    pub fn with_update_interval(interval_secs: u64) -> Result<Self> {
        Ok(Self {
            workloads: Vec::new(),
            update_interval: interval_secs,
            last_update: std::time::Instant::now(),
        })
    }

    /// Detect AI workloads running on the system
    pub fn detect_workloads(&mut self) -> Result<Vec<AiWorkload>> {
        // Check if we need to update
        if self.last_update.elapsed().as_secs() < self.update_interval {
            return Ok(self.workloads.clone());
        }

        self.workloads.clear();
        self.last_update = std::time::Instant::now();

        // Platform-specific detection
        #[cfg(target_os = "linux")]
        {
            self.detect_linux()?;
        }

        #[cfg(target_os = "windows")]
        {
            self.detect_windows()?;
        }

        #[cfg(target_os = "macos")]
        {
            self.detect_macos()?;
        }

        Ok(self.workloads.clone())
    }

    /// Get current workloads without refresh
    pub fn workloads(&self) -> &[AiWorkload] {
        &self.workloads
    }

    /// Set update interval
    pub fn set_update_interval(&mut self, interval_secs: u64) {
        self.update_interval = interval_secs;
    }

    #[cfg(target_os = "linux")]
    fn detect_linux(&mut self) -> Result<()> {
        use std::fs;

        // Scan /proc for Python/AI processes
        let proc_entries = fs::read_dir("/proc").map_err(crate::error::IronError::Io)?;

        for entry in proc_entries.filter_map(|e| e.ok()) {
            if let Ok(file_name) = entry.file_name().into_string() {
                if let Ok(pid) = file_name.parse::<u32>() {
                    if let Some(workload) = self.analyze_process_linux(pid)? {
                        self.workloads.push(workload);
                    }
                }
            }
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn analyze_process_linux(&self, pid: u32) -> Result<Option<AiWorkload>> {
        use std::fs;

        // Read command line
        let cmdline_path = format!("/proc/{}/cmdline", pid);
        let cmdline = fs::read_to_string(&cmdline_path)
            .ok()
            .map(|s| s.replace('\0', " ").trim().to_string())
            .unwrap_or_default();

        // Check if this looks like an AI workload
        let framework = self.detect_framework(&cmdline);
        if framework == AiFramework::Unknown {
            return Ok(None);
        }

        // Read process name. A process whose `comm` cannot be read has almost
        // certainly exited between the two reads, so it is skipped. It used to
        // be named `pid_<n>`, which is a name nothing reported.
        let comm_path = format!("/proc/{}/comm", pid);
        let name = match fs::read_to_string(&comm_path) {
            Ok(s) => s.trim().to_string(),
            Err(_) => return Ok(None),
        };

        // Detect workload type
        let workload_type = self.detect_workload_type(&cmdline);

        // Read environment variables. `None` when `environ` is unreadable (another
        // user's process, or one that exited); an empty map used to stand in for
        // that, which says the process had no variables.
        let environ_path = format!("/proc/{}/environ", pid);
        let env_vars: Option<HashMap<String, String>> = fs::read_to_string(&environ_path)
            .ok()
            .map(|s| self.parse_environ(&s));

        // Check for distributed training, TPU and cloud provider. Without an
        // environment none of them can be observed.
        let distributed_config = env_vars
            .as_ref()
            .and_then(|env| self.detect_distributed_config(env));
        let tpu_config = env_vars
            .as_ref()
            .and_then(|env| self.detect_tpu_config(env));
        let cloud_provider = env_vars.as_ref().map_or(CloudProvider::Unknown, |env| {
            self.detect_cloud_provider(env)
        });

        // Try to parse training metrics from logs or environment
        let training_metrics = if workload_type == WorkloadType::Training {
            self.try_parse_training_metrics(pid, env_vars.as_ref().unwrap_or(&HashMap::new()))?
        } else {
            None
        };

        // Try to parse inference metrics
        let inference_metrics = if workload_type == WorkloadType::Inference {
            self.try_parse_inference_metrics(pid)?
        } else {
            None
        };

        Ok(Some(AiWorkload {
            pid,
            name,
            cmdline,
            framework,
            workload_type,
            training_metrics,
            inference_metrics,
            gpu_indices: self.detect_gpu_usage(pid)?,
            tpu_config,
            distributed_config,
            cloud_provider,
            env_vars,
            start_time: None,
        }))
    }

    #[cfg(target_os = "windows")]
    fn detect_windows(&mut self) -> Result<()> {
        use crate::error::IronError;
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
            TH32CS_SNAPPROCESS,
        };

        // Take a snapshot of all processes
        let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }
            .map_err(|e| IronError::System(format!("Failed to create snapshot: {}", e)))?;

        let mut entry = PROCESSENTRY32W {
            dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
            ..Default::default()
        };

        // Get first process
        if unsafe { Process32FirstW(snapshot, &mut entry) }.is_err() {
            unsafe { CloseHandle(snapshot).ok() };
            return Ok(());
        }

        loop {
            let exe_name: String = entry
                .szExeFile
                .iter()
                .take_while(|&&c| c != 0)
                .map(|&c| c as u8 as char)
                .collect();

            let exe_lower = exe_name.to_lowercase();
            let pid = entry.th32ProcessID;

            // Check if this is a Python process or known AI runtime
            let is_ai_candidate = exe_lower.contains("python")
                || exe_lower.contains("pytorch")
                || exe_lower.contains("tensorflow")
                || exe_lower.contains("ollama")
                || exe_lower.contains("llama")
                || exe_lower.contains("triton")
                || exe_lower.contains("vllm")
                || exe_lower.contains("onnx")
                || exe_lower.contains("tensorrt")
                || exe_lower.contains("nvinfer")
                || exe_lower.contains("cuda");

            if is_ai_candidate {
                // Try to get full command line (requires opening process)
                if let Ok(Some(w)) = self.analyze_process_windows(pid, &exe_name) {
                    self.workloads.push(w);
                }
            }

            // Get next process
            if unsafe { Process32NextW(snapshot, &mut entry) }.is_err() {
                break;
            }
        }

        unsafe { CloseHandle(snapshot).ok() };
        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn analyze_process_windows(&self, pid: u32, exe_name: &str) -> Result<Option<AiWorkload>> {
        // Try to detect framework from executable name
        let exe_lower = exe_name.to_lowercase();

        // Determine framework
        let framework = if exe_lower.contains("python") {
            // Could be any Python-based framework, mark as unknown and use GPU detection
            AiFramework::Unknown
        } else if exe_lower.contains("triton")
            || exe_lower.contains("nvinfer")
            || exe_lower.contains("tensorrt")
        {
            AiFramework::TensorRT
        } else if exe_lower.contains("onnx") {
            AiFramework::ONNX
        } else {
            // Ollama lands here. It used to be mapped to ONNX, on the claim that
            // it "uses GGML/ONNX internally". That is a fact about its
            // implementation that nothing in the process shows, so the name
            // alone does not identify a framework.
            AiFramework::Unknown
        };

        // Check if this process is using GPU via NVML
        let gpu_indices = self.detect_gpu_usage(pid)?;

        // A `None` list is not evidence of GPU use, so it does not count as GPU use here.
        // The skip keeps its existing meaning: no GPU evidence and no framework.
        let gpu_in_use = gpu_indices.as_deref().is_some_and(|g| !g.is_empty());

        // If no GPU usage and unknown framework, skip
        if !gpu_in_use && framework == AiFramework::Unknown {
            return Ok(None);
        }

        // Determine workload type
        let workload_type = if exe_lower.contains("train") {
            WorkloadType::Training
        } else if exe_lower.contains("serve") || exe_lower.contains("server") {
            WorkloadType::Inference
        } else if gpu_in_use {
            // Has GPU, likely inference or training
            WorkloadType::Inference
        } else {
            WorkloadType::Unknown
        };

        Ok(Some(AiWorkload {
            pid,
            name: exe_name.to_string(),
            cmdline: exe_name.to_string(), // Full cmdline requires more complex WMI query
            // Previously promoted an unidentified framework to PyTorch whenever
            // the process held a GPU. A Python process on a GPU is as likely to
            // be JAX, TensorFlow, ONNX Runtime or vLLM -- or a CUDA program that
            // is not machine learning at all -- and the guess reached the user
            // through `tuning::serve`, which reports `ai_frameworks` beside the
            // evidence string "an AI framework was identified in a running
            // process". Identified is exactly what it was not.
            //
            // `ai_present` does not depend on this and is unaffected: holding a
            // GPU is still evidence of an AI workload. Only the claim about
            // *which* framework is withdrawn.
            framework,
            workload_type,
            training_metrics: None,
            inference_metrics: None,
            gpu_indices,
            tpu_config: None,
            distributed_config: None,
            // The environment of another process is not read on Windows, so the
            // variables are `None`, not an empty map, which would say the process
            // had none.
            cloud_provider: CloudProvider::Unknown,
            env_vars: None,
            start_time: None,
        }))
    }

    #[cfg(target_os = "macos")]
    fn detect_macos(&mut self) -> Result<()> {
        use crate::error::IronError;
        use std::process::Command;

        // Use ps to list all processes with full command lines
        let output = Command::new("ps")
            .args(["-axo", "pid,command"])
            .output()
            .map_err(|e| IronError::System(format!("Failed to run ps: {}", e)))?;

        let stdout = String::from_utf8_lossy(&output.stdout);

        // AI-related keywords to look for
        let ai_keywords = [
            "python",
            "ollama",
            "mlx",
            "coreml",
            "pytorch",
            "tensorflow",
            "torch",
            "transformers",
            "llama",
            "llama.cpp",
            "whisper",
            "stable-diffusion",
            "diffusion",
            "comfyui",
            "automatic1111",
            "vllm",
        ];

        for line in stdout.lines().skip(1) {
            // Skip header
            let parts: Vec<&str> = line.trim().splitn(2, ' ').collect();
            if parts.len() < 2 {
                continue;
            }

            let pid: u32 = match parts[0].trim().parse() {
                Ok(p) => p,
                Err(_) => continue,
            };
            let cmdline = parts[1].to_lowercase();

            // Check if this looks like an AI workload
            let is_ai_process = ai_keywords.iter().any(|kw| cmdline.contains(kw));
            if !is_ai_process {
                continue;
            }

            // Analyze the process
            if let Some(workload) = self.analyze_process_macos(pid, &cmdline)? {
                self.workloads.push(workload);
            }
        }

        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn analyze_process_macos(&self, pid: u32, cmdline: &str) -> Result<Option<AiWorkload>> {
        use std::process::Command;

        let process_name = cmdline
            .split('/')
            .next_back()
            .unwrap_or("unknown")
            .split_whitespace()
            .next()
            .unwrap_or("unknown")
            .to_string();

        // Skip common non-AI processes
        if matches!(
            process_name.as_str(),
            "grep" | "ps" | "sh" | "bash" | "zsh" | "cat" | "head" | "tail"
        ) {
            return Ok(None);
        }

        // Get memory usage via ps
        let mem_output = Command::new("ps")
            .args(["-p", &pid.to_string(), "-o", "rss="])
            .output()
            .ok();

        let memory_mb = mem_output
            .and_then(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .trim()
                    .parse::<u64>()
                    .ok()
            })
            .unwrap_or(0)
            / 1024; // Convert KB to MB

        let framework = self.detect_framework(cmdline);
        let workload_type = self.detect_workload_type(cmdline);

        // This function was written against an older `AiWorkload` — it set
        // process_name, gpu_utilization, gpu_memory_mb, system_memory_mb,
        // cpu_percent, model_name, and an `accelerator` of a `HardwareAccelerator`
        // type that does not exist, and reached for a `CloudProvider::HuggingFace`
        // variant that does not either. Being macOS-only it had never been
        // compiled, so none of that was ever caught. It now builds the struct the
        // rest of the module uses.
        //
        // `memory_mb` is still read above because `ps` is already being run, but
        // the struct has no field for resident memory; the process monitor owns
        // that. Dropping the read entirely would remove a working measurement in
        // case this grows a home for it, so it is bound and explicitly unused.
        let _ = memory_mb;

        // The environment is not read here, and the process name does not show a
        // cloud provider. This used to report `OnPremise` for any `ollama` process,
        // which is a claim about the host, not something ps reported.
        let cloud_provider = CloudProvider::Unknown;

        Ok(Some(AiWorkload {
            pid,
            name: process_name,
            cmdline: cmdline.to_string(),
            framework,
            workload_type,
            // `ps` gives no training or inference telemetry, and there is no Metal
            // performance API call here to supply GPU figures.
            training_metrics: None,
            inference_metrics: None,
            // Metal attribution is not performed here, so this is unread rather than empty.
            gpu_indices: None,
            tpu_config: None,
            distributed_config: None,
            cloud_provider,
            env_vars: None,
            start_time: None,
        }))
    }

    /// Identify the framework from the executable and the module it runs with
    /// `-m`. Matching is on whole names only. A substring match used to read
    /// `scp tf.log host:` as TensorFlow and any path containing `jax` as JAX.
    #[allow(dead_code)]
    fn detect_framework(&self, cmdline: &str) -> AiFramework {
        let names = framework_names(cmdline);
        let has = |candidates: &[&str]| names_match(&names, candidates);

        if has(&["torch", "pytorch", "torchrun"]) {
            AiFramework::PyTorch
        } else if has(&["tensorflow", "tensorflow_model_server", "tf"]) {
            AiFramework::TensorFlow
        } else if has(&["jax"]) {
            AiFramework::JAX
        } else if has(&["onnx", "onnxruntime"]) {
            AiFramework::ONNX
        } else if has(&["tensorrt", "trt"]) {
            AiFramework::TensorRT
        } else if has(&["mxnet"]) {
            AiFramework::MXNet
        } else if has(&["keras"]) {
            AiFramework::Keras
        } else if has(&["caffe"]) {
            AiFramework::Caffe
        } else {
            AiFramework::Unknown
        }
    }

    #[allow(dead_code)]
    fn detect_workload_type(&self, cmdline: &str) -> WorkloadType {
        if cmdline.contains("train") || cmdline.contains("fit") {
            WorkloadType::Training
        } else if cmdline.contains("infer")
            || cmdline.contains("predict")
            || cmdline.contains("serve")
        {
            WorkloadType::Inference
        } else if cmdline.contains("fine-tune") || cmdline.contains("finetune") {
            WorkloadType::FineTuning
        } else if cmdline.contains("eval") || cmdline.contains("test") {
            WorkloadType::Evaluation
        } else if cmdline.contains("preprocess") || cmdline.contains("transform") {
            WorkloadType::DataPreprocessing
        } else {
            WorkloadType::Unknown
        }
    }

    #[allow(dead_code)]
    fn parse_environ(&self, environ: &str) -> HashMap<String, String> {
        environ
            .split('\0')
            .filter_map(|s| {
                let parts: Vec<&str> = s.splitn(2, '=').collect();
                if parts.len() == 2 {
                    Some((parts[0].to_string(), parts[1].to_string()))
                } else {
                    None
                }
            })
            .collect()
    }

    #[allow(dead_code)]
    fn detect_distributed_config(
        &self,
        env_vars: &HashMap<String, String>,
    ) -> Option<DistributedConfig> {
        // PyTorch distributed
        if let (Some(world_size), Some(rank)) = (
            env_vars.get("WORLD_SIZE").and_then(|s| s.parse().ok()),
            env_vars.get("RANK").and_then(|s| s.parse().ok()),
        ) {
            return Some(DistributedConfig {
                world_size: Some(world_size),
                rank: Some(rank),
                // Unset is not GPU 0, and an unnamed backend is not NCCL: the
                // process group is chosen in code, which the environment does
                // not show. These were 0 and "nccl".
                local_rank: env_vars.get("LOCAL_RANK").and_then(|s| s.parse().ok()),
                backend: env_vars
                    .get("BACKEND")
                    .or_else(|| env_vars.get("NCCL_BACKEND"))
                    .cloned(),
                master_addr: env_vars.get("MASTER_ADDR").cloned(),
                master_port: env_vars.get("MASTER_PORT").and_then(|s| s.parse().ok()),
            });
        }

        // TensorFlow distributed: `TF_CONFIG` is JSON naming every task in the
        // cluster by role. It used to be detected by presence alone and reported
        // as a world of one process at rank 0 -- a single-machine job, for a
        // configuration that exists only to describe a multi-machine one.
        if let Some(tf_config) = env_vars.get("TF_CONFIG") {
            let parsed: Option<serde_json::Value> = serde_json::from_str(tf_config).ok();
            let world_size = parsed.as_ref().and_then(|v| {
                let cluster = v.get("cluster")?.as_object()?;
                let tasks: usize = cluster
                    .values()
                    .map(|role| role.as_array().map_or(0, Vec::len))
                    .sum();
                u32::try_from(tasks).ok().filter(|&n| n > 0)
            });
            return Some(DistributedConfig {
                world_size,
                rank: None,
                local_rank: None,
                backend: Some("tensorflow".to_string()),
                master_addr: None,
                master_port: None,
            });
        }

        None
    }

    #[allow(dead_code)]
    fn detect_tpu_config(&self, env_vars: &HashMap<String, String>) -> Option<TpuConfig> {
        // Check for TPU environment variables
        env_vars
            .get("TPU_NAME")
            .or_else(|| env_vars.get("TPU_WORKER_NAME"))
            .map(|_tpu_name| TpuConfig {
                tpu_type: env_vars.get("TPU_TYPE").cloned(),
                num_cores: env_vars.get("TPU_NUM_CORES").and_then(|s| s.parse().ok()),
                topology: env_vars.get("TPU_TOPOLOGY").cloned(),
                zone: env_vars
                    .get("TPU_ZONE")
                    .or_else(|| env_vars.get("GCP_ZONE"))
                    .cloned(),
                project: env_vars.get("GCP_PROJECT").cloned(),
            })
    }

    #[allow(dead_code)]
    fn detect_cloud_provider(&self, env_vars: &HashMap<String, String>) -> CloudProvider {
        if env_vars.contains_key("AWS_REGION") || env_vars.contains_key("AWS_DEFAULT_REGION") {
            CloudProvider::AWS
        } else if env_vars.contains_key("AZURE_SUBSCRIPTION_ID") {
            CloudProvider::Azure
        } else if env_vars.contains_key("GCP_PROJECT")
            || env_vars.contains_key("GOOGLE_CLOUD_PROJECT")
        {
            CloudProvider::GCP
        } else {
            // No cloud evidence. `K8S_POD_NAME` says a container but not which
            // cloud, so it lands here too. This used to return `OnPremise` for
            // every host without a cloud variable, which is a claim about the
            // host that the environment cannot support.
            CloudProvider::Unknown
        }
    }

    #[allow(dead_code)]
    fn detect_gpu_usage(&self, _pid: u32) -> Result<Option<Vec<usize>>> {
        // Check which GPUs this process is using
        // This would ideally query GPU drivers, but for now we can check CUDA_VISIBLE_DEVICES.
        // Only a set CUDA_VISIBLE_DEVICES is a list. Its absence means the process sees every
        // GPU, which says nothing about which it uses, so that is `None` too. Windows and macOS
        // do not attribute GPU use at all, so they are `None`.
        #[cfg(target_os = "linux")]
        {
            use std::fs;
            let environ_path = format!("/proc/{}/environ", _pid);
            if let Ok(environ) = fs::read_to_string(&environ_path) {
                let env_map = self.parse_environ(&environ);
                if let Some(cuda_devices) = env_map.get("CUDA_VISIBLE_DEVICES") {
                    return Ok(Some(
                        cuda_devices
                            .split(',')
                            .filter_map(|s| s.trim().parse().ok())
                            .collect(),
                    ));
                }
            }
        }

        Ok(None)
    }

    #[allow(dead_code)]
    fn try_parse_training_metrics(
        &self,
        _pid: u32,
        _env_vars: &HashMap<String, String>,
    ) -> Result<Option<TrainingMetrics>> {
        // Try to find tensorboard logs, checkpoints, or other indicators
        // This is a simplified version - real implementation would need to:
        // 1. Check for TensorBoard event files
        // 2. Parse checkpoint files
        // 3. Monitor log files
        // 4. Use framework-specific APIs if available

        // For now, return None - would need more sophisticated monitoring
        Ok(None)
    }

    #[allow(dead_code)]
    fn try_parse_inference_metrics(&self, _pid: u32) -> Result<Option<InferenceMetrics>> {
        // Try to detect inference metrics
        // Would need to monitor network traffic, log files, or use framework APIs
        Ok(None)
    }
}

/// The names a command line can be identified by: the executable's base name
/// without its extension or version suffix (`python3.11` is `python3`), and
/// each dotted segment of a module given with `-m`. Splitting on whole
/// tokens is what keeps `jax` in a path from reading as JAX.
#[allow(dead_code)]
fn framework_names(cmdline: &str) -> Vec<String> {
    let words: Vec<&str> = cmdline.split_whitespace().collect();
    let mut names = Vec::new();

    if let Some(exe) = words.first() {
        if let Some(base) = exe.rsplit(['/', '\\']).next() {
            if let Some(stem) = base.split('.').next() {
                names.push(stem.to_string());
            }
        }
    }

    for pair in words.windows(2) {
        if pair[0] == "-m" {
            names.extend(pair[1].split('.').map(str::to_string));
        }
    }

    names
}

/// Whether any of `names` is one of `candidates`, compared as whole names.
#[allow(dead_code)]
fn names_match(names: &[String], candidates: &[&str]) -> bool {
    names.iter().any(|n| candidates.contains(&n.as_str()))
}

impl Default for AiWorkloadMonitor {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| Self {
            workloads: Vec::new(),
            update_interval: 5,
            last_update: std::time::Instant::now(),
        })
    }
}

#[cfg(test)]
mod tpu_absence_tests {
    use super::*;

    #[cfg(target_os = "linux")]
    #[test]
    fn distributed_settings_are_read_from_the_environment_not_assumed() {
        let monitor = AiWorkloadMonitor::new().unwrap();
        let env = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect()
        };

        let torch = monitor
            .detect_distributed_config(&env(&[("WORLD_SIZE", "8"), ("RANK", "3")]))
            .unwrap();
        assert_eq!((torch.world_size, torch.rank), (Some(8), Some(3)));
        assert_eq!(torch.local_rank, None, "unset LOCAL_RANK is not GPU 0");
        assert_eq!(torch.backend, None, "an unnamed backend is not NCCL");

        let tf = monitor
            .detect_distributed_config(&env(&[(
                "TF_CONFIG",
                r#"{"cluster":{"chief":["a:1"],"worker":["b:1","c:1"],"ps":["d:1"]},"task":{"type":"worker","index":1}}"#,
            )]))
            .unwrap();
        assert_eq!(tf.world_size, Some(4));
        assert_eq!(tf.rank, None);

        let unparsed = monitor
            .detect_distributed_config(&env(&[("TF_CONFIG", "not json")]))
            .unwrap();
        assert_eq!(unparsed.world_size, None);
    }

    fn detector() -> AiWorkloadMonitor {
        AiWorkloadMonitor::default()
    }

    #[test]
    fn a_tpu_with_no_core_count_in_the_environment_reports_none() {
        // `TPU_NAME` is what makes this a TPU host; the rest may be unset.
        let mut env = HashMap::new();
        env.insert("TPU_NAME".to_string(), "node-1".to_string());

        let cfg = detector()
            .detect_tpu_config(&env)
            .expect("TPU_NAME identifies a TPU host");
        assert_eq!(
            cfg.num_cores, None,
            "an unset TPU_NUM_CORES must not read as a v2-8"
        );
        assert_eq!(cfg.tpu_type, None);
        assert_eq!(cfg.topology, None);
    }

    #[test]
    fn a_tpu_that_declares_itself_is_reported_as_declared() {
        let mut env = HashMap::new();
        env.insert("TPU_NAME".to_string(), "node-1".to_string());
        env.insert("TPU_NUM_CORES".to_string(), "32".to_string());
        env.insert("TPU_TYPE".to_string(), "v3".to_string());
        env.insert("TPU_TOPOLOGY".to_string(), "4x4".to_string());

        let cfg = detector().detect_tpu_config(&env).unwrap();
        assert_eq!(cfg.num_cores, Some(32));
        assert_eq!(cfg.tpu_type.as_deref(), Some("v3"));
        assert_eq!(cfg.topology.as_deref(), Some("4x4"));
    }

    #[test]
    fn an_unparseable_core_count_is_absent_rather_than_defaulted() {
        let mut env = HashMap::new();
        env.insert("TPU_NAME".to_string(), "node-1".to_string());
        env.insert("TPU_NUM_CORES".to_string(), "many".to_string());

        assert_eq!(detector().detect_tpu_config(&env).unwrap().num_cores, None);
    }

    #[test]
    fn a_host_with_no_tpu_name_is_not_a_tpu_host() {
        assert!(detector().detect_tpu_config(&HashMap::new()).is_none());
    }

    #[test]
    fn a_host_with_no_cloud_evidence_is_unknown_not_on_premise() {
        assert_eq!(
            detector().detect_cloud_provider(&HashMap::new()),
            CloudProvider::Unknown
        );

        // A container name says the process is containerised, not which cloud.
        let mut env = HashMap::new();
        env.insert("K8S_POD_NAME".to_string(), "pod-1".to_string());
        assert_eq!(
            detector().detect_cloud_provider(&env),
            CloudProvider::Unknown
        );
    }

    #[test]
    fn framework_is_not_read_from_a_substring_of_an_argument() {
        let m = detector();
        // `tf.log` is a file, and `jaxen-notes` is a directory.
        assert_eq!(
            m.detect_framework("scp tf.log host:/data"),
            AiFramework::Unknown
        );
        assert_eq!(
            m.detect_framework("/home/u/jaxen-notes/run.sh"),
            AiFramework::Unknown
        );
        // Ollama is not identified as any framework from its name alone.
        assert_eq!(
            m.detect_framework("/usr/bin/ollama serve"),
            AiFramework::Unknown
        );
    }

    #[test]
    fn framework_is_named_by_its_executable_or_its_module() {
        let m = detector();
        assert_eq!(
            m.detect_framework("/usr/bin/python3 -m torch.distributed.run train.py"),
            AiFramework::PyTorch
        );
        assert_eq!(
            m.detect_framework("torchrun --nproc 4 train.py"),
            AiFramework::PyTorch
        );
        assert_eq!(
            m.detect_framework("python3.11 -m jax.tools"),
            AiFramework::JAX
        );
        assert_eq!(
            m.detect_framework("tensorflow_model_server --port=8500"),
            AiFramework::TensorFlow
        );
    }
}