Persist the learned fan map and reuse it until the hardware changes
source-pr / source (pull_request) Successful in 12s

Mapping fans perturbs the machine, so it is done once and stored. ensure_map
reuses a stored map only when the fan and sensor counts match the current
machine; a mismatch is ignored rather than trusted, because applying a map
learned on four fans to a two-fan machine would mis-control thermals.

The store is a small schema-1 document; corrupt or foreign files are ignored
and trigger a fresh sweep instead of failing the boot.
This commit is contained in:
2026-10-22 10:47:19 -06:00
parent 5a1a7948b1
commit 5048156b74
2 changed files with 319 additions and 0 deletions
+318
View File
@@ -0,0 +1,318 @@
// SPDX-License-Identifier: MIT
//! Persisting the learned fan map.
//!
//! Mapping fans means heating and cooling the machine deliberately, so it is done once, stored, and
//! reused until the fan or sensor set changes. A stored map that does not match the current set is
//! ignored rather than trusted: silently applying a map learned on four fans to a machine with two
//! would mis-control thermals.
use crate::detect::FanZone;
use crate::fanmap::{map_fans, sweep, FanMap, FanProbe, MapThresholds, SweepConfig, SweepError};
use serde_json::{json, Value};
use std::fs;
use std::io;
use std::path::Path;
/// A stored map together with the hardware it was learned on.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StoredMap {
pub fans: u8,
pub zones: u8,
pub assignments: Vec<FanZone>,
pub unresolved: Vec<u8>,
}
impl StoredMap {
pub fn from_map(map: &FanMap, fans: u8, zones: u8) -> Self {
Self {
fans,
zones,
assignments: map.assignments.clone(),
unresolved: map.unresolved.clone(),
}
}
pub fn to_map(&self) -> FanMap {
FanMap {
assignments: self.assignments.clone(),
unresolved: self.unresolved.clone(),
confidence_per_mille: vec![0; self.assignments.len()],
}
}
/// True when this map was learned on the same fan and zone counts.
pub fn matches(&self, fans: u8, zones: u8) -> bool {
self.fans == fans && self.zones == zones
}
pub fn to_json(&self) -> String {
json!({
"schema": 1,
"fans": self.fans,
"zones": self.zones,
"assignments": self.assignments.iter().map(|zone| json!({
"fan": zone.fan,
"zones": zone.zones,
})).collect::<Vec<_>>(),
"unresolved": self.unresolved,
})
.to_string()
}
pub fn from_json(text: &str) -> Option<Self> {
let root: Value = serde_json::from_str(text).ok()?;
if root.get("schema")?.as_u64()? != 1 {
return None;
}
let fans = u8::try_from(root.get("fans")?.as_u64()?).ok()?;
let zones = u8::try_from(root.get("zones")?.as_u64()?).ok()?;
let assignments = root
.get("assignments")?
.as_array()?
.iter()
.map(|entry| {
Some(FanZone {
fan: u8::try_from(entry.get("fan")?.as_u64()?).ok()?,
zones: entry
.get("zones")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?,
})
})
.collect::<Option<Vec<FanZone>>>()?;
let unresolved = root
.get("unresolved")?
.as_array()?
.iter()
.map(|zone| u8::try_from(zone.as_u64()?).ok())
.collect::<Option<Vec<u8>>>()?;
Some(Self {
fans,
zones,
assignments,
unresolved,
})
}
}
/// Why mapping did not produce a stored map.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StoreError<E> {
Sweep(SweepError<E>),
Io(&'static str),
}
/// Read a stored map, if one exists and parses.
pub fn load(path: &Path) -> Option<StoredMap> {
let text = fs::read_to_string(path).ok()?;
StoredMap::from_json(&text)
}
/// Write a map, creating the parent directory when needed.
pub fn save(path: &Path, stored: &StoredMap) -> io::Result<()> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
fs::write(path, stored.to_json())
}
/// Return the stored map when it matches this machine, otherwise sweep, map, and store the result.
pub fn ensure_map<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
thresholds: MapThresholds,
path: &Path,
settle: S,
) -> Result<FanMap, StoreError<B::Error>> {
if let Some(stored) = load(path) {
if stored.matches(config.fans, config.zones) {
return Ok(stored.to_map());
}
}
let zones: Vec<u8> = (0..config.zones).collect();
let samples = sweep(backend, config, settle).map_err(StoreError::Sweep)?;
let map = map_fans(&samples, &zones, thresholds);
let stored = StoredMap::from_map(&map, config.fans, config.zones);
save(path, &stored).map_err(|_| StoreError::Io("cannot write the fan map"))?;
Ok(map)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fanmap::{ProbeSample, ZoneReading};
struct CountingBackend {
duty: Vec<u8>,
owners: Vec<(u8, u8)>,
calls: usize,
}
impl FanProbe for CountingBackend {
type Error = ();
fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), ()> {
self.calls += 1;
self.duty[fan as usize] = pwm;
Ok(())
}
fn read_zone(&mut self, zone: u8) -> Result<i32, ()> {
// Zones without an explicit owner follow fan 0, which keeps the mock usable when a
// test asks for more zones than the fixture declares.
let owner = self
.owners
.iter()
.find(|(_, candidate)| *candidate == zone)
.map(|(fan, _)| *fan)
.unwrap_or(0);
Ok(if self.duty[owner as usize] >= 100 {
50_000
} else {
70_000
})
}
}
fn backend() -> CountingBackend {
CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
}
}
fn config(zones: u8) -> SweepConfig {
SweepConfig {
fans: 2,
zones,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
}
}
fn path(name: &str) -> std::path::PathBuf {
let mut dir = std::env::temp_dir();
dir.push(format!("alkane-fanmap-{}-{name}.json", std::process::id()));
dir
}
#[test]
fn a_stored_map_round_trips() {
let map = FanMap {
assignments: vec![FanZone {
fan: 0,
zones: vec![0, 1],
}],
unresolved: vec![2],
confidence_per_mille: vec![900],
};
let stored = StoredMap::from_map(&map, 4, 3);
let text = stored.to_json();
assert_eq!(StoredMap::from_json(&text).expect("parse"), stored);
let back = stored.to_map();
assert_eq!(back.assignments, map.assignments);
assert_eq!(back.unresolved, map.unresolved);
}
#[test]
fn corrupt_or_foreign_json_is_ignored() {
assert!(StoredMap::from_json("not json").is_none());
assert!(StoredMap::from_json(r#"{"schema":2}"#).is_none());
assert!(StoredMap::from_json(r#"{"schema":1,"fans":2}"#).is_none());
}
#[test]
fn a_matching_map_is_reused_without_sweeping() {
let file = path("reuse");
let first = ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
assert_eq!(first.zones_for(0), vec![0]);
let mut reuse = backend();
let second = ensure_map(
&mut reuse,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(second.zones_for(0), vec![0]);
assert_eq!(reuse.calls, 0, "a stored map must not cause another sweep");
let _ = std::fs::remove_file(&file);
}
#[test]
fn a_changed_sensor_set_forces_a_new_sweep() {
let file = path("changed");
ensure_map(
&mut backend(),
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("first");
let mut fresh = backend();
let map = ensure_map(
&mut fresh,
&config(2),
MapThresholds::default(),
&file,
|_| {},
)
.expect("second");
assert_eq!(map.zones_for(1), vec![1]);
// The stored file describes two zones; asking for three must not reuse it.
let mut three = CountingBackend {
duty: vec![100, 100],
owners: vec![(0, 0), (1, 1)],
calls: 0,
};
let _ = ensure_map(
&mut three,
&config(3),
MapThresholds::default(),
&file,
|_| {},
);
assert!(three.calls > 0);
let _ = std::fs::remove_file(&file);
}
#[test]
fn samples_from_a_sweep_still_map_correctly() {
let samples = vec![
ProbeSample {
fan: 0,
pwm: 40,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 70_000,
}],
},
ProbeSample {
fan: 0,
pwm: 100,
readings: vec![ZoneReading {
zone: 0,
temp_mc: 50_000,
}],
},
];
let map = map_fans(&samples, &[0], MapThresholds::default());
assert_eq!(map.zones_for(0), vec![0]);
}
}
+1
View File
@@ -11,6 +11,7 @@ pub mod bm13xx;
pub mod detect;
pub mod difficulty;
pub mod fanmap;
pub mod fanmap_store;
pub mod fault;
pub mod hal_wire;
pub mod management;