Add the profile database and the end-to-end detection driver
source-pr / source (pull_request) Successful in 12s
source-pr / source (pull_request) Successful in 12s
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.
This commit is contained in:
+151
-6
@@ -161,10 +161,14 @@ pub fn plan(
|
||||
if chains.is_empty() {
|
||||
return Err(DetectionError::NoChains);
|
||||
}
|
||||
if chains.iter().any(|chain| chain.chip == ChipModel::Unknown) {
|
||||
if chains.iter().all(|chain| chain.chip == ChipModel::Unknown) {
|
||||
return Err(DetectionError::UnknownChip);
|
||||
}
|
||||
if chains.iter().any(|chain| chain.chip != profile.chip) {
|
||||
if chains
|
||||
.iter()
|
||||
.filter(|chain| chain.is_identified())
|
||||
.any(|chain| chain.chip != profile.chip)
|
||||
{
|
||||
return Err(DetectionError::ChipProfileMismatch);
|
||||
}
|
||||
let psu = psu.ok_or(DetectionError::PsuUnidentified)?;
|
||||
@@ -216,7 +220,7 @@ pub enum ProbeOutcome {
|
||||
///
|
||||
/// Framing, baud switching and electrical detail stay in the SDK image for that family; the OS
|
||||
/// only decides how many attempts to spend and what the results mean.
|
||||
pub trait ChainProbe {
|
||||
pub trait DetectionBackend {
|
||||
type Error;
|
||||
|
||||
/// Attempt one identification on `chain`. `attempt` lets the backend cycle its candidate
|
||||
@@ -224,6 +228,8 @@ pub trait ChainProbe {
|
||||
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error>;
|
||||
/// Read the hashboard EEPROM, or report that it is absent or unreadable.
|
||||
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error>;
|
||||
/// Identify the PSU, if this backend can. `None` means "cannot tell", which refuses later.
|
||||
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error>;
|
||||
}
|
||||
|
||||
/// How many identification attempts to spend per chain before declaring it unidentified.
|
||||
@@ -242,7 +248,7 @@ impl Default for ProbeBudget {
|
||||
///
|
||||
/// A chain that never identifies is reported as `ChipModel::Unknown` with zero chips rather than
|
||||
/// being dropped, so the plan can refuse explicitly and the API can show why.
|
||||
pub fn probe_chain<B: ChainProbe>(
|
||||
pub fn probe_chain<B: DetectionBackend>(
|
||||
backend: &mut B,
|
||||
chain: u8,
|
||||
budget: ProbeBudget,
|
||||
@@ -268,7 +274,7 @@ pub fn probe_chain<B: ChainProbe>(
|
||||
}
|
||||
|
||||
/// Probe every declared chain port.
|
||||
pub fn detect_chains<B: ChainProbe>(
|
||||
pub fn detect_chains<B: DetectionBackend>(
|
||||
backend: &mut B,
|
||||
chains: &[u8],
|
||||
budget: ProbeBudget,
|
||||
@@ -280,6 +286,50 @@ pub fn detect_chains<B: ChainProbe>(
|
||||
Ok(reports)
|
||||
}
|
||||
|
||||
/// Everything the caller knows before probing: which ports exist, how hard to try, and how the
|
||||
/// hashboards report temperature.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct DetectionRequest<'a> {
|
||||
pub chain_ports: &'a [u8],
|
||||
pub budget: ProbeBudget,
|
||||
pub sensor: SensorTopology,
|
||||
pub fan_zones: Vec<FanZone>,
|
||||
}
|
||||
|
||||
/// Why a detection run did not produce a plan.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum DetectionFailure<E> {
|
||||
Backend(E),
|
||||
Refused(DetectionError),
|
||||
NoProfile,
|
||||
}
|
||||
|
||||
/// Detect, select a profile, and decide whether the machine may run.
|
||||
///
|
||||
/// The profile is selected by chip, sensor wiring and the number of physical chain ports, so a
|
||||
/// machine with a dead chain still matches its profile and runs degraded instead of being
|
||||
/// reclassified as a different model.
|
||||
pub fn run_detection<B: DetectionBackend>(
|
||||
backend: &mut B,
|
||||
db: &crate::profiles::ProfileDb,
|
||||
request: &DetectionRequest<'_>,
|
||||
) -> Result<HardwarePlan, DetectionFailure<B::Error>> {
|
||||
let reports = detect_chains(backend, request.chain_ports, request.budget)
|
||||
.map_err(DetectionFailure::Backend)?;
|
||||
let chip = reports
|
||||
.iter()
|
||||
.find(|report| report.is_identified())
|
||||
.map(|report| report.chip)
|
||||
.ok_or(DetectionFailure::Refused(DetectionError::UnknownChip))?;
|
||||
let chains = u8::try_from(request.chain_ports.len()).unwrap_or(u8::MAX);
|
||||
let profile = db
|
||||
.find(chip, chains, request.sensor)
|
||||
.ok_or(DetectionFailure::NoProfile)?;
|
||||
let psu = backend.identify_psu().map_err(DetectionFailure::Backend)?;
|
||||
plan(&reports, profile, psu.as_ref(), request.fan_zones.clone())
|
||||
.map_err(DetectionFailure::Refused)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -427,6 +477,7 @@ mod tests {
|
||||
eeprom: EepromState,
|
||||
calls: usize,
|
||||
fail_at: u8,
|
||||
psu: Option<PsuCapability>,
|
||||
}
|
||||
|
||||
impl ScriptedProbe {
|
||||
@@ -436,11 +487,12 @@ mod tests {
|
||||
eeprom,
|
||||
calls: 0,
|
||||
fail_at: u8::MAX,
|
||||
psu: Some(psu()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainProbe for ScriptedProbe {
|
||||
impl DetectionBackend for ScriptedProbe {
|
||||
type Error = ();
|
||||
|
||||
fn probe(&mut self, _chain: u8, attempt: u8) -> Result<ProbeOutcome, ()> {
|
||||
@@ -454,6 +506,10 @@ mod tests {
|
||||
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
|
||||
Ok(self.eeprom.clone())
|
||||
}
|
||||
|
||||
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
|
||||
Ok(self.psu.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -553,4 +609,93 @@ mod tests {
|
||||
Err(DetectionError::UnknownChip)
|
||||
);
|
||||
}
|
||||
|
||||
fn db() -> crate::profiles::ProfileDb {
|
||||
crate::profiles::ProfileDb::new(vec![profile()]).expect("db")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_detection_emits_a_plan_end_to_end() {
|
||||
let mut backend = ScriptedProbe::new(
|
||||
&[
|
||||
ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
],
|
||||
EepromState::Absent,
|
||||
);
|
||||
let request = DetectionRequest {
|
||||
chain_ports: &[0, 1, 2],
|
||||
budget: ProbeBudget::default(),
|
||||
sensor: SensorTopology::Pic,
|
||||
fan_zones: vec![FanZone {
|
||||
fan: 0,
|
||||
zones: vec![0],
|
||||
}],
|
||||
};
|
||||
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
|
||||
assert_eq!(plan.chains.len(), 3);
|
||||
assert_eq!(plan.psu, "APW12");
|
||||
assert!(!plan.operating_point.confirmed);
|
||||
assert_eq!(plan.operating_point.voltage_mv, 1200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_detection_refuses_when_no_profile_matches() {
|
||||
let mut backend = ScriptedProbe::new(
|
||||
&[ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
}],
|
||||
EepromState::Absent,
|
||||
);
|
||||
let request = DetectionRequest {
|
||||
chain_ports: &[0],
|
||||
budget: ProbeBudget::default(),
|
||||
sensor: SensorTopology::Pic,
|
||||
fan_zones: Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
run_detection(&mut backend, &db(), &request),
|
||||
Err(DetectionFailure::NoProfile)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_detection_runs_degraded_with_a_dead_chain() {
|
||||
let mut backend = ScriptedProbe::new(
|
||||
&[
|
||||
ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
ProbeOutcome::Identified {
|
||||
chip: ChipModel::Bm1362,
|
||||
chips: 126,
|
||||
},
|
||||
ProbeOutcome::Silent,
|
||||
ProbeOutcome::Silent,
|
||||
ProbeOutcome::Silent,
|
||||
ProbeOutcome::Silent,
|
||||
],
|
||||
EepromState::Absent,
|
||||
);
|
||||
let request = DetectionRequest {
|
||||
chain_ports: &[0, 1, 2],
|
||||
budget: ProbeBudget::default(),
|
||||
sensor: SensorTopology::Pic,
|
||||
fan_zones: Vec::new(),
|
||||
};
|
||||
let plan = run_detection(&mut backend, &db(), &request).expect("plan");
|
||||
assert_eq!(plan.degraded_chains(126), vec![2]);
|
||||
}
|
||||
}
|
||||
|
||||
+8
-2
@@ -1,7 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
|
||||
|
||||
use crate::detect::{ChainProbe, ChipModel, EepromState, Envelope, ProbeOutcome, PsuCapability};
|
||||
use crate::detect::{
|
||||
ChipModel, DetectionBackend, EepromState, Envelope, ProbeOutcome, PsuCapability,
|
||||
};
|
||||
use crate::HardwareBackend;
|
||||
use std::fmt;
|
||||
use std::io::{self, Read, Write};
|
||||
@@ -446,7 +448,7 @@ impl HalClient {
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainProbe for HalClient {
|
||||
impl DetectionBackend for HalClient {
|
||||
type Error = HalError;
|
||||
|
||||
fn probe(&mut self, chain: u8, attempt: u8) -> Result<ProbeOutcome, Self::Error> {
|
||||
@@ -456,6 +458,10 @@ impl ChainProbe for HalClient {
|
||||
fn eeprom(&mut self, chain: u8) -> Result<EepromState, Self::Error> {
|
||||
self.read_eeprom(chain)
|
||||
}
|
||||
|
||||
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, Self::Error> {
|
||||
self.identify_psu().map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn chip_from_wire(value: u8) -> Option<ChipModel> {
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod hal_wire;
|
||||
pub mod management;
|
||||
pub mod miner;
|
||||
pub mod pow;
|
||||
pub mod profiles;
|
||||
pub mod scrypt_pow;
|
||||
pub mod stratum_client;
|
||||
pub mod stratum_session;
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
// 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(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user