Boot over the real HAL contract
source-pr / source (pull_request) Successful in 14s

boot_from_hal connects the board backend, detects through the actual HAL
verbs, runs the one-time fan sweep through the same socket, publishes the
snapshot and returns the runtime and the learned map.

The tests drive it against a mock backend that speaks the real wire protocol
(ALKH framing, CAPABILITIES, PROBE_CHAIN, READ_EEPROM, IDENTIFY_PSU), so the
detection path is exercised end to end rather than assumed, and a missing
socket surfaces as a backend error instead of a half-booted miner.
This commit is contained in:
2026-10-22 10:54:35 -06:00
parent 64e1a9ae2b
commit 894b22277f
+171
View File
@@ -9,7 +9,10 @@ use crate::detect::{
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
SensorTopology,
};
use crate::fanmap::{FanMap, MapThresholds, SweepConfig};
use crate::fanmap_store::ensure_map;
use crate::fault::FaultPolicy;
use crate::hal_wire::{HalClient, HalError};
use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus};
use crate::profiles::{ProfileDb, ProfileError};
use crate::runtime::MinerRuntime;
@@ -18,6 +21,7 @@ use crate::web;
use std::fmt;
use std::io;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;
@@ -124,6 +128,8 @@ pub struct BootConfig {
pub enum BootError<E> {
Profile(ProfileError),
Detection(DetectionFailure<E>),
/// The board backend could not be reached or refused an operation.
Backend(E),
}
impl<E: fmt::Debug> fmt::Display for BootError<E> {
@@ -131,6 +137,7 @@ impl<E: fmt::Debug> fmt::Display for BootError<E> {
match self {
Self::Profile(error) => write!(f, "profile database rejected: {error:?}"),
Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"),
Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"),
}
}
}
@@ -172,6 +179,55 @@ pub fn boot<B: DetectionBackend>(
Ok(runtime)
}
/// A boot over the real local HAL contract, including the one-time fan sweep.
pub struct HalBoot<'a> {
pub config: &'a BootConfig,
pub sweep: SweepConfig,
pub thresholds: MapThresholds,
pub map_path: &'a Path,
}
/// Connect the board backend, detect, map the fans once, and publish.
///
/// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL
/// protocol, so the wiring is exercised rather than assumed.
pub fn boot_from_hal(
socket: &Path,
settings: &HalBoot<'_>,
status: &MiningStatus,
) -> Result<(MinerRuntime, FanMap), BootError<HalError>> {
let mut client = HalClient::connect(socket).map_err(BootError::Backend)?;
let zone_count = settings.sweep.zones;
let map = if zone_count == 0 {
FanMap::default()
} else {
ensure_map(
&mut client,
&settings.sweep,
settings.thresholds,
settings.map_path,
|millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))),
)
.map_err(|error| match error {
crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => {
BootError::Backend(error)
}
crate::fanmap_store::StoreError::Sweep(_) => {
BootError::Backend(HalError::Protocol("fan sweep configuration rejected"))
}
crate::fanmap_store::StoreError::Io(message) => {
BootError::Backend(HalError::Protocol(message))
}
})?
};
let config = BootConfig {
fan_zones: map.assignments.clone(),
..settings.config.clone()
};
let runtime = boot(&mut client, &config, status)?;
Ok((runtime, map))
}
/// Read one HTTP response body from a bound server, for health checks and tests.
pub fn http_get(address: SocketAddr, path: &str) -> io::Result<String> {
use std::io::{Read, Write};
@@ -190,6 +246,7 @@ mod tests {
ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint,
};
use crate::detect::{ProbeOutcome, PsuCapability};
use crate::fanmap::{MapThresholds, SweepConfig};
use crate::fault::FaultPolicy;
use crate::tuning::{PidConfig, TuningTarget};
use std::io::{Read, Write};
@@ -415,4 +472,118 @@ mod tests {
"fan:100"
);
}
fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> {
use std::io::{Read, Write};
use std::os::unix::net::UnixListener;
let listener = UnixListener::bind(&socket).expect("bind hal");
std::thread::spawn(move || {
let (mut stream, _) = listener.accept().expect("accept");
loop {
let mut header = [0_u8; 16];
if stream.read_exact(&mut header).is_err() {
return;
}
let opcode = header[5];
let sequence = header[8..12].to_vec();
let length =
u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize;
let mut payload = vec![0_u8; length];
if length > 0 && stream.read_exact(&mut payload).is_err() {
return;
}
let body: Vec<u8> = match opcode {
// CAPABILITIES: chain probe, EEPROM, PSU identity.
7 => {
let mut body = vec![0_u8];
body.extend_from_slice(&7_u32.to_le_bytes());
body
}
// PROBE_CHAIN: identified, bm1362, 126 chips.
8 => vec![0, 0, 1, 126, 0],
// READ_EEPROM: absent.
9 => vec![0, 1],
// IDENTIFY_PSU: APW12 with its envelope.
10 => {
let name = b"APW12";
let mut body = vec![0_u8, name.len() as u8];
body.extend_from_slice(name);
for word in [1200_u16, 1600, 0, 1000, 3600] {
body.extend_from_slice(&word.to_le_bytes());
}
body
}
_ => vec![1],
};
let mut out = [0_u8; 16];
out[..4].copy_from_slice(b"ALKH");
out[4] = 1;
out[5] = opcode;
out[6..8].copy_from_slice(&1_u16.to_le_bytes());
out[8..12].copy_from_slice(&sequence);
out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes());
if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() {
return;
}
}
})
}
#[test]
fn boot_over_the_hal_socket_detects_and_publishes() {
let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id()));
let socket = base.with_extension("sock");
let map_path = base.with_extension("map.json");
let _ = std::fs::remove_file(&socket);
let server = hal_server(socket.clone());
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &map_path,
};
let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal");
assert_eq!(runtime.active_chains(), vec![0, 1, 2]);
assert!(map.assignments.is_empty());
let document = status.hardware_document();
assert_eq!(document["available"], true);
assert_eq!(document["psu"], "APW12");
assert_eq!(document["chip"], "bm1362");
let _ = std::fs::remove_file(&socket);
let _ = server.join();
}
#[test]
fn boot_over_a_missing_socket_is_a_backend_error() {
let socket =
std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id()));
let status = MiningStatus::new();
let config = boot_config();
let settings = HalBoot {
config: &config,
sweep: SweepConfig {
fans: 0,
zones: 0,
low_pwm: 40,
high_pwm: 100,
repeats: 1,
settle_ms: 0,
},
thresholds: MapThresholds::default(),
map_path: &socket,
};
assert!(matches!(
boot_from_hal(&socket, &settings, &status),
Err(BootError::Backend(_))
));
}
}