use super::{classify_from_signals, plan_from_settings, Classification, Plan, Signals};
use crate::profile::SettingRisk;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
#[default]
Recommend,
Apply {
ceiling: SettingRisk,
confirm: bool,
},
}
pub const UNATTENDED_CEILING: SettingRisk = SettingRisk::Moderate;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Cycle {
pub elapsed_secs: u64,
pub plan: Plan,
pub applied: Vec<AppliedOutcome>,
pub withheld: Vec<Withheld>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AppliedOutcome {
pub setting_id: String,
pub status: String,
pub message: String,
#[serde(default)]
pub outcome: Option<crate::profile::apply::ApplyOutcome>,
#[serde(default)]
pub verdict: Option<crate::tuning::verify::Verdict>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Withheld {
pub setting_id: String,
pub reason: String,
}
pub fn revert_cycle(cycle: &Cycle, confirm: bool) -> Vec<crate::profile::apply::ApplyOutcome> {
cycle
.applied
.iter()
.rev()
.filter(|a| {
!a.verdict
.as_ref()
.is_some_and(crate::tuning::verify::Verdict::warrants_revert)
})
.filter_map(|a| a.outcome.as_ref())
.map(|o| crate::profile::apply::revert_setting(o, confirm))
.collect()
}
pub fn collect_signals() -> Signals {
let mut signals = Signals::default();
if let Ok(mut monitor) = crate::ai_workload::AiWorkloadMonitor::new() {
if let Ok(workloads) = monitor.detect_workloads() {
signals.ai_present = Some(!workloads.is_empty());
signals.ai_training = Some(workloads.iter().any(|w| w.is_training()));
signals.ai_frameworks = workloads
.iter()
.filter(|w| w.framework != crate::ai_workload::AiFramework::Unknown)
.map(|w| format!("{:?}", w.framework).to_lowercase())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
}
}
if let Ok(monitor) = crate::UnifiedMonitor::new() {
if let Ok(gpus) = monitor.snapshot_gpus() {
let failed = !monitor.gpus().detection_failures().is_empty();
signals.gpu_count = if gpus.is_empty() && failed {
None
} else {
Some(gpus.len())
};
signals.gpu_utilization = gpus
.iter()
.filter_map(|g| g.utilization())
.map(f32::from)
.fold(None, |acc: Option<f32>, u| {
Some(acc.map_or(u, |a| a.max(u)))
});
}
}
signals.cpu_utilization = read_cpu_utilization();
signals.game_processes = detect_game_processes();
signals
}
pub(crate) fn read_cpu_utilization() -> Option<f32> {
#[cfg(windows)]
{
crate::platform::windows::read_cpu_stats()
.ok()
.map(|s| 100.0 - s.total.idle)
}
#[cfg(target_os = "linux")]
{
crate::platform::linux::read_cpu_stats()
.ok()
.map(|s| 100.0 - s.total.idle)
}
#[cfg(not(any(windows, target_os = "linux")))]
{
None
}
}
fn detect_game_processes() -> Option<Vec<String>> {
const MARKERS: [&str; 8] = [
"steam",
"epicgameslauncher",
"battle.net",
"gog galaxy",
"riotclientservices",
"eadesktop",
"ubisoftconnect",
"unrealengine",
];
let Ok(mut monitor) = crate::process_monitor::ProcessMonitor::new() else {
return None;
};
let Ok(processes) = monitor.processes() else {
return None;
};
let mut found: Vec<String> = processes
.iter()
.map(|p| p.name.to_ascii_lowercase())
.filter(|name| MARKERS.iter().any(|m| name.contains(m)))
.collect();
found.sort();
found.dedup();
Some(found)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VerifyPolicy {
pub settle: Duration,
pub plan: crate::tuning::verify::SamplingPlan,
}
impl Default for VerifyPolicy {
fn default() -> Self {
Self {
settle: Duration::from_secs(5),
plan: crate::tuning::verify::SamplingPlan::default(),
}
}
}
pub fn cycle(mode: Mode, started: Instant) -> Cycle {
let signals = collect_signals();
let classification = classify_from_signals(&signals);
cycle_with(mode, started, classification)
}
pub fn cycle_verified(mode: Mode, started: Instant, policy: &VerifyPolicy) -> Cycle {
let mut scratch = crate::tuning::ledger::Ledger::new();
cycle_verified_with(mode, started, policy, &mut scratch)
}
pub fn cycle_verified_with(
mode: Mode,
started: Instant,
policy: &VerifyPolicy,
ledger: &mut crate::tuning::ledger::Ledger,
) -> Cycle {
let signals = collect_signals();
let classification = classify_from_signals(&signals);
cycle_inner(mode, started, classification, Some(policy), Some(ledger))
}
pub fn cycle_with(mode: Mode, started: Instant, classification: Classification) -> Cycle {
cycle_inner(mode, started, classification, None, None)
}
fn cycle_inner(
mode: Mode,
started: Instant,
classification: Classification,
policy: Option<&VerifyPolicy>,
mut ledger: Option<&mut crate::tuning::ledger::Ledger>,
) -> Cycle {
let settings = current_settings();
let plan = plan_from_settings(classification, &settings);
let mut applied = Vec::new();
let mut withheld = Vec::new();
match mode {
Mode::Recommend => {
for rec in &plan.recommendations {
withheld.push(Withheld {
setting_id: rec.setting_id.clone(),
reason: "server is in recommend mode and will not write".to_string(),
});
}
}
Mode::Apply { ceiling, confirm } => {
let effective = min_risk(ceiling, UNATTENDED_CEILING);
for rec in &plan.recommendations {
if !plan.within_risk(effective).contains(&rec) {
withheld.push(Withheld {
setting_id: rec.setting_id.clone(),
reason: format!(
"risk {:?} exceeds the unattended ceiling {:?}",
rec.risk, effective
),
});
continue;
}
if let Some(skip) = ledger.as_ref().and_then(|l| l.skip(&rec.setting_id)) {
withheld.push(Withheld {
setting_id: rec.setting_id.clone(),
reason: skip.reason(&rec.setting_id),
});
continue;
}
let (outcome, verdict) = match policy {
Some(p) => {
let v = crate::tuning::verify::apply_verified(
&rec.setting_id,
rec.proposed.clone(),
confirm,
p.settle,
&p.plan,
);
(v.outcome, Some(v.verdict))
}
None => (
crate::profile::apply::apply_setting_reversible(
&rec.setting_id,
rec.proposed.clone(),
confirm,
),
None,
),
};
if let (Some(l), Some(v)) = (ledger.as_mut(), verdict.as_ref()) {
l.record(&rec.setting_id, v.clone());
}
applied.push(AppliedOutcome {
setting_id: rec.setting_id.clone(),
status: format!("{:?}", outcome.status),
message: outcome.message.clone(),
outcome: Some(outcome),
verdict,
});
}
}
}
Cycle {
elapsed_secs: started.elapsed().as_secs(),
plan,
applied,
withheld,
}
}
fn min_risk(a: SettingRisk, b: SettingRisk) -> SettingRisk {
let rank = |r: SettingRisk| match r {
SettingRisk::Informational => 0u8,
SettingRisk::Safe => 1,
SettingRisk::Moderate => 2,
SettingRisk::Dangerous => 3,
};
if rank(a) <= rank(b) {
a
} else {
b
}
}
fn current_settings() -> Vec<crate::profile::Setting> {
let mut inspector = crate::profile::ProfileInspector::new();
let snapshot = inspector.snapshot_all();
snapshot
.providers
.values()
.flat_map(|groups| groups.iter())
.flat_map(|group| group.settings.iter().cloned())
.collect()
}
pub fn run<F, S>(mode: Mode, interval: Duration, mut on_cycle: F, mut stop: S)
where
F: FnMut(&Cycle),
S: FnMut() -> bool,
{
let started = Instant::now();
while !stop() {
let c = cycle(mode, started);
on_cycle(&c);
let deadline = Instant::now() + interval;
while Instant::now() < deadline {
if stop() {
return;
}
std::thread::sleep(Duration::from_millis(200).min(interval));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::profile::Subsystem;
use crate::tuning::{Method, Recommendation, UseCase};
fn plan_with(risk: SettingRisk) -> Classification {
let _ = risk;
Classification {
use_case: UseCase::AiTraining,
confidence: 0.9,
method: Method::Signals,
evidence: vec!["test".into()],
}
}
#[test]
fn the_default_mode_is_recommend_only() {
assert_eq!(Mode::default(), Mode::Recommend);
}
#[test]
fn recommend_mode_withholds_with_a_reason() {
let c = cycle_with(
Mode::Recommend,
Instant::now(),
plan_with(SettingRisk::Safe),
);
assert!(c.applied.is_empty(), "recommend mode must not write");
for w in &c.withheld {
assert!(w.reason.contains("recommend mode"), "{}", w.reason);
}
assert_eq!(c.withheld.len(), c.plan.recommendations.len());
}
#[test]
fn an_unattended_apply_is_capped_below_dangerous() {
assert_eq!(
min_risk(SettingRisk::Dangerous, UNATTENDED_CEILING),
SettingRisk::Moderate
);
assert_eq!(
min_risk(SettingRisk::Safe, UNATTENDED_CEILING),
SettingRisk::Safe
);
}
#[test]
fn a_dangerous_recommendation_is_withheld_even_when_confirmed() {
let plan = Plan {
classification: plan_with(SettingRisk::Dangerous),
recommendations: vec![Recommendation {
setting_id: "some_voltage_thing".into(),
subsystem: Subsystem::Gpu,
display_name: "Voltage".into(),
current: crate::profile::SettingValue::Int(1000),
proposed: crate::profile::SettingValue::Int(1100),
risk: SettingRisk::Dangerous,
basis: "test".into(),
rationale: "test".into(),
}],
skipped: vec![],
};
let effective = min_risk(SettingRisk::Dangerous, UNATTENDED_CEILING);
assert!(
plan.within_risk(effective).is_empty(),
"a Dangerous recommendation must not survive the unattended ceiling"
);
}
#[test]
fn the_loop_stops_promptly_when_asked() {
const INTERVAL: Duration = Duration::from_secs(300);
const GENEROUS: Duration = Duration::from_secs(60);
let mut cycles = 0;
let started = Instant::now();
run(Mode::Recommend, INTERVAL, |_| cycles += 1, {
let mut calls = 0;
move || {
calls += 1;
calls > 1
}
});
assert_eq!(cycles, 1);
assert!(
started.elapsed() < GENEROUS,
"stopping took {:?} against a {INTERVAL:?} interval, so the stop request \
was not noticed until the sleep ended",
started.elapsed()
);
}
#[test]
fn collecting_signals_never_panics() {
let s = collect_signals();
let c = classify_from_signals(&s);
assert!(!c.evidence.is_empty());
}
#[test]
fn reverting_a_recommend_only_cycle_is_a_no_op() {
let cycle = cycle(Mode::Recommend, Instant::now());
assert!(cycle.applied.is_empty(), "Recommend mode must not write");
assert!(revert_cycle(&cycle, true).is_empty());
}
#[test]
fn revert_undoes_in_reverse_and_reports_the_unrevertible() {
use crate::profile::apply::{ApplyOutcome, ApplyStatus};
use crate::profile::{SettingValue, Subsystem};
let mk = |id: &str, previous: Option<&str>| AppliedOutcome {
setting_id: id.into(),
status: "Applied".into(),
message: String::new(),
outcome: Some(ApplyOutcome {
setting_id: id.into(),
subsystem: Some(Subsystem::Cpu),
requested: SettingValue::Text("new".into()),
status: ApplyStatus::Applied,
message: String::new(),
timestamp: 0,
previous: previous.map(|p| SettingValue::Text(p.into())),
}),
verdict: None,
};
let cycle = Cycle {
elapsed_secs: 0,
plan: Plan {
classification: Classification {
use_case: crate::tuning::UseCase::Idle,
confidence: 0.0,
method: crate::tuning::Method::Signals,
evidence: vec![],
},
recommendations: vec![],
skipped: vec![],
},
applied: vec![mk("first", Some("old")), mk("second", None)],
withheld: vec![],
};
let reverts = revert_cycle(&cycle, true);
assert_eq!(reverts.len(), 2, "every applied write is accounted for");
assert_eq!(
reverts[0].setting_id, "second",
"the last write applied is the first undone"
);
assert_eq!(reverts[0].status, ApplyStatus::NotWritable);
assert!(reverts[0].message.contains("no prior value"));
}
#[test]
fn a_measured_regression_is_withheld_on_the_next_cycle() {
use crate::tuning::ledger::{Ledger, Skip};
let mut ledger = Ledger::new();
ledger.record(
"scaling_governor",
crate::tuning::verify::Verdict::Regressed {
metric: "m".into(),
before: 10.0,
after: 20.0,
delta: 10.0,
},
);
let skip = ledger.skip("scaling_governor");
assert_eq!(skip, Some(Skip::Regressed));
let reason = skip.unwrap().reason("scaling_governor");
assert!(
reason.contains("scaling_governor") && reason.contains("regression"),
"a withheld recommendation must say what was measured, not merely that it was skipped: {reason}"
);
ledger.record(
"active_scheme_guid",
crate::tuning::verify::Verdict::Unverifiable {
reason: "no metric is declared".into(),
},
);
assert_eq!(
ledger.skip("active_scheme_guid"),
None,
"an absent measurement must not be treated as evidence against a setting"
);
}
#[test]
fn a_write_verification_already_reverted_is_not_reverted_twice() {
use crate::profile::apply::{ApplyOutcome, ApplyStatus};
use crate::profile::SettingValue;
let mk = |id: &str, verdict: Option<crate::tuning::verify::Verdict>| AppliedOutcome {
setting_id: id.into(),
status: "Applied".into(),
message: String::new(),
outcome: Some(ApplyOutcome {
setting_id: id.into(),
subsystem: Some(Subsystem::Cpu),
requested: SettingValue::Text("new".into()),
status: ApplyStatus::Applied,
message: String::new(),
timestamp: 0,
previous: Some(SettingValue::Text("old".into())),
}),
verdict,
};
let regressed = crate::tuning::verify::Verdict::Regressed {
metric: "m".into(),
before: 10.0,
after: 20.0,
delta: 10.0,
};
let improved = crate::tuning::verify::Verdict::Improved {
metric: "m".into(),
before: 20.0,
after: 10.0,
delta: -10.0,
};
let cycle = Cycle {
elapsed_secs: 0,
plan: Plan {
classification: Classification {
use_case: crate::tuning::UseCase::Idle,
confidence: 0.0,
method: crate::tuning::Method::Signals,
evidence: vec![],
},
recommendations: vec![],
skipped: vec![],
},
applied: vec![
mk("kept", Some(improved)),
mk("already_undone", Some(regressed)),
mk("unmeasured", None),
],
withheld: vec![],
};
let reverts = revert_cycle(&cycle, true);
let ids: Vec<&str> = reverts.iter().map(|r| r.setting_id.as_str()).collect();
assert!(
!ids.contains(&"already_undone"),
"verification put this one back; reverting it again would restore the value that was measured as worse. got {ids:?}"
);
assert!(
ids.contains(&"kept"),
"an improvement is still the caller's to undo if they ask"
);
assert!(
ids.contains(&"unmeasured"),
"a write nobody measured must still be revertible"
);
}
}