use crate::error::IronError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SystemClass {
Workstation,
Server,
GamingDesktop,
Desktop,
Laptop,
GamingLaptop,
Ultrabook,
Embedded,
VirtualMachine,
CloudInstance,
MiniPc,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum PerformanceTier {
UltraLow, Low, MidLow, Mid, MidHigh, High, Ultra, Datacenter, }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BottleneckType {
CpuBound,
GpuBound,
MemoryBound,
StorageBound,
NetworkBound,
ThermalThrottling,
PowerLimited,
}
const BOTTLENECK_CONFIDENCE_CPU_GPU_IMBALANCE: f32 = 0.75;
const BOTTLENECK_CONFIDENCE_RAM_GPU_WORKLOADS: f32 = 0.7;
const BOTTLENECK_CONFIDENCE_RAM_PER_CORE: f32 = 0.65;
const BOTTLENECK_CONFIDENCE_NO_SSD: f32 = 0.85;
const BOTTLENECK_CONFIDENCE_SATA_HIGH_CORE: f32 = 0.6;
const BOTTLENECK_CONFIDENCE_SLOW_SERVER_NIC: f32 = 0.5;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bottleneck {
pub bottleneck_type: BottleneckType,
pub component: String,
pub severity: u8,
pub reason: String,
pub confidence: f32,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Workload {
MlTraining,
MlInference,
VideoEditing,
Rendering3D,
Gaming,
Compilation,
WebServer,
DatabaseServer,
Virtualization,
ScientificComputing,
OfficeProductivity,
MediaStreaming,
NetworkAppliance,
}
const WORKLOAD_CONFIDENCE_ML_TRAINING: f32 = 0.7;
const WORKLOAD_CONFIDENCE_ML_INFERENCE: f32 = 0.75;
const WORKLOAD_CONFIDENCE_GAMING: f32 = 0.8;
const WORKLOAD_CONFIDENCE_VIDEO_EDITING: f32 = 0.7;
const WORKLOAD_CONFIDENCE_COMPILATION: f32 = 0.8;
const WORKLOAD_CONFIDENCE_WEB_SERVER: f32 = 0.65;
const WORKLOAD_CONFIDENCE_DATABASE_SERVER: f32 = 0.65;
const WORKLOAD_CONFIDENCE_VIRTUALIZATION: f32 = 0.7;
const WORKLOAD_CONFIDENCE_OFFICE_PRODUCTIVITY: f32 = 0.9;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkloadSuitability {
pub workload: Workload,
pub score: u8,
pub confidence: f32,
pub limiting_factors: Vec<String>,
pub strengths: Vec<String>,
}
const AGE_CONFIDENCE_CPU_AND_GPU: f32 = 0.85;
const AGE_CONFIDENCE_CPU_OR_GPU: f32 = 0.65;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAge {
pub cpu_year: Option<u16>,
pub gpu_year: Option<u16>,
pub estimated_age_years: Option<f32>,
pub confidence: Option<f32>,
pub reasoning: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThermalEnvelope {
pub estimated_total_tdp_watts: Option<f32>,
pub cpu_tdp_watts: Option<f32>,
pub cpu_tdp_measured: bool,
pub gpu_tdp_watts: Option<f32>,
pub gpu_adapters_counted: u32,
pub gpu_tdp_measured: bool,
pub headroom: ThermalHeadroom,
pub cooling_score: Option<u8>,
pub recommendations: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThermalHeadroom {
Ample,
Adequate,
Marginal,
Insufficient,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpgradeRecommendation {
pub component: String,
pub current: String,
pub recommended: String,
pub description: String,
pub expected_impact: String,
pub priority: u8,
pub cost_tier: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAnomaly {
pub description: String,
pub severity: AnomalySeverity,
pub explanation: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnomalySeverity {
Info,
Warning,
Critical,
}
const CLASSIFICATION_CONFIDENCE_VIRTUAL_MACHINE: f32 = 0.95;
const CLASSIFICATION_WEIGHT_SERVER_CPU: f32 = 0.35;
const CLASSIFICATION_WEIGHT_SERVER_ECC: f32 = 0.2;
const CLASSIFICATION_WEIGHT_SERVER_PHYSICAL_CORES: f32 = 0.15;
const CLASSIFICATION_WEIGHT_SERVER_RAM: f32 = 0.1;
const CLASSIFICATION_WEIGHT_SERVER_NUMA: f32 = 0.15;
const CLASSIFICATION_WEIGHT_SERVER_CHASSIS: f32 = 0.3;
const CLASSIFICATION_WEIGHT_SERVER_NO_BATTERY: f32 = 0.05;
const CLASSIFICATION_WEIGHT_SERVER_NICS: f32 = 0.1;
const CLASSIFICATION_CONFIDENCE_SERVER_CAP: f32 = 0.95;
const CLASSIFICATION_WEIGHT_LAPTOP_MOBILE_CHASSIS: f32 = 0.6;
const CLASSIFICATION_WEIGHT_LAPTOP_BATTERY: f32 = 0.25;
const CLASSIFICATION_WEIGHT_LAPTOP_LOW_CORES: f32 = 0.05;
const CLASSIFICATION_WEIGHT_LAPTOP_LOW_RAM: f32 = 0.05;
const CLASSIFICATION_CONFIDENCE_LAPTOP_CAP: f32 = 0.95;
const CLASSIFICATION_SCALE_GAMING_LAPTOP: f32 = 0.9;
const CLASSIFICATION_SCALE_ULTRABOOK: f32 = 0.8;
const CLASSIFICATION_CONFIDENCE_WORKSTATION: f32 = 0.6;
const CLASSIFICATION_CONFIDENCE_GAMING_DESKTOP: f32 = 0.6;
const CLASSIFICATION_CONFIDENCE_DESKTOP: f32 = 0.5;
const CLASSIFICATION_CONFIDENCE_EMBEDDED: f32 = 0.8;
const CLASSIFICATION_CONFIDENCE_MINI_PC: f32 = 0.7;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareAnalysisReport {
pub classification: SystemClass,
pub classification_confidence: Option<f32>,
pub performance_tier: Option<PerformanceTier>,
pub performance_score: Option<u8>,
pub bottlenecks: Vec<Bottleneck>,
pub workload_scores: Vec<WorkloadSuitability>,
pub hardware_age: HardwareAge,
pub thermal_envelope: ThermalEnvelope,
pub upgrade_recommendations: Vec<UpgradeRecommendation>,
pub anomalies: Vec<HardwareAnomaly>,
pub hardware_fingerprint: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct HardwareFeatures {
cpu_cores_physical: Option<u32>,
cpu_cores_logical: Option<u32>,
cpu_max_freq_mhz: Option<u32>,
cpu_model: Option<String>,
cpu_vendor: Option<String>,
is_server_cpu: bool,
has_ecc: Option<bool>,
cpu_tdp_watts: Option<f32>,
cpu_tdp_measured: bool,
ram_total_gb: Option<f32>,
ram_channels: u32,
ram_speed_mhz: u32,
has_discrete_gpu: Option<bool>,
gpu_count: u32,
gpu_model: String,
gpu_vram_gb: Option<f32>,
has_tensor_cores: Option<bool>,
has_rt_cores: Option<bool>,
gpu_tdp_watts: Option<f32>,
gpu_tdp_measured: bool,
gpu_adapters_counted: u32,
has_nvme: Option<bool>,
has_ssd: Option<bool>,
total_storage_gb: Option<f32>,
boot_drive_type: Option<String>,
has_battery: bool,
chassis_type: Option<String>,
is_virtual: Option<bool>,
numa_nodes: Option<u32>,
pcie_gen: u32,
max_nic_speed_gbps: Option<f32>,
nic_count: Option<u32>,
}
impl HardwareFeatures {
fn chassis(&self) -> &str {
self.chassis_type.as_deref().unwrap_or("")
}
fn ram_at_least(&self, gb: f32) -> bool {
self.ram_total_gb.is_some_and(|v| v >= gb)
}
fn ram_below(&self, gb: f32) -> bool {
self.ram_total_gb.is_some_and(|v| v < gb)
}
fn vram_at_least(&self, gb: f32) -> bool {
self.gpu_vram_gb.is_some_and(|v| v >= gb)
}
fn vram_below(&self, gb: f32) -> bool {
self.gpu_vram_gb.is_some_and(|v| v < gb)
}
fn is_discrete_gpu(&self) -> bool {
self.has_discrete_gpu == Some(true)
}
}
#[cfg(target_os = "windows")]
fn wmi_enum(value: Option<&serde_json::Value>, names: &[(&str, u64)]) -> Option<u64> {
let value = value?;
if let Some(n) = value.as_u64() {
return Some(n);
}
let text = value.as_str()?.trim().to_ascii_lowercase();
names
.iter()
.find(|(name, _)| *name == text)
.map(|(_, code)| *code)
}
fn anything_read(f: &HardwareFeatures) -> bool {
f.cpu_cores_physical.is_some_and(|c| c > 0)
|| f.cpu_cores_logical.is_some_and(|c| c > 0)
|| f.cpu_max_freq_mhz.is_some_and(|c| c > 0)
|| f.cpu_model.is_some()
|| f.cpu_vendor.is_some()
|| f.ram_total_gb.is_some_and(|v| v > 0.0)
|| f.is_discrete_gpu()
|| f.gpu_count > 0
|| !f.gpu_model.is_empty()
|| f.has_battery
|| f.is_virtual == Some(true)
|| f.chassis_type.is_some()
|| f.nic_count.is_some_and(|n| n > 0)
|| f.max_nic_speed_gbps.is_some_and(|v| v > 0.0)
}
#[cfg(target_os = "windows")]
fn json_items(text: &str) -> Option<Vec<serde_json::Value>> {
let text = text.trim();
if text.starts_with('[') {
serde_json::from_str(text).ok()
} else {
serde_json::from_str::<serde_json::Value>(text)
.ok()
.map(|v| vec![v])
}
}
#[cfg(target_os = "linux")]
fn dmi_chassis_label(code: &str) -> Option<&'static str> {
match code {
"3" | "4" | "5" | "6" | "7" => Some("Desktop"),
"8" | "9" | "10" | "14" => Some("Laptop"),
"11" | "12" => Some("Handheld"),
"13" => Some("All-in-One"),
"17" | "23" => Some("Server"),
"35" | "36" => Some("Mini PC"),
_ => None,
}
}
#[cfg(target_os = "linux")]
fn khz_as_mhz(text: &str) -> Option<u32> {
text.trim()
.parse::<u32>()
.ok()
.map(|khz| khz / 1000)
.filter(|&mhz| mhz > 0)
}
#[cfg(target_os = "linux")]
fn base_disk_name(name: &str) -> Option<&str> {
if name.starts_with("nvme") {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
Some(match trimmed.strip_suffix('p') {
Some(disk) if disk.ends_with(|c: char| c.is_ascii_digit()) => disk,
_ => name,
})
} else if name.starts_with("sd") {
Some(name.trim_end_matches(|c: char| c.is_ascii_digit()))
} else {
None
}
}
#[cfg(all(test, target_os = "linux"))]
mod sysfs_parse_tests {
use super::*;
#[test]
fn cpufreq_is_read_in_khz_and_reported_in_mhz() {
assert_eq!(khz_as_mhz("5700000\n"), Some(5700));
assert_eq!(khz_as_mhz("2400000"), Some(2400));
assert_eq!(khz_as_mhz(""), None);
assert_eq!(khz_as_mhz("0\n"), None);
assert_eq!(khz_as_mhz("n/a"), None);
}
#[test]
fn a_root_partition_maps_to_its_whole_disk() {
assert_eq!(base_disk_name("nvme0n1p2"), Some("nvme0n1"));
assert_eq!(base_disk_name("nvme0n1"), Some("nvme0n1"));
assert_eq!(base_disk_name("sda2"), Some("sda"));
assert_eq!(base_disk_name("sda"), Some("sda"));
assert_eq!(base_disk_name("vda1"), None);
assert_eq!(base_disk_name("mapper/cryptroot"), None);
assert_eq!(base_disk_name("overlay"), None);
}
}
#[cfg(all(test, target_os = "linux"))]
mod dmi_chassis_tests {
use super::*;
#[test]
fn dmi_codes_map_to_labels_and_unmapped_codes_stay_unread() {
assert_eq!(dmi_chassis_label("3"), Some("Desktop"));
assert_eq!(dmi_chassis_label("10"), Some("Laptop"));
assert_eq!(dmi_chassis_label("17"), Some("Server"));
assert_eq!(dmi_chassis_label("2"), None);
assert_eq!(dmi_chassis_label(""), None);
}
}
pub struct HardwareInferenceEngine {
features: HardwareFeatures,
}
impl HardwareInferenceEngine {
pub fn new() -> Result<Self, IronError> {
let mut engine = Self {
features: HardwareFeatures::default(),
};
engine.extract_features();
Ok(engine)
}
pub fn from_features(features_json: &str) -> Result<Self, IronError> {
let features: HardwareFeatures = serde_json::from_str(features_json)
.map_err(|e| IronError::Parse(format!("Invalid features JSON: {}", e)))?;
Ok(Self { features })
}
pub fn full_analysis(&self) -> HardwareAnalysisReport {
let (classification, class_confidence) = self.classify_system();
let any_read = anything_read(&self.features);
let (tier, score) = self.compute_performance_tier();
let bottlenecks = self.detect_bottlenecks();
let workloads = self.score_workloads();
let age = self.estimate_hardware_age();
let thermal = self.analyze_thermal_envelope();
let upgrades = self.suggest_upgrades(&bottlenecks);
let anomalies = self.detect_anomalies();
let fingerprint = self.compute_fingerprint();
HardwareAnalysisReport {
classification,
classification_confidence: class_confidence,
performance_tier: any_read.then_some(tier),
performance_score: any_read.then_some(score),
bottlenecks,
workload_scores: workloads,
hardware_age: age,
thermal_envelope: thermal,
upgrade_recommendations: upgrades,
anomalies,
hardware_fingerprint: fingerprint,
}
}
fn extract_features(&mut self) {
self.extract_cpu_features();
self.extract_memory_features();
self.extract_gpu_features();
self.extract_storage_features();
self.extract_platform_features();
self.extract_network_features();
}
#[cfg(any(target_os = "windows", test))]
fn windows_cpu_identity(json: &serde_json::Value) -> (Option<String>, Option<String>) {
let elements: Vec<&serde_json::Value> = match json.as_array() {
Some(items) => items.iter().collect(),
None => vec![json],
};
let text = |item: &serde_json::Value, key: &str| {
item.get(key)
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
let agreed = |key: &str| {
let mut values = elements.iter().map(|item| text(item, key));
let first = values.next()??;
values
.all(|v| v.as_deref() == Some(first.as_str()))
.then_some(first)
};
(agreed("Name"), agreed("Manufacturer"))
}
fn extract_cpu_features(&mut self) {
#[cfg(target_os = "linux")]
{
if let Ok(cpuinfo) = std::fs::read_to_string("/proc/cpuinfo") {
let mut model = String::new();
let mut cores = std::collections::HashSet::new();
let mut logical = 0u32;
let mut vendor = String::new();
for line in cpuinfo.lines() {
if line.starts_with("model name") {
if let Some(m) = line.split(':').nth(1) {
model = m.trim().to_string();
}
}
if line.starts_with("vendor_id") {
if let Some(v) = line.split(':').nth(1) {
vendor = v.trim().to_string();
}
}
if line.starts_with("core id") {
if let Some(c) = line.split(':').nth(1) {
if let Ok(id) = c.trim().parse::<u32>() {
cores.insert(id);
}
}
}
if line.starts_with("processor") {
logical += 1;
}
}
self.features.cpu_model = (!model.is_empty()).then_some(model);
self.features.cpu_vendor = (!vendor.is_empty()).then_some(vendor);
let physical = if cores.is_empty() {
logical
} else {
cores.len() as u32
};
self.features.cpu_cores_physical = (physical > 0).then_some(physical);
self.features.cpu_cores_logical = (logical > 0).then_some(logical);
}
self.features.cpu_max_freq_mhz =
std::fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")
.ok()
.as_deref()
.and_then(khz_as_mhz);
}
#[cfg(target_os = "windows")]
{
if let Ok(output) = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command",
"Get-CimInstance Win32_Processor | Select-Object Name,Manufacturer,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed | ConvertTo-Json"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) {
(self.features.cpu_model, self.features.cpu_vendor) =
Self::windows_cpu_identity(&json);
self.features.cpu_cores_physical = json
.get("NumberOfCores")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
self.features.cpu_cores_logical = json
.get("NumberOfLogicalProcessors")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
self.features.cpu_max_freq_mhz = json
.get("MaxClockSpeed")
.and_then(|v| v.as_u64())
.map(|v| v as u32);
}
}
}
#[cfg(target_os = "macos")]
{
if let Ok(output) = std::process::Command::new("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()
{
self.features.cpu_model = String::from_utf8(output.stdout)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
}
if let Ok(output) = std::process::Command::new("sysctl")
.args(["-n", "hw.physicalcpu"])
.output()
{
self.features.cpu_cores_physical = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.parse()
.ok();
}
if let Ok(output) = std::process::Command::new("sysctl")
.args(["-n", "hw.logicalcpu"])
.output()
{
self.features.cpu_cores_logical = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.parse()
.ok();
}
}
let model_lower = self
.features
.cpu_model
.as_deref()
.unwrap_or("")
.to_lowercase();
self.features.is_server_cpu = model_lower.contains("xeon")
|| model_lower.contains("epyc")
|| model_lower.contains("threadripper")
|| model_lower.contains("platinum")
|| model_lower.contains("gold")
|| model_lower.contains("silver");
match Self::measured_cpu_power_cap_watts() {
Some(watts) => {
self.features.cpu_tdp_watts = Some(watts);
self.features.cpu_tdp_measured = true;
}
None => {
self.features.cpu_tdp_watts = Self::infer_cpu_tdp(&model_lower);
self.features.cpu_tdp_measured = false;
}
}
}
fn extract_memory_features(&mut self) {
#[cfg(target_os = "linux")]
{
if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
for line in meminfo.lines() {
if line.starts_with("MemTotal:") {
if let Some(kb) = line.split_whitespace().nth(1) {
if let Ok(k) = kb.parse::<u64>() {
self.features.ram_total_gb = Some(k as f32 / 1_048_576.0);
}
}
}
}
}
}
#[cfg(target_os = "windows")]
{
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_OperatingSystem).TotalVisibleMemorySize",
])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
if let Ok(kb) = text.trim().parse::<u64>() {
self.features.ram_total_gb = Some(kb as f32 / 1_048_576.0);
}
}
}
#[cfg(target_os = "macos")]
{
if let Ok(output) = std::process::Command::new("sysctl")
.args(["-n", "hw.memsize"])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
if let Ok(bytes) = text.trim().parse::<u64>() {
self.features.ram_total_gb = Some(bytes as f32 / 1_073_741_824.0);
}
}
}
}
fn extract_gpu_features(&mut self) {
#[cfg(target_os = "linux")]
{
if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("card") && !name.contains('-') {
let label = std::fs::read_to_string(entry.path().join("device/label"))
.or_else(|_| {
std::fs::read_to_string(entry.path().join("device/product_name"))
})
.unwrap_or_default()
.trim()
.to_string();
if !label.is_empty() {
self.features.gpu_model = label;
self.features.gpu_count += 1;
}
}
}
}
}
#[cfg(target_os = "windows")]
{
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-CimInstance Win32_VideoController | Select-Object Name | ConvertTo-Json",
])
.output()
{
let text = String::from_utf8(output.stdout).unwrap_or_default();
for gpu in json_items(&text).unwrap_or_default() {
if let Some(name) = gpu
.get("Name")
.and_then(|v| v.as_str())
.filter(|n| !n.is_empty())
{
self.features.gpu_model = name.to_string();
self.features.gpu_count += 1;
}
}
}
}
let adapters = Self::gpu_adapters();
let (discrete, vram) = Self::discrete_gpu_and_vram(adapters.as_deref());
self.features.has_discrete_gpu = discrete;
self.features.gpu_vram_gb = vram;
self.features.has_tensor_cores = None;
self.features.has_rt_cores = None;
let gpu_lower = self.features.gpu_model.to_lowercase();
let measured = adapters
.as_deref()
.and_then(Self::measured_gpu_power_caps_watts);
match measured {
Some((watts, counted)) => {
self.features.gpu_tdp_watts = Some(watts);
self.features.gpu_tdp_measured = true;
self.features.gpu_adapters_counted = counted;
}
None => {
let table = Self::infer_gpu_tdp(&gpu_lower);
self.features.gpu_adapters_counted = u32::from(table.is_some());
self.features.gpu_tdp_watts = table;
self.features.gpu_tdp_measured = false;
}
}
}
fn gpu_adapters() -> Option<Vec<crate::GpuInfo>> {
let monitor = crate::UnifiedMonitor::new().ok()?;
monitor.snapshot_gpus().ok()
}
fn discrete_gpu_and_vram(adapters: Option<&[crate::GpuInfo]>) -> (Option<bool>, Option<f32>) {
const GIB: f32 = 1_073_741_824.0;
let Some(gpus) = adapters.filter(|g| !g.is_empty()) else {
return (None, None);
};
let discrete: Vec<&crate::GpuInfo> = gpus
.iter()
.filter(|g| g.static_info.integrated == Some(false))
.collect();
if discrete.is_empty() {
let all_integrated = gpus.iter().all(|g| g.static_info.integrated == Some(true));
return (all_integrated.then_some(false), None);
}
let totals: Option<Vec<u64>> = discrete
.iter()
.map(|g| g.dynamic_info.memory.total)
.collect();
let vram = totals
.and_then(|t| t.into_iter().max())
.map(|bytes| (bytes as f32 / GIB).round());
(Some(true), vram)
}
fn extract_storage_features(&mut self) {
#[cfg(target_os = "linux")]
{
let mut classified = 0usize;
let mut unclassified = false;
let mut any_nvme = std::path::Path::new("/sys/class/nvme").exists();
let mut any_ssd = any_nvme;
let mut total: Option<f32> = None;
if let Ok(entries) = std::fs::read_dir("/sys/block") {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
let is_nvme = name.starts_with("nvme");
if !(name.starts_with("sd") || is_nvme) {
let pseudo = ["loop", "ram", "zram", "sr", "dm-", "md"]
.iter()
.any(|p| name.starts_with(p));
if !pseudo {
unclassified = true;
}
continue;
}
if is_nvme {
any_nvme = true;
any_ssd = true;
classified += 1;
} else {
match std::fs::read_to_string(entry.path().join("queue/rotational"))
.ok()
.as_deref()
.map(str::trim)
{
Some("0") => {
any_ssd = true;
classified += 1;
}
Some("1") => classified += 1,
_ => unclassified = true,
}
}
if let Some(sectors) = std::fs::read_to_string(entry.path().join("size"))
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
{
total = Some(total.unwrap_or(0.0) + (sectors * 512) as f32 / 1e9);
}
}
}
self.features.has_nvme = if any_nvme {
Some(true)
} else {
(classified > 0 && !unclassified).then_some(false)
};
self.features.has_ssd = if any_ssd {
Some(true)
} else {
(classified > 0 && !unclassified).then_some(false)
};
self.features.total_storage_gb = total;
self.features.boot_drive_type = Self::linux_root_drive_type();
}
#[cfg(target_os = "windows")]
{
const BUS_TYPES: &[(&str, u64)] = &[
("scsi", 1),
("atapi", 2),
("ata", 3),
("1394", 4),
("ssa", 5),
("fibre channel", 6),
("usb", 7),
("raid", 8),
("iscsi", 9),
("sas", 10),
("sata", 11),
("sd", 12),
("mmc", 13),
("virtual", 14),
("file backed virtual", 15),
("storage spaces", 16),
("nvme", 17),
("scm", 18),
("ufs", 19),
];
let disks = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-PhysicalDisk | Select-Object MediaType,Size,BusType | ConvertTo-Json",
])
.output()
.ok()
.and_then(|o| json_items(&String::from_utf8(o.stdout).unwrap_or_default()))
.unwrap_or_default();
let kinds: Vec<(Option<u64>, Option<u64>)> = disks
.iter()
.map(|disk| {
(
wmi_enum(disk.get("MediaType"), &[("hdd", 3), ("ssd", 4)]),
wmi_enum(disk.get("BusType"), BUS_TYPES),
)
})
.collect();
let any_nvme = kinds.iter().any(|(_, bus)| *bus == Some(17));
let any_ssd = kinds
.iter()
.any(|(media, bus)| *media == Some(4) || *bus == Some(17));
self.features.has_nvme = if any_nvme {
Some(true)
} else {
(!kinds.is_empty() && kinds.iter().all(|(_, bus)| bus.is_some())).then_some(false)
};
self.features.has_ssd = if any_ssd {
Some(true)
} else {
(!kinds.is_empty() && kinds.iter().all(|(media, _)| *media == Some(3)))
.then_some(false)
};
let sizes: Option<Vec<u64>> = disks
.iter()
.map(|d| d.get("Size").and_then(|v| v.as_u64()))
.collect();
self.features.total_storage_gb = (!disks.is_empty())
.then(|| sizes.map(|s| s.iter().sum::<u64>() as f32 / 1e9))
.flatten();
self.features.boot_drive_type = Self::windows_system_drive_type(BUS_TYPES);
}
}
#[cfg(target_os = "linux")]
fn linux_root_drive_type() -> Option<String> {
let mounts = std::fs::read_to_string("/proc/mounts").ok()?;
let device = mounts.lines().find_map(|line| {
let mut fields = line.split_whitespace();
let (dev, mountpoint) = (fields.next()?, fields.next()?);
(mountpoint == "/").then_some(dev)
})?;
let name = device.strip_prefix("/dev/")?;
let base = base_disk_name(name)?;
if base.starts_with("nvme") {
return Some("NVMe".into());
}
match std::fs::read_to_string(format!("/sys/block/{base}/queue/rotational"))
.ok()?
.trim()
{
"0" => Some("SATA SSD".into()),
"1" => Some("HDD".into()),
_ => None,
}
}
#[cfg(target_os = "windows")]
fn windows_system_drive_type(bus_types: &[(&str, u64)]) -> Option<String> {
let script = concat!(
"$p = Get-Partition -DriveLetter $env:SystemDrive.Substring(0,1) -ErrorAction Stop; ",
"Get-PhysicalDisk | Where-Object { [string]$_.DeviceId -eq [string]$p.DiskNumber } ",
"| Select-Object MediaType,BusType | ConvertTo-Json"
);
let output = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", script])
.output()
.ok()?;
let text = String::from_utf8(output.stdout).ok()?;
let disk = json_items(&text)?.into_iter().next()?;
let media = wmi_enum(disk.get("MediaType"), &[("hdd", 3), ("ssd", 4)]);
let bus = wmi_enum(disk.get("BusType"), bus_types);
if bus == Some(17) {
Some("NVMe".into())
} else if media == Some(4) {
Some("SSD".into())
} else if media == Some(3) {
Some("HDD".into())
} else {
None
}
}
fn extract_platform_features(&mut self) {
#[cfg(target_os = "linux")]
{
self.features.has_battery = std::path::Path::new("/sys/class/power_supply/BAT0")
.exists()
|| std::path::Path::new("/sys/class/power_supply/BAT1").exists();
if let Ok(chassis) = std::fs::read_to_string("/sys/class/dmi/id/chassis_type") {
self.features.chassis_type = dmi_chassis_label(chassis.trim()).map(Into::into);
}
if let Ok(product) = std::fs::read_to_string("/sys/class/dmi/id/product_name") {
let lower = product.to_lowercase();
self.features.is_virtual = Some(
lower.contains("virtual")
|| lower.contains("vmware")
|| lower.contains("kvm")
|| lower.contains("qemu")
|| lower.contains("hyperv")
|| lower.contains("xen"),
);
}
if let Ok(entries) = std::fs::read_dir("/sys/devices/system/node") {
self.features.numa_nodes = Some(
entries
.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with("node"))
.count() as u32,
);
}
}
#[cfg(target_os = "windows")]
{
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_Battery).Status",
])
.output()
{
let text = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
self.features.has_battery = !text.is_empty();
}
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_ComputerSystem).Model",
])
.output()
{
let model = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_lowercase();
self.features.is_virtual =
(output.status.success() && !model.is_empty()).then(|| {
model.contains("virtual")
|| model.contains("vmware")
|| model.contains("hyper-v")
});
}
if let Ok(output) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_SystemEnclosure).ChassisTypes[0]",
])
.output()
{
let code = String::from_utf8(output.stdout)
.unwrap_or_default()
.trim()
.to_string();
let read = match code.as_str() {
"3" | "4" | "5" | "6" | "7" | "15" => Some("Desktop"),
"8" | "9" | "10" | "14" | "31" | "32" => Some("Laptop"),
"11" | "12" => Some("Handheld"),
"13" => Some("All-in-One"),
"17" | "23" | "28" => Some("Server"),
"35" | "36" => Some("Mini PC"),
_ => None,
};
self.features.chassis_type = if self.features.is_virtual == Some(true) {
Some("Virtual".into())
} else {
read.map(Into::into)
};
}
}
}
fn extract_network_features(&mut self) {
#[cfg(target_os = "linux")]
{
if let Ok(entries) = std::fs::read_dir("/sys/class/net") {
let mut physical = 0u32;
let mut fastest: Option<f32> = None;
for entry in entries.flatten() {
let path = entry.path();
if !path.join("device").exists() {
continue;
}
physical += 1;
if let Some(mbps) = std::fs::read_to_string(path.join("speed"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
{
let gbps = mbps as f32 / 1000.0;
fastest = Some(fastest.map_or(gbps, |f| f.max(gbps)));
}
}
self.features.nic_count = Some(physical);
self.features.max_nic_speed_gbps = fastest;
}
}
#[cfg(target_os = "windows")]
{
if let Some(adapters) = std::process::Command::new("powershell")
.args([
"-NoProfile",
"-Command",
"Get-NetAdapter -Physical | Select-Object LinkSpeed | ConvertTo-Json",
])
.output()
.ok()
.and_then(|o| json_items(&String::from_utf8(o.stdout).unwrap_or_default()))
{
self.features.nic_count = Some(adapters.len() as u32);
let mut fastest: Option<f32> = None;
for adapter in &adapters {
if let Some(speed) = adapter.get("LinkSpeed").and_then(|v| v.as_str()) {
let parts: Vec<&str> = speed.split_whitespace().collect();
if parts.len() >= 2 {
if let Ok(val) = parts[0].parse::<f32>() {
let gbps = match parts[1].chars().next() {
Some('G') => Some(val),
Some('M') => Some(val / 1000.0),
Some('K') => Some(val / 1_000_000.0),
Some('T') => Some(val * 1000.0),
_ => None,
};
if let Some(gbps) = gbps {
fastest = Some(fastest.map_or(gbps, |f| f.max(gbps)));
}
}
}
}
}
self.features.max_nic_speed_gbps = fastest;
}
}
}
fn classify_system(&self) -> (SystemClass, Option<f32>) {
if !anything_read(&self.features) {
return (SystemClass::Unknown, None);
}
let f = &self.features;
let mut scores: Vec<(SystemClass, f32)> = Vec::new();
if f.is_virtual == Some(true) {
scores.push((
SystemClass::VirtualMachine,
CLASSIFICATION_CONFIDENCE_VIRTUAL_MACHINE,
));
}
let server_score = {
let mut s = 0.0f32;
if f.is_server_cpu {
s += CLASSIFICATION_WEIGHT_SERVER_CPU;
}
if f.has_ecc == Some(true) {
s += CLASSIFICATION_WEIGHT_SERVER_ECC;
}
if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
s += CLASSIFICATION_WEIGHT_SERVER_PHYSICAL_CORES;
}
if f.ram_at_least(64.0) {
s += CLASSIFICATION_WEIGHT_SERVER_RAM;
}
if f.numa_nodes.is_some_and(|n| n >= 2) {
s += CLASSIFICATION_WEIGHT_SERVER_NUMA;
}
if f.chassis().contains("Server") {
s += CLASSIFICATION_WEIGHT_SERVER_CHASSIS;
}
if !f.has_battery {
s += CLASSIFICATION_WEIGHT_SERVER_NO_BATTERY;
}
if f.nic_count.is_some_and(|n| n >= 2) {
s += CLASSIFICATION_WEIGHT_SERVER_NICS;
}
s.min(CLASSIFICATION_CONFIDENCE_SERVER_CAP)
};
if server_score > 0.3 {
scores.push((SystemClass::Server, server_score));
}
let chassis_is_mobile = f.chassis().contains("Laptop") || f.chassis().contains("Handheld");
let chassis_is_stationary = f.chassis().contains("Desktop")
|| f.chassis().contains("Server")
|| f.chassis().contains("Mini PC")
|| f.chassis().contains("All-in-One");
let laptop_score = {
let mut s = 0.0f32;
if chassis_is_mobile {
s += CLASSIFICATION_WEIGHT_LAPTOP_MOBILE_CHASSIS;
}
if f.has_battery && !chassis_is_stationary {
s += CLASSIFICATION_WEIGHT_LAPTOP_BATTERY;
}
if f.cpu_cores_physical.is_some_and(|v| v <= 8) {
s += CLASSIFICATION_WEIGHT_LAPTOP_LOW_CORES;
}
if f.ram_total_gb.is_some_and(|v| v <= 32.0) {
s += CLASSIFICATION_WEIGHT_LAPTOP_LOW_RAM;
}
s.min(CLASSIFICATION_CONFIDENCE_LAPTOP_CAP)
};
if laptop_score > 0.3 {
let gpu_lower = f.gpu_model.to_lowercase();
if f.is_discrete_gpu() && (gpu_lower.contains("rtx") || gpu_lower.contains("rx ")) {
scores.push((
SystemClass::GamingLaptop,
laptop_score * CLASSIFICATION_SCALE_GAMING_LAPTOP,
));
} else if f.ram_total_gb.is_some_and(|v| v <= 16.0)
&& f.cpu_cores_physical.is_some_and(|v| v <= 4)
{
scores.push((
SystemClass::Ultrabook,
laptop_score * CLASSIFICATION_SCALE_ULTRABOOK,
));
} else {
scores.push((SystemClass::Laptop, laptop_score));
}
}
if f.is_virtual == Some(false) && !chassis_is_mobile && !f.chassis().contains("Server") {
let gpu_lower = f.gpu_model.to_lowercase();
let is_gaming_gpu = gpu_lower.contains("rtx")
|| gpu_lower.contains("gtx")
|| gpu_lower.contains("rx 6")
|| gpu_lower.contains("rx 7");
if f.is_server_cpu || f.ram_at_least(64.0) {
scores.push((
SystemClass::Workstation,
CLASSIFICATION_CONFIDENCE_WORKSTATION,
));
} else if is_gaming_gpu {
scores.push((
SystemClass::GamingDesktop,
CLASSIFICATION_CONFIDENCE_GAMING_DESKTOP,
));
} else {
scores.push((SystemClass::Desktop, CLASSIFICATION_CONFIDENCE_DESKTOP));
}
}
if f.cpu_cores_physical.is_some_and(|v| v <= 4) && f.ram_total_gb.is_some_and(|v| v <= 4.0)
{
let model = f.cpu_model.as_deref().unwrap_or("").to_lowercase();
if model.contains("arm") || model.contains("cortex") || model.contains("tegra") {
scores.push((SystemClass::Embedded, CLASSIFICATION_CONFIDENCE_EMBEDDED));
}
}
if f.chassis().contains("Mini") {
scores.push((SystemClass::MiniPc, CLASSIFICATION_CONFIDENCE_MINI_PC));
}
scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
match scores.first().cloned() {
Some((class, score)) => (class, Some(score)),
None => (SystemClass::Unknown, None),
}
}
fn compute_performance_tier(&self) -> (PerformanceTier, u8) {
let f = &self.features;
let mut score = 0u32;
score += f.cpu_cores_physical.map_or(0, |cores| match cores {
0..=1 => 10,
2 => 30,
4 => 80,
6 => 120,
8 => 160,
12 => 200,
16 => 250,
24 => 280,
32 => 300,
_ => 350, });
score += f.cpu_max_freq_mhz.map_or(0, |mhz| match mhz {
0..=1500 => 0,
1501..=2500 => 10,
2501..=3500 => 25,
3501..=4500 => 40,
_ => 50, });
score += f.ram_total_gb.map_or(0, |gb| match gb as u32 {
0..=2 => 5,
3..=4 => 20,
5..=8 => 50,
9..=16 => 80,
17..=32 => 120,
33..=64 => 160,
65..=128 => 180,
_ => 200, });
if f.is_discrete_gpu() {
score += 50; score += f.gpu_vram_gb.map_or(0, |gb| match gb as u32 {
0..=2 => 10,
3..=4 => 40,
5..=8 => 80,
9..=12 => 120,
13..=16 => 160,
17..=24 => 200,
_ => 250, });
if f.has_tensor_cores == Some(true) {
score += 30;
}
if f.has_rt_cores == Some(true) {
score += 20;
}
}
if f.has_nvme == Some(true) {
score += 60;
} else if f.has_ssd == Some(true) {
score += 30;
}
score += f.total_storage_gb.map_or(0, |gb| match gb as u32 {
0..=128 => 5,
129..=512 => 15,
513..=2048 => 25,
_ => 40,
});
score += f.max_nic_speed_gbps.map_or(0, |gbps| match gbps as u32 {
0 => 0,
1 => 15,
10 => 30,
25 => 40,
_ => 50, });
let normalized = ((score as f32 / 1000.0) * 100.0).min(100.0) as u8;
let tier = match normalized {
0..=10 => PerformanceTier::UltraLow,
11..=25 => PerformanceTier::Low,
26..=35 => PerformanceTier::MidLow,
36..=50 => PerformanceTier::Mid,
51..=65 => PerformanceTier::MidHigh,
66..=80 => PerformanceTier::High,
81..=90 => PerformanceTier::Ultra,
_ => PerformanceTier::Datacenter,
};
(tier, normalized)
}
fn detect_bottlenecks(&self) -> Vec<Bottleneck> {
let f = &self.features;
let mut bottlenecks = Vec::new();
if f.is_discrete_gpu()
&& f.cpu_cores_physical.is_some_and(|v| v <= 4)
&& f.vram_at_least(8.0)
{
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::CpuBound,
component: "CPU".into(),
severity: 70,
reason: format!(
"Only {} CPU cores paired with {}GB GPU — CPU will bottleneck GPU-intensive tasks",
f.cpu_cores_physical.unwrap_or_default(),
f.gpu_vram_gb.unwrap_or_default() as u32
),
confidence: BOTTLENECK_CONFIDENCE_CPU_GPU_IMBALANCE,
});
}
if f.is_discrete_gpu() && f.vram_at_least(8.0) && f.ram_below(16.0) {
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::MemoryBound,
component: "System RAM".into(),
severity: 60,
reason: format!(
"{:.0}GB RAM is insufficient for GPU workloads with {}GB VRAM",
f.ram_total_gb.unwrap_or_default(),
f.gpu_vram_gb.unwrap_or_default() as u32
),
confidence: BOTTLENECK_CONFIDENCE_RAM_GPU_WORKLOADS,
});
}
if f.cpu_cores_physical.is_some_and(|v| v >= 8) && f.ram_below(16.0) {
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::MemoryBound,
component: "System RAM".into(),
severity: 55,
reason: format!(
"{:.0}GB RAM for {} cores — should have at least 2GB/core",
f.ram_total_gb.unwrap_or_default(),
f.cpu_cores_physical.unwrap_or_default()
),
confidence: BOTTLENECK_CONFIDENCE_RAM_PER_CORE,
});
}
if f.has_ssd == Some(false) {
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::StorageBound,
component: "Storage".into(),
severity: 80,
reason: "No SSD detected — HDD will severely bottleneck modern workloads".into(),
confidence: BOTTLENECK_CONFIDENCE_NO_SSD,
});
}
if f.cpu_cores_physical.is_some_and(|v| v >= 16)
&& f.has_ssd == Some(true)
&& f.has_nvme == Some(false)
{
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::StorageBound,
component: "Storage bus".into(),
severity: 40,
reason: "High-core-count CPU with SATA SSD — NVMe would reduce I/O bottleneck"
.into(),
confidence: BOTTLENECK_CONFIDENCE_SATA_HIGH_CORE,
});
}
if f.is_server_cpu && f.max_nic_speed_gbps.is_some_and(|v| v < 10.0) {
bottlenecks.push(Bottleneck {
bottleneck_type: BottleneckType::NetworkBound,
component: "Network".into(),
severity: 45,
reason: format!(
"Server CPU with only {:.0} Gbps NIC — consider 10/25 GbE",
f.max_nic_speed_gbps.unwrap_or_default()
),
confidence: BOTTLENECK_CONFIDENCE_SLOW_SERVER_NIC,
});
}
bottlenecks
}
fn score_workloads(&self) -> Vec<WorkloadSuitability> {
let f = &self.features;
let mut results = Vec::new();
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.has_tensor_cores == Some(true) {
score += 30;
strengths.push("Tensor cores available".into());
}
if f.vram_at_least(24.0) {
score += 25;
strengths.push(format!(
"{:.0}GB VRAM for large models",
f.gpu_vram_gb.unwrap_or_default()
));
} else if f.vram_at_least(12.0) {
score += 15;
} else if f.vram_at_least(8.0) {
score += 8;
limiting.push("Limited VRAM for large models".into());
} else if f.vram_below(8.0) {
limiting.push("Insufficient VRAM for ML training".into());
}
if f.ram_at_least(64.0) {
score += 15;
} else if f.ram_at_least(32.0) {
score += 10;
} else if f.ram_below(32.0) {
limiting.push("RAM may limit dataset size".into());
}
if f.has_nvme == Some(true) {
score += 10;
}
if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 10;
}
if f.gpu_count > 1 {
score += 10;
strengths.push("Multi-GPU available".into());
}
results.push(WorkloadSuitability {
workload: Workload::MlTraining,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_ML_TRAINING,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.is_discrete_gpu() {
score += 30;
strengths.push("Discrete GPU".into());
}
if f.vram_at_least(8.0) {
score += 20;
}
if f.has_tensor_cores == Some(true) {
score += 15;
}
if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
score += 15;
}
if f.ram_at_least(16.0) {
score += 10;
}
if f.has_nvme == Some(true) {
score += 10;
}
if f.has_discrete_gpu == Some(false) {
limiting.push("No discrete GPU — CPU inference only".into());
}
results.push(WorkloadSuitability {
workload: Workload::MlInference,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_ML_INFERENCE,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.is_discrete_gpu() && f.vram_at_least(8.0) {
score += 35;
strengths.push(format!(
"Discrete GPU with {:.0}GB VRAM",
f.gpu_vram_gb.unwrap_or_default()
));
} else if f.is_discrete_gpu() {
score += 15;
} else if f.has_discrete_gpu == Some(false) {
limiting.push("No discrete GPU".into());
}
if f.has_rt_cores == Some(true) {
score += 10;
strengths.push("Ray tracing support".into());
}
if f.cpu_max_freq_mhz.is_some_and(|v| v >= 4000) {
score += 15;
strengths.push("High CPU clock speed".into());
} else if f.cpu_max_freq_mhz.is_some_and(|v| v >= 3000) {
score += 10;
}
if f.ram_at_least(16.0) {
score += 10;
} else if f.ram_below(16.0) {
limiting.push("< 16GB RAM".into());
}
if f.has_nvme == Some(true) {
score += 10;
}
if f.cpu_cores_physical.is_some_and(|v| v >= 6) {
score += 10;
}
if f.has_ssd == Some(true) {
score += 10;
}
results.push(WorkloadSuitability {
workload: Workload::Gaming,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_GAMING,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.is_discrete_gpu() {
score += 20;
}
if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 20;
strengths.push("Multi-core for rendering".into());
} else if f.cpu_cores_physical.is_some_and(|v| v >= 6) {
score += 15;
}
if f.ram_at_least(32.0) {
score += 20;
strengths.push("Plenty of RAM for timelines".into());
} else if f.ram_at_least(16.0) {
score += 10;
} else if f.ram_below(16.0) {
limiting.push("< 16GB RAM limits timeline length".into());
}
if f.has_nvme == Some(true) {
score += 15;
strengths.push("NVMe for fast media reads".into());
}
if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
score += 10;
} else if f.total_storage_gb.is_some_and(|v| v < 2000.0) {
limiting.push("Limited storage for large projects".into());
}
if f.vram_at_least(8.0) {
score += 15;
}
results.push(WorkloadSuitability {
workload: Workload::VideoEditing,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_VIDEO_EDITING,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
score += 35;
strengths.push("Many cores for parallel builds".into());
} else if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 25;
} else if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
score += 15;
} else {
limiting.push("Few cores — slow parallel builds".into());
}
if f.ram_at_least(32.0) {
score += 25;
} else if f.ram_at_least(16.0) {
score += 15;
}
if f.has_nvme == Some(true) {
score += 20;
strengths.push("Fast build I/O with NVMe".into());
} else if f.has_ssd == Some(true) {
score += 10;
}
if f.cpu_max_freq_mhz.is_some_and(|v| v >= 4000) {
score += 10;
}
if f.total_storage_gb.is_some_and(|v| v >= 512.0) {
score += 10;
}
results.push(WorkloadSuitability {
workload: Workload::Compilation,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_COMPILATION,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 25;
} else if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
score += 15;
}
if f.ram_at_least(16.0) {
score += 20;
}
if f.max_nic_speed_gbps.is_some_and(|v| v >= 10.0) {
score += 25;
strengths.push("10+ GbE networking".into());
} else if f.max_nic_speed_gbps.is_some_and(|v| v >= 1.0) {
score += 10;
} else if f.max_nic_speed_gbps.is_some_and(|v| v < 1.0) {
limiting.push("Slow network".into());
}
if f.has_nvme == Some(true) {
score += 15;
}
if f.nic_count.is_some_and(|n| n >= 2) {
score += 10;
strengths.push("Multiple NICs for redundancy".into());
}
if f.is_server_cpu {
score += 5;
}
results.push(WorkloadSuitability {
workload: Workload::WebServer,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_WEB_SERVER,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.ram_at_least(64.0) {
score += 30;
strengths.push("Large RAM for caching".into());
} else if f.ram_at_least(32.0) {
score += 20;
} else if f.ram_below(32.0) {
limiting.push("RAM limits index caching".into());
}
if f.has_nvme == Some(true) {
score += 25;
strengths.push("NVMe for fast IOPS".into());
} else if f.has_ssd == Some(true) {
score += 15;
} else if f.has_ssd == Some(false) {
limiting.push("HDD severely limits database IOPS".into());
}
if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 20;
}
if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
score += 15;
}
if f.has_ecc == Some(true) {
score += 10;
strengths.push("ECC memory for data integrity".into());
}
results.push(WorkloadSuitability {
workload: Workload::DatabaseServer,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_DATABASE_SERVER,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 0u8;
let mut strengths = Vec::new();
let mut limiting = Vec::new();
if f.cpu_cores_physical.is_some_and(|v| v >= 16) {
score += 30;
strengths.push("Many cores for VMs".into());
} else if f.cpu_cores_physical.is_some_and(|v| v >= 8) {
score += 15;
} else {
limiting.push("Few cores limits VM density".into());
}
if f.ram_at_least(128.0) {
score += 30;
} else if f.ram_at_least(64.0) {
score += 20;
strengths.push("Good RAM for VMs".into());
} else if f.ram_at_least(32.0) {
score += 10;
} else if f.ram_below(32.0) {
limiting.push("Limited RAM for virtual machines".into());
}
if f.has_nvme == Some(true) {
score += 15;
}
if f.numa_nodes.is_some_and(|n| n >= 2) {
score += 10;
strengths.push("NUMA for VM pinning".into());
}
if f.is_server_cpu {
score += 10;
}
if f.total_storage_gb.is_some_and(|v| v >= 2000.0) {
score += 5;
}
results.push(WorkloadSuitability {
workload: Workload::Virtualization,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_VIRTUALIZATION,
limiting_factors: limiting,
strengths,
});
}
{
let mut score = 50u8; let strengths = Vec::new();
let mut limiting = Vec::new();
if f.cpu_cores_physical.is_some_and(|v| v >= 4) {
score += 15;
}
if f.ram_at_least(8.0) {
score += 15;
} else if f.ram_below(8.0) {
limiting.push("< 8GB RAM may cause slowdowns".into());
}
if f.has_ssd == Some(true) {
score += 15;
} else if f.has_ssd == Some(false) {
limiting.push("HDD makes boot and app launch slow".into());
}
if f.cpu_cores_physical.is_some_and(|v| v < 2) || f.ram_below(4.0) {
score = score.saturating_sub(30);
}
results.push(WorkloadSuitability {
workload: Workload::OfficeProductivity,
score: score.min(100),
confidence: WORKLOAD_CONFIDENCE_OFFICE_PRODUCTIVITY,
limiting_factors: limiting,
strengths,
});
}
results.sort_by_key(|p| std::cmp::Reverse(p.score));
results
}
fn estimate_hardware_age(&self) -> HardwareAge {
let f = &self.features;
let cpu_lower = f.cpu_model.as_deref().unwrap_or("").to_lowercase();
let gpu_lower = f.gpu_model.to_lowercase();
let cpu_year = Self::infer_cpu_year(&cpu_lower);
let gpu_year = Self::infer_gpu_year(&gpu_lower);
let current = Self::current_year();
let years = match (cpu_year, gpu_year) {
(Some(cy), Some(gy)) => {
let avg = (cy + gy) as f32 / 2.0;
Some((current - avg).max(0.0))
}
(Some(cy), None) => Some((current - cy as f32).max(0.0)),
(None, Some(gy)) => Some((current - gy as f32).max(0.0)),
(None, None) => None,
};
let confidence = match (cpu_year, gpu_year) {
(Some(_), Some(_)) => Some(AGE_CONFIDENCE_CPU_AND_GPU),
(Some(_), None) | (None, Some(_)) => Some(AGE_CONFIDENCE_CPU_OR_GPU),
(None, None) => None,
};
let reasoning = format!(
"CPU: {} (est. {}), GPU: {} (est. {})",
f.cpu_model.as_deref().unwrap_or("unknown"),
cpu_year.map_or("unknown".to_string(), |y| y.to_string()),
f.gpu_model,
gpu_year.map_or("unknown".to_string(), |y| y.to_string()),
);
HardwareAge {
cpu_year,
gpu_year,
estimated_age_years: years,
confidence,
reasoning,
}
}
fn infer_cpu_year(model: &str) -> Option<u16> {
let is_amd = model.contains("amd")
|| model.contains("ryzen")
|| model.contains("epyc")
|| model.contains("threadripper");
if !is_amd {
if model.contains("14th gen")
|| model.contains("core ultra")
|| model.contains("14900")
|| model.contains("14700")
{
return Some(2024);
}
if model.contains("13th gen")
|| model.contains("13900")
|| model.contains("13700")
|| model.contains("13600")
{
return Some(2022);
}
if model.contains("12th gen")
|| model.contains("12900")
|| model.contains("12700")
|| model.contains("12600")
{
return Some(2021);
}
if model.contains("11th gen") || model.contains("11900") || model.contains("11700") {
return Some(2021);
}
if model.contains("10th gen") || model.contains("10900") || model.contains("10700") {
return Some(2020);
}
if model.contains("9th gen") || model.contains("9900") || model.contains("9700") {
return Some(2018);
}
if model.contains("8th gen") || model.contains("8700") {
return Some(2017);
}
}
if model.contains("ryzen 9 9") || model.contains("ryzen 7 9") || model.contains("zen 5") {
return Some(2024);
}
if model.contains("ryzen 9 7")
|| model.contains("ryzen 7 7")
|| model.contains("ryzen 5 7")
|| model.contains("zen 4")
{
return Some(2022);
}
if model.contains("ryzen 9 5")
|| model.contains("ryzen 7 5")
|| model.contains("ryzen 5 5")
|| model.contains("zen 3")
{
return Some(2020);
}
if model.contains("ryzen 9 3")
|| model.contains("ryzen 7 3")
|| model.contains("ryzen 5 3")
|| model.contains("zen 2")
{
return Some(2019);
}
if model.contains("epyc 9") {
return Some(2023);
}
if model.contains("epyc 7") && model.contains("3") {
return Some(2022);
}
if model.contains("epyc 7") {
return Some(2019);
}
if model.contains("xeon w9") || model.contains("xeon w7") {
return Some(2023);
}
if model.contains("xeon") && model.contains("v5") {
return Some(2017);
}
if model.contains("xeon") && model.contains("v4") {
return Some(2016);
}
if model.contains("m4") {
return Some(2024);
}
if model.contains("m3") {
return Some(2023);
}
if model.contains("m2") {
return Some(2022);
}
if model.contains("m1") {
return Some(2020);
}
None
}
fn current_year() -> f32 {
const SECONDS_PER_YEAR: f32 = 365.2425 * 24.0 * 60.0 * 60.0;
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f32())
.unwrap_or(0.0);
1970.0 + secs / SECONDS_PER_YEAR
}
fn infer_gpu_year(model: &str) -> Option<u16> {
if model.contains("rtx 50") || model.contains("5090") || model.contains("5080") {
return Some(2025);
}
if model.contains("rtx 40") || model.contains("4090") || model.contains("4080") {
return Some(2022);
}
if model.contains("3090 ti") {
return Some(2022);
}
if model.contains("3080 ti") || model.contains("3070 ti") {
return Some(2021);
}
if model.contains("rtx 30") || model.contains("3090") || model.contains("3080") {
return Some(2020);
}
if model.contains("rtx 20") || model.contains("2080") || model.contains("2070") {
return Some(2018);
}
if model.contains("gtx 1080") || model.contains("gtx 10") {
return Some(2016);
}
if model.contains("gtx 9") {
return Some(2014);
}
if model.contains("h100") || model.contains("h200") {
return Some(2023);
}
if model.contains("a100") {
return Some(2020);
}
if model.contains("v100") {
return Some(2017);
}
if model.contains("rx 9") {
return Some(2025);
}
if model.contains("rx 7") {
return Some(2022);
}
if model.contains("rx 6") {
return Some(2020);
}
if model.contains("rx 5") {
return Some(2019);
}
if model.contains("arc b") {
return Some(2024);
}
if model.contains("arc a") {
return Some(2022);
}
if model.contains("m4") {
return Some(2024);
}
if model.contains("m3") {
return Some(2023);
}
if model.contains("m2") {
return Some(2022);
}
if model.contains("m1") {
return Some(2020);
}
None
}
fn analyze_thermal_envelope(&self) -> ThermalEnvelope {
let f = &self.features;
let cpu_tdp = f.cpu_tdp_watts;
let gpu_tdp = f.gpu_tdp_watts;
let total_tdp = match (cpu_tdp, gpu_tdp) {
(Some(c), Some(g)) => Some(c + g + 30.0),
_ => None,
};
let is_mobile_chassis = f.chassis().contains("Laptop") || f.chassis().contains("Handheld");
let headroom = if is_mobile_chassis {
match total_tdp {
None => ThermalHeadroom::Unknown,
Some(t) if t > 150.0 => ThermalHeadroom::Insufficient,
Some(t) if t > 100.0 => ThermalHeadroom::Marginal,
Some(t) if t > 60.0 => ThermalHeadroom::Adequate,
Some(_) => ThermalHeadroom::Ample,
}
} else if f.chassis().contains("Mini") {
match total_tdp {
Some(t) if t > 120.0 => ThermalHeadroom::Marginal,
Some(_) => ThermalHeadroom::Adequate,
None => ThermalHeadroom::Unknown,
}
} else {
ThermalHeadroom::Unknown
};
let cooling_score = match &headroom {
ThermalHeadroom::Ample => Some(90),
ThermalHeadroom::Adequate => Some(70),
ThermalHeadroom::Marginal => Some(40),
ThermalHeadroom::Insufficient => Some(15),
ThermalHeadroom::Unknown => None,
};
let mut recommendations = Vec::new();
if headroom == ThermalHeadroom::Insufficient || headroom == ThermalHeadroom::Marginal {
recommendations.push(
"Consider improving cooling (better fans, repasting, or external cooling)".into(),
);
}
if is_mobile_chassis && gpu_tdp.is_some_and(|g| g > 80.0) {
recommendations.push(
"High GPU TDP in a laptop — may experience thermal throttling under sustained load"
.into(),
);
}
ThermalEnvelope {
estimated_total_tdp_watts: total_tdp,
cpu_tdp_watts: cpu_tdp,
cpu_tdp_measured: f.cpu_tdp_measured,
gpu_tdp_watts: gpu_tdp,
gpu_adapters_counted: f.gpu_adapters_counted,
gpu_tdp_measured: f.gpu_tdp_measured,
headroom,
cooling_score,
recommendations,
}
}
fn measured_cpu_power_cap_watts() -> Option<f32> {
use crate::rapl::PowerDomain;
let monitor = crate::rapl::RaplMonitor::new().ok()?;
let watts: f64 = monitor
.readings()
.iter()
.filter(|r| r.domain == PowerDomain::Package)
.filter_map(|r| r.power_limit_uw)
.map(|uw| uw as f64 / 1_000_000.0)
.sum();
(watts > 0.0).then_some(watts as f32)
}
fn infer_cpu_tdp(model_lower: &str) -> Option<f32> {
if model_lower.contains("i9-14") || model_lower.contains("i9-13") {
return Some(125.0);
}
if model_lower.contains("i7-14") || model_lower.contains("i7-13") {
return Some(65.0);
}
if model_lower.contains("i5-14") || model_lower.contains("i5-13") {
return Some(65.0);
}
if model_lower.contains("i3") {
return Some(35.0);
}
if model_lower.contains("ryzen 9") {
return Some(120.0);
}
if model_lower.contains("ryzen 7") {
return Some(65.0);
}
if model_lower.contains("ryzen 5") {
return Some(65.0);
}
if model_lower.contains("ryzen 3") {
return Some(35.0);
}
if model_lower.contains("epyc") {
return Some(225.0);
}
if model_lower.contains("xeon") {
return Some(150.0);
}
if model_lower.contains("threadripper") {
return Some(280.0);
}
if model_lower.contains("celeron") || model_lower.contains("atom") {
return Some(15.0);
}
if model_lower.contains("m1") || model_lower.contains("m2") {
return Some(20.0);
}
if model_lower.contains("m3") || model_lower.contains("m4") {
return Some(22.0);
}
if model_lower.contains("arm") || model_lower.contains("cortex") {
return Some(5.0);
}
None
}
fn measured_gpu_power_caps_watts(gpus: &[crate::GpuInfo]) -> Option<(f32, u32)> {
let caps: Vec<f32> = gpus
.iter()
.filter_map(|g| g.dynamic_info.power.limit)
.map(|mw| mw as f32 / 1000.0)
.collect();
(!caps.is_empty()).then(|| (caps.iter().sum(), caps.len() as u32))
}
fn infer_gpu_tdp(model_lower: &str) -> Option<f32> {
if model_lower.contains("4090") {
return Some(450.0);
}
if model_lower.contains("4080") {
return Some(320.0);
}
if model_lower.contains("4070 ti") {
return Some(285.0);
}
if model_lower.contains("4070") {
return Some(200.0);
}
if model_lower.contains("4060") {
return Some(115.0);
}
if model_lower.contains("3090") {
return Some(350.0);
}
if model_lower.contains("3080") {
return Some(320.0);
}
if model_lower.contains("3070") {
return Some(220.0);
}
if model_lower.contains("3060") {
return Some(170.0);
}
if model_lower.contains("h100") {
return Some(700.0);
}
if model_lower.contains("a100") {
return Some(300.0);
}
if model_lower.contains("rx 7900") {
return Some(355.0);
}
if model_lower.contains("rx 7800") {
return Some(263.0);
}
if model_lower.contains("rx 7700") {
return Some(245.0);
}
if model_lower.contains("rx 7600") {
return Some(165.0);
}
if model_lower.contains("arc a7") {
return Some(225.0);
}
if model_lower.contains("arc a5") {
return Some(175.0);
}
None
}
fn suggest_upgrades(&self, bottlenecks: &[Bottleneck]) -> Vec<UpgradeRecommendation> {
let f = &self.features;
let mut recs = Vec::new();
if f.ram_below(8.0) {
recs.push(UpgradeRecommendation {
component: "RAM".into(),
current: format!("{:.0}GB", f.ram_total_gb.unwrap_or_default()),
recommended: "16GB+".into(),
description: "Upgrade to at least 16GB RAM".into(),
expected_impact: "40-60% reduction in memory-related slowdowns".into(),
priority: 9,
cost_tier: 2,
});
} else if f.ram_below(16.0) && f.is_discrete_gpu() {
recs.push(UpgradeRecommendation {
component: "RAM".into(),
current: format!("{:.0}GB", f.ram_total_gb.unwrap_or_default()),
recommended: "32GB".into(),
description: "Upgrade RAM for GPU workloads".into(),
expected_impact: "20-30% better multitasking and GPU workflow performance".into(),
priority: 7,
cost_tier: 2,
});
}
if f.has_ssd == Some(false) {
recs.push(UpgradeRecommendation {
component: "Boot Drive".into(),
current: "HDD".into(),
recommended: "NVMe SSD".into(),
description: "Replace HDD with NVMe SSD for dramatic speed improvement".into(),
expected_impact: "5-10x faster boot, app launch, and file operations".into(),
priority: 10,
cost_tier: 2,
});
} else if f.has_ssd == Some(true)
&& f.has_nvme == Some(false)
&& f.cpu_cores_physical.is_some_and(|v| v >= 8)
{
recs.push(UpgradeRecommendation {
component: "Boot Drive".into(),
current: "SATA SSD".into(),
recommended: "NVMe Gen4 SSD".into(),
description: "Upgrade to NVMe for faster I/O".into(),
expected_impact: "3-5x faster sequential reads, lower I/O latency".into(),
priority: 5,
cost_tier: 2,
});
}
for bn in bottlenecks {
match bn.bottleneck_type {
BottleneckType::GpuBound if bn.severity > 50 => {
recs.push(UpgradeRecommendation {
component: "GPU".into(),
current: f.gpu_model.clone(),
recommended: "Next-tier GPU".into(),
description: "GPU is the primary bottleneck".into(),
expected_impact: "30-100% improvement in GPU-bound workloads".into(),
priority: 8,
cost_tier: 4,
});
}
BottleneckType::CpuBound if bn.severity > 50 => {
recs.push(UpgradeRecommendation {
component: "CPU".into(),
current: f.cpu_model.clone().unwrap_or_else(|| "unknown".into()),
recommended: "Higher core-count CPU".into(),
description: "CPU bottlenecks the system".into(),
expected_impact: "20-50% improvement in CPU-bound workloads".into(),
priority: 7,
cost_tier: 4,
});
}
BottleneckType::NetworkBound if bn.severity > 40 => {
recs.push(UpgradeRecommendation {
component: "Network".into(),
current: format!(
"{:.0} Gbps NIC",
f.max_nic_speed_gbps.unwrap_or_default()
),
recommended: "10 GbE NIC".into(),
description: "Network is a bottleneck for server workloads".into(),
expected_impact: "10x network throughput".into(),
priority: 6,
cost_tier: 3,
});
}
_ => {}
}
}
recs.sort_by_key(|p| std::cmp::Reverse(p.priority));
recs
}
fn detect_anomalies(&self) -> Vec<HardwareAnomaly> {
let f = &self.features;
let mut anomalies = Vec::new();
if f.vram_at_least(16.0) && f.ram_below(16.0) {
anomalies.push(HardwareAnomaly {
description: format!(
"GPU has {:.0}GB VRAM but system only has {:.0}GB RAM",
f.gpu_vram_gb.unwrap_or_default(),
f.ram_total_gb.unwrap_or_default()
),
severity: AnomalySeverity::Warning,
explanation:
"GPU VRAM exceeds system RAM — data loading will bottleneck GPU workloads"
.into(),
});
}
if f.is_server_cpu && (f.chassis().contains("Laptop") || f.chassis().contains("Handheld")) {
anomalies.push(HardwareAnomaly {
description: "Server-class CPU detected in a battery-powered system".into(),
severity: AnomalySeverity::Info,
explanation: "This is unusual but may be a mobile workstation".into(),
});
}
if let (Some(vram), Some(ram)) = (f.gpu_vram_gb, f.ram_total_gb) {
if vram > ram && vram > 0.0 {
anomalies.push(HardwareAnomaly {
description: format!(
"GPU VRAM ({:.0}GB) exceeds system RAM ({:.0}GB)",
vram, ram
),
severity: AnomalySeverity::Warning,
explanation:
"System RAM should typically be at least 2x GPU VRAM for optimal performance"
.into(),
});
}
}
if f.cpu_cores_physical.is_some_and(|v| v >= 32)
&& f.cpu_max_freq_mhz.is_some_and(|v| v < 2500)
{
anomalies.push(HardwareAnomaly {
description: format!(
"{} cores at only {} MHz",
f.cpu_cores_physical.unwrap_or_default(),
f.cpu_max_freq_mhz.unwrap_or_default()
),
severity: AnomalySeverity::Info,
explanation: "Many-core + low clock = throughput-optimized (server/HPC), not latency-sensitive".into(),
});
}
if f.has_discrete_gpu == Some(false)
&& f.ram_at_least(64.0)
&& f.cpu_cores_physical.is_some_and(|v| v >= 16)
{
anomalies.push(HardwareAnomaly {
description: "Powerful CPU and RAM but no discrete GPU".into(),
severity: AnomalySeverity::Info,
explanation: "System may be optimized for CPU-bound workloads or virtualization"
.into(),
});
}
if f.total_storage_gb.is_some_and(|v| v >= 10000.0)
&& f.max_nic_speed_gbps.is_some_and(|v| v < 10.0)
{
anomalies.push(HardwareAnomaly {
description: format!(
"{:.0}TB storage with only {:.0} Gbps network",
f.total_storage_gb.unwrap_or_default() / 1000.0,
f.max_nic_speed_gbps.unwrap_or_default()
),
severity: AnomalySeverity::Warning,
explanation: "Large storage with slow network — data transfers will be slow".into(),
});
}
anomalies
}
fn compute_fingerprint(&self) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
self.features.cpu_model.hash(&mut hasher);
self.features.cpu_cores_physical.hash(&mut hasher);
self.features.cpu_cores_logical.hash(&mut hasher);
self.features
.ram_total_gb
.map(|v| v as u64)
.hash(&mut hasher);
self.features.gpu_model.hash(&mut hasher);
self.features
.gpu_vram_gb
.map(|v| v as u64)
.hash(&mut hasher);
self.features.has_nvme.hash(&mut hasher);
self.features
.total_storage_gb
.map(|v| v as u64)
.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
}
impl Default for HardwareInferenceEngine {
fn default() -> Self {
Self::new().unwrap_or(Self {
features: HardwareFeatures::default(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_engine_creation() {
let engine = HardwareInferenceEngine::new();
assert!(engine.is_ok());
}
#[test]
fn test_engine_default() {
let engine = HardwareInferenceEngine::default();
let report = engine.full_analysis();
let _ = &report.classification;
let _ = &report.performance_tier;
}
#[test]
fn a_machine_nothing_was_read_from_is_unknown_with_no_confidence() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures::default(),
};
let (class, confidence) = engine.classify_system();
assert_eq!(class, SystemClass::Unknown);
assert_eq!(confidence, None);
let report = engine.full_analysis();
assert_eq!(report.classification, SystemClass::Unknown);
assert_eq!(report.classification_confidence, None);
assert_eq!(report.performance_score, None);
assert_eq!(report.performance_tier, None);
let one_reading = HardwareInferenceEngine {
features: HardwareFeatures {
ram_total_gb: Some(32.0),
..HardwareFeatures::default()
},
};
let (class, confidence) = one_reading.classify_system();
assert_eq!(class, SystemClass::Unknown);
assert_eq!(confidence, None);
let read_physical = HardwareInferenceEngine {
features: HardwareFeatures {
ram_total_gb: Some(32.0),
is_virtual: Some(false),
..HardwareFeatures::default()
},
};
let (class, confidence) = read_physical.classify_system();
assert_eq!(class, SystemClass::Desktop);
assert_eq!(confidence, Some(CLASSIFICATION_CONFIDENCE_DESKTOP));
}
#[test]
fn test_full_analysis_report() {
let engine = HardwareInferenceEngine::new().unwrap();
let report = engine.full_analysis();
assert!(!report.hardware_fingerprint.is_empty());
assert!(!report.workload_scores.is_empty());
}
#[test]
fn test_gaming_desktop_classification() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures {
cpu_cores_physical: Some(8),
cpu_cores_logical: Some(16),
cpu_max_freq_mhz: Some(5000),
cpu_model: Some("Intel Core i7-14700K".into()),
cpu_vendor: Some("Intel".into()),
is_server_cpu: false,
has_ecc: Some(false),
cpu_tdp_watts: Some(125.0),
cpu_tdp_measured: false,
ram_total_gb: Some(32.0),
ram_channels: 2,
ram_speed_mhz: 3600,
has_discrete_gpu: Some(true),
gpu_count: 1,
gpu_model: "NVIDIA GeForce RTX 4070 Ti".into(),
gpu_vram_gb: Some(12.0),
has_tensor_cores: Some(true),
has_rt_cores: Some(true),
gpu_tdp_watts: Some(285.0),
gpu_tdp_measured: false,
gpu_adapters_counted: 1,
has_nvme: Some(true),
has_ssd: Some(true),
total_storage_gb: Some(2000.0),
boot_drive_type: Some("NVMe".into()),
has_battery: false,
chassis_type: Some("Desktop".into()),
is_virtual: Some(false),
numa_nodes: Some(1),
pcie_gen: 4,
max_nic_speed_gbps: Some(2.5),
nic_count: Some(1),
},
};
let report = engine.full_analysis();
assert!(
report.classification == SystemClass::GamingDesktop
|| report.classification == SystemClass::Desktop
|| report.classification == SystemClass::Workstation
);
assert!(report.performance_tier >= Some(PerformanceTier::MidHigh));
assert!(report.performance_score.is_some_and(|s| s >= 50));
}
#[test]
fn test_server_classification() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures {
cpu_cores_physical: Some(64),
cpu_cores_logical: Some(128),
cpu_max_freq_mhz: Some(2800),
cpu_model: Some("AMD EPYC 9554".into()),
cpu_vendor: Some("AMD".into()),
is_server_cpu: true,
has_ecc: Some(true),
cpu_tdp_watts: Some(225.0),
cpu_tdp_measured: false,
ram_total_gb: Some(512.0),
ram_channels: 8,
ram_speed_mhz: 4800,
has_discrete_gpu: Some(false),
gpu_count: 0,
gpu_model: String::new(),
gpu_vram_gb: None,
has_tensor_cores: Some(false),
has_rt_cores: Some(false),
gpu_tdp_watts: None,
gpu_tdp_measured: false,
gpu_adapters_counted: 1,
has_nvme: Some(true),
has_ssd: Some(true),
total_storage_gb: Some(15000.0),
boot_drive_type: Some("NVMe".into()),
has_battery: false,
chassis_type: Some("Server".into()),
is_virtual: Some(false),
numa_nodes: Some(2),
pcie_gen: 5,
max_nic_speed_gbps: Some(25.0),
nic_count: Some(4),
},
};
let report = engine.full_analysis();
assert_eq!(report.classification, SystemClass::Server);
assert!(report.performance_tier >= Some(PerformanceTier::High));
let virt = report
.workload_scores
.iter()
.find(|w| w.workload == Workload::Virtualization)
.unwrap();
assert!(virt.score >= 70);
}
#[test]
fn test_laptop_bottleneck() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures {
cpu_cores_physical: Some(4),
cpu_cores_logical: Some(8),
cpu_max_freq_mhz: Some(2800),
cpu_model: Some("Intel Core i5".into()),
cpu_vendor: Some("Intel".into()),
is_server_cpu: false,
has_ecc: Some(false),
cpu_tdp_watts: Some(15.0),
cpu_tdp_measured: false,
ram_total_gb: Some(8.0),
ram_channels: 2,
ram_speed_mhz: 3200,
has_discrete_gpu: Some(true),
gpu_count: 1,
gpu_model: "NVIDIA GeForce RTX 4070 Laptop".into(),
gpu_vram_gb: Some(8.0),
has_tensor_cores: Some(true),
has_rt_cores: Some(true),
gpu_tdp_watts: Some(100.0),
gpu_tdp_measured: false,
gpu_adapters_counted: 1,
has_nvme: Some(true),
has_ssd: Some(true),
total_storage_gb: Some(512.0),
boot_drive_type: Some("NVMe".into()),
has_battery: true,
chassis_type: Some("Laptop".into()),
is_virtual: Some(false),
numa_nodes: Some(1),
pcie_gen: 4,
max_nic_speed_gbps: Some(1.0),
nic_count: Some(1),
},
};
let report = engine.full_analysis();
assert!(!report.bottlenecks.is_empty());
assert!(!report.anomalies.is_empty() || !report.bottlenecks.is_empty());
}
#[test]
fn test_cpu_year_inference() {
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("intel core i9-14900k"),
Some(2024)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("amd ryzen 7 7800x3d"),
Some(2022)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("apple m3 max"),
Some(2023)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("amd epyc 9554"),
Some(2023)
);
}
#[test]
fn a_model_number_is_read_for_the_right_vendor() {
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("amd ryzen 9 9900x 12-core processor"),
Some(2024)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("amd ryzen 9 9950x3d"),
Some(2024)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("intel core i9-9900k"),
Some(2018)
);
assert_eq!(
HardwareInferenceEngine::infer_cpu_year("amd ryzen 7 7700x"),
Some(2022)
);
}
#[test]
fn the_current_year_comes_from_the_clock_not_from_the_source() {
let year = HardwareInferenceEngine::current_year();
assert!(
year > 2024.0 && year < 2100.0,
"current_year() returned {year}, which is not a plausible year from a \
working clock"
);
let from_the_clock = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("the clock is after 1970")
.as_secs_f32()
/ (365.2425 * 24.0 * 60.0 * 60.0)
+ 1970.0;
assert!(
(year - from_the_clock).abs() < 0.01,
"current_year() {year} does not match the clock {from_the_clock}"
);
}
#[test]
fn a_ti_refresh_is_not_dated_from_its_series() {
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3090 ti"),
Some(2022)
);
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3080 ti"),
Some(2021)
);
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 3090"),
Some(2020)
);
}
#[test]
fn test_gpu_year_inference() {
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("nvidia geforce rtx 4090"),
Some(2022)
);
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("amd radeon rx 7900 xtx"),
Some(2022)
);
assert_eq!(
HardwareInferenceEngine::infer_gpu_year("nvidia h100"),
Some(2023)
);
}
#[test]
fn test_performance_tier_scoring() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures {
cpu_cores_physical: Some(2),
cpu_cores_logical: Some(4),
cpu_max_freq_mhz: Some(1800),
ram_total_gb: Some(4.0),
has_discrete_gpu: Some(false),
has_ssd: Some(false),
has_nvme: Some(false),
total_storage_gb: Some(500.0),
..HardwareFeatures::default()
},
};
let (tier, _score) = engine.compute_performance_tier();
assert!(tier <= PerformanceTier::MidLow);
}
#[test]
fn test_workload_suitability() {
let engine = HardwareInferenceEngine {
features: HardwareFeatures {
cpu_cores_physical: Some(16),
cpu_cores_logical: Some(32),
cpu_max_freq_mhz: Some(4500),
ram_total_gb: Some(128.0),
has_discrete_gpu: Some(true),
gpu_vram_gb: Some(24.0),
has_tensor_cores: Some(true),
has_nvme: Some(true),
has_ssd: Some(true),
total_storage_gb: Some(4000.0),
..HardwareFeatures::default()
},
};
let workloads = engine.score_workloads();
let ml = workloads
.iter()
.find(|w| w.workload == Workload::MlTraining)
.unwrap();
assert!(ml.score >= 60); }
fn engine_with(features: HardwareFeatures) -> HardwareInferenceEngine {
HardwareInferenceEngine { features }
}
fn workload(engine: &HardwareInferenceEngine, kind: Workload) -> WorkloadSuitability {
engine
.score_workloads()
.into_iter()
.find(|w| w.workload == kind)
.unwrap()
}
#[test]
fn unread_storage_emits_no_storage_advice() {
let unread = engine_with(HardwareFeatures {
cpu_cores_physical: Some(16),
..HardwareFeatures::default()
});
assert!(!unread
.detect_bottlenecks()
.iter()
.any(|b| matches!(b.bottleneck_type, BottleneckType::StorageBound)));
assert!(!unread
.suggest_upgrades(&[])
.iter()
.any(|u| u.component == "Boot Drive"));
assert!(!workload(&unread, Workload::DatabaseServer)
.limiting_factors
.iter()
.any(|s| s.contains("HDD")));
let hdd = engine_with(HardwareFeatures {
cpu_cores_physical: Some(16),
has_ssd: Some(false),
has_nvme: Some(false),
..HardwareFeatures::default()
});
assert!(hdd
.detect_bottlenecks()
.iter()
.any(|b| matches!(b.bottleneck_type, BottleneckType::StorageBound)));
assert!(hdd
.suggest_upgrades(&[])
.iter()
.any(|u| u.component == "Boot Drive"));
}
#[test]
fn unread_vram_emits_no_vram_advice() {
let engine = engine_with(HardwareFeatures {
cpu_cores_physical: Some(8),
ram_total_gb: Some(8.0),
has_discrete_gpu: Some(true),
gpu_vram_gb: None,
..HardwareFeatures::default()
});
assert!(!engine
.detect_bottlenecks()
.iter()
.any(|b| b.reason.contains("GPU workloads")));
assert!(!engine
.detect_anomalies()
.iter()
.any(|a| a.description.contains("VRAM")));
assert!(!workload(&engine, Workload::MlTraining)
.limiting_factors
.iter()
.any(|s| s.contains("VRAM")));
}
#[test]
fn unread_ram_emits_no_ram_advice() {
let engine = engine_with(HardwareFeatures {
cpu_cores_physical: Some(16),
has_discrete_gpu: Some(true),
gpu_vram_gb: Some(24.0),
..HardwareFeatures::default()
});
assert!(!engine
.suggest_upgrades(&[])
.iter()
.any(|u| u.component == "RAM"));
assert!(!engine
.detect_anomalies()
.iter()
.any(|a| a.description.contains("RAM")));
assert!(!engine
.detect_bottlenecks()
.iter()
.any(|b| b.component == "System RAM"));
assert!(!workload(&engine, Workload::MlTraining)
.limiting_factors
.iter()
.any(|s| s.contains("RAM")));
}
#[test]
fn unread_gpu_presence_emits_no_gpu_absence_advice() {
let engine = engine_with(HardwareFeatures {
cpu_cores_physical: Some(16),
ram_total_gb: Some(64.0),
has_discrete_gpu: None,
..HardwareFeatures::default()
});
assert!(!engine
.detect_anomalies()
.iter()
.any(|a| a.description.contains("no discrete GPU")));
for kind in [Workload::MlInference, Workload::Gaming] {
assert!(!workload(&engine, kind)
.limiting_factors
.iter()
.any(|s| s.contains("No discrete GPU")));
}
}
#[test]
fn unread_network_emits_no_network_advice() {
let engine = engine_with(HardwareFeatures {
cpu_cores_physical: Some(64),
is_server_cpu: true,
ram_total_gb: Some(512.0),
total_storage_gb: Some(15000.0),
max_nic_speed_gbps: None,
nic_count: None,
..HardwareFeatures::default()
});
assert!(!engine
.detect_bottlenecks()
.iter()
.any(|b| matches!(b.bottleneck_type, BottleneckType::NetworkBound)));
assert!(!engine
.detect_anomalies()
.iter()
.any(|a| a.description.contains("Gbps")));
assert!(!engine
.suggest_upgrades(&[])
.iter()
.any(|u| u.component == "Network"));
assert!(!workload(&engine, Workload::WebServer)
.limiting_factors
.iter()
.any(|s| s.contains("Slow network")));
}
#[cfg(target_os = "windows")]
#[test]
fn powershell_output_is_read_as_items_or_as_nothing() {
assert_eq!(json_items(r#"{"Name":"a"}"#).map(|v| v.len()), Some(1));
assert_eq!(
json_items(r#"[{"Name":"a"},{"Name":"b"}]"#).map(|v| v.len()),
Some(2)
);
assert_eq!(json_items(""), None);
assert_eq!(json_items("Get-PhysicalDisk : not recognized"), None);
let table = &[("hdd", 3), ("ssd", 4)];
let unspecified = serde_json::Value::String("Unspecified".into());
assert_eq!(wmi_enum(Some(&unspecified), table), None);
let ssd = serde_json::Value::String("SSD".into());
assert_eq!(wmi_enum(Some(&ssd), table), Some(4));
}
#[test]
fn cpu_identity_is_none_unless_a_name_or_vendor_was_read() {
let json: serde_json::Value = serde_json::from_str(
r#"{"Name":"AMD Ryzen 9 9900X 12-Core Processor ","Manufacturer":"AuthenticAMD"}"#,
)
.unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&json),
(
Some("AMD Ryzen 9 9900X 12-Core Processor".to_string()),
Some("AuthenticAMD".to_string())
)
);
let missing: serde_json::Value = serde_json::from_str(r#"{"NumberOfCores":8}"#).unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&missing),
(None, None)
);
let blank: serde_json::Value =
serde_json::from_str(r#"{"Name":" ","Manufacturer":""}"#).unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&blank),
(None, None)
);
let wrong_type: serde_json::Value = serde_json::from_str(r#"{"Name":42}"#).unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&wrong_type),
(None, None)
);
}
#[test]
fn cpu_identity_reads_a_multi_socket_array_when_sockets_agree() {
let agreeing: serde_json::Value = serde_json::from_str(
r#"[{"Name":"Intel Xeon Gold 6248R CPU @ 3.00GHz ","Manufacturer":"GenuineIntel"},
{"Name":"Intel Xeon Gold 6248R CPU @ 3.00GHz ","Manufacturer":"GenuineIntel"}]"#,
)
.unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&agreeing),
(
Some("Intel Xeon Gold 6248R CPU @ 3.00GHz".to_string()),
Some("GenuineIntel".to_string())
)
);
let mixed: serde_json::Value = serde_json::from_str(
r#"[{"Name":"Intel Xeon Gold 6248R","Manufacturer":"GenuineIntel"},
{"Name":"Intel Xeon Silver 4210","Manufacturer":"GenuineIntel"}]"#,
)
.unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&mixed),
(None, Some("GenuineIntel".to_string()))
);
let empty: serde_json::Value = serde_json::from_str("[]").unwrap();
assert_eq!(
HardwareInferenceEngine::windows_cpu_identity(&empty),
(None, None)
);
}
#[test]
fn test_serialization() {
let engine = HardwareInferenceEngine::new().unwrap();
let report = engine.full_analysis();
let json = serde_json::to_string(&report).unwrap();
let _: HardwareAnalysisReport = serde_json::from_str(&json).unwrap();
}
}