Files
alkane-os/src/profiles.rs
T
noah 9ed94bd01f
source-pr / source (pull_request) Successful in 12s
Add the profile database and the end-to-end detection driver
Profiles carry the only envelopes detection may use, so a combination absent
from the database is refused rather than guessed. The schema-1 document is
validated on load: unknown chips or sensor wiring, inverted or zero envelopes,
zero chain counts and duplicate names are all rejected.

run_detection now ties the pieces together: probe every declared port, select
a profile by chip, sensor wiring and physical port count, identify the PSU, and
emit a HardwarePlan. A machine with a dead chain still matches its three-chain
profile and runs degraded instead of being reclassified; plan() now tolerates
unidentified chains and refuses only when nothing identified.

The detection backend contract gains identify_psu(), and HalClient answers it
through the new HAL verb.
2026-10-22 10:17:34 -06:00

237 lines
7.4 KiB
Rust

// SPDX-License-Identifier: MIT
//! Board profile database.
//!
//! Profiles carry the safe voltage/frequency envelope a chip/board combination may run inside.
//! Detection may only use what this database provides: if a combination is absent, the answer is
//! "refuse", never "assume a number". Entries are data, so they can be filled from captures
//! without touching code.
use crate::detect::{BoardProfile, ChipModel, Envelope, SensorTopology};
use serde_json::Value;
/// Why a profile database was rejected.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProfileError {
InvalidJson,
UnsupportedSchema,
MissingProfiles,
UnknownChip(String),
UnknownSensor(String),
InvalidEnvelope(String),
DuplicateName(String),
}
/// A validated set of profiles.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ProfileDb {
profiles: Vec<BoardProfile>,
}
impl ProfileDb {
/// Validate and keep a set of profiles.
pub fn new(profiles: Vec<BoardProfile>) -> Result<Self, ProfileError> {
for (index, profile) in profiles.iter().enumerate() {
if profiles[..index]
.iter()
.any(|other| other.name == profile.name)
{
return Err(ProfileError::DuplicateName(profile.name.clone()));
}
if profile.chains == 0 {
return Err(ProfileError::InvalidEnvelope(profile.name.clone()));
}
let envelope = profile.envelope;
if envelope.v_min_mv == 0
|| envelope.v_min_mv > envelope.v_max_mv
|| envelope.f_min_mhz > envelope.f_max_mhz
{
return Err(ProfileError::InvalidEnvelope(profile.name.clone()));
}
}
Ok(Self { profiles })
}
/// Parse the schema-1 profile document.
pub fn from_json(text: &str) -> Result<Self, ProfileError> {
let root: Value = serde_json::from_str(text).map_err(|_| ProfileError::InvalidJson)?;
match root.get("schema").and_then(Value::as_u64) {
Some(1) => {}
Some(_) => return Err(ProfileError::UnsupportedSchema),
None => return Err(ProfileError::UnsupportedSchema),
}
let entries = root
.get("profiles")
.and_then(Value::as_array)
.ok_or(ProfileError::MissingProfiles)?;
let mut profiles = Vec::with_capacity(entries.len());
for entry in entries {
profiles.push(profile_from_value(entry)?);
}
if profiles.is_empty() {
return Err(ProfileError::MissingProfiles);
}
Self::new(profiles)
}
/// Exact lookup: a profile only applies to the chip, chain count and sensor wiring it declares.
pub fn find(
&self,
chip: ChipModel,
chains: u8,
sensor: SensorTopology,
) -> Option<&BoardProfile> {
self.profiles.iter().find(|profile| {
profile.chip == chip && profile.chains == chains && profile.sensor == sensor
})
}
pub fn len(&self) -> usize {
self.profiles.len()
}
pub fn is_empty(&self) -> bool {
self.profiles.is_empty()
}
}
fn profile_from_value(entry: &Value) -> Result<BoardProfile, ProfileError> {
let name = entry
.get("name")
.and_then(Value::as_str)
.ok_or(ProfileError::InvalidJson)?
.to_owned();
let chip_text = entry
.get("chip")
.and_then(Value::as_str)
.ok_or(ProfileError::UnknownChip(name.clone()))?;
let chip = match chip_text {
"bm1362" => ChipModel::Bm1362,
"bm1366" => ChipModel::Bm1366,
"bm1368" => ChipModel::Bm1368,
"bm1370" => ChipModel::Bm1370,
"bm1398" => ChipModel::Bm1398,
other => return Err(ProfileError::UnknownChip(other.to_owned())),
};
let sensor_text = entry
.get("sensor")
.and_then(Value::as_str)
.ok_or(ProfileError::UnknownSensor(name.clone()))?;
let sensor = match sensor_text {
"pic" => SensorTopology::Pic,
"nopic" => SensorTopology::NoPic,
"unknown" => SensorTopology::Unknown,
other => return Err(ProfileError::UnknownSensor(other.to_owned())),
};
let chains = entry
.get("chains")
.and_then(Value::as_u64)
.and_then(|value| u8::try_from(value).ok())
.ok_or(ProfileError::InvalidEnvelope(name.clone()))?;
let envelope = entry
.get("envelope")
.and_then(Value::as_object)
.ok_or(ProfileError::InvalidEnvelope(name.clone()))?;
let field = |key: &str| -> Result<u16, ProfileError> {
envelope
.get(key)
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok())
.ok_or(ProfileError::InvalidEnvelope(name.clone()))
};
let envelope = Envelope {
v_min_mv: field("v_min_mv")?,
v_max_mv: field("v_max_mv")?,
f_min_mhz: field("f_min_mhz")?,
f_max_mhz: field("f_max_mhz")?,
};
Ok(BoardProfile {
name,
chip,
sensor,
chains,
envelope,
})
}
#[cfg(test)]
mod tests {
use super::*;
const VALID: &str = r#"{
"schema": 1,
"profiles": [
{
"name": "s19jpro-bm1362-pic",
"chip": "bm1362",
"sensor": "pic",
"chains": 3,
"envelope": {"v_min_mv": 1100, "v_max_mv": 1500, "f_min_mhz": 300, "f_max_mhz": 700}
}
]
}"#;
#[test]
fn valid_document_loads_and_resolves() {
let db = ProfileDb::from_json(VALID).expect("db");
assert_eq!(db.len(), 1);
let profile = db
.find(ChipModel::Bm1362, 3, SensorTopology::Pic)
.expect("profile");
assert_eq!(profile.name, "s19jpro-bm1362-pic");
assert_eq!(profile.envelope.v_max_mv, 1500);
assert!(db.find(ChipModel::Bm1362, 2, SensorTopology::Pic).is_none());
assert!(db
.find(ChipModel::Bm1362, 3, SensorTopology::NoPic)
.is_none());
}
#[test]
fn unknown_chip_is_rejected() {
let text = VALID.replace("bm1362", "bm9999");
assert_eq!(
ProfileDb::from_json(&text),
Err(ProfileError::UnknownChip("bm9999".into()))
);
}
#[test]
fn inverted_envelope_is_rejected() {
let text = VALID.replace(
"\"v_min_mv\": 1100, \"v_max_mv\": 1500",
"\"v_min_mv\": 1500, \"v_max_mv\": 1100",
);
assert!(matches!(
ProfileDb::from_json(&text),
Err(ProfileError::InvalidEnvelope(_))
));
}
#[test]
fn wrong_schema_is_rejected() {
let text = VALID.replace("\"schema\": 1", "\"schema\": 2");
assert_eq!(
ProfileDb::from_json(&text),
Err(ProfileError::UnsupportedSchema)
);
}
#[test]
fn missing_profiles_are_rejected() {
assert_eq!(
ProfileDb::from_json("{\"schema\": 1}"),
Err(ProfileError::MissingProfiles)
);
}
#[test]
fn duplicate_names_are_rejected() {
let one = VALID.split("\"profiles\": [").nth(1).unwrap();
let entry = one.trim().trim_end_matches("]\n }").trim();
let duplicated = format!("{{\"schema\": 1, \"profiles\": [{entry}, {entry}]}}");
assert!(matches!(
ProfileDb::from_json(&duplicated),
Err(ProfileError::DuplicateName(_))
));
}
}