Files
alkane-toolkit/crates/alkane-gui/src/model.rs
T
noahandClaude Opus 4.8 67a7d832ee
build-test-release / release (push) Successful in 7m24s
GUI round 11 follow-ups: equal-height zebra, backdrop dimming, SVG KPI icons, boards sort
- Zebra stripe heights: the cell rect wx hands a custom renderer is shrunk to the
  content size in BOTH dimensions, so shape cells (dots) and text cells filled
  different-height bands -> unequal stripes across columns. SegmentRenderer now
  fills an over-sized rect (full column width + well beyond the row vertically);
  the cell DC clips it to the real cell, giving uniform full-row stripes. Verified
  in a screenshot.
- Focus dimming: the treeview's own state flags don't carry GTK_STATE_FLAG_BACKDROP
  (that lives on the toplevel), so uncoloured segments (combined-cell slashes,
  target hashrate, "Stock") never dimmed. ThemedTextColour now reads the toplevel
  window's active state (gtk_window_is_active) and forces BACKDROP onto the
  style-context state when inactive, so those segments take the same dimmed themed
  colour the native columns do.
- KPI icons: replaced the hand-drawn vectors with operator-supplied Font Awesome
  Pro SVGs (rabbit=hashing, turtle=slow, cracked wine glass=not hashing,
  otter=paused) plus matching in-repo bolt (power) and hive (hashrate) SVGs. New
  wxbr_svg_icon renders an SVG via wxBitmapBundle::FromSVG; the GUI recolours
  each icon's currentColor to the card's colour and sizes it to the SVG aspect
  ratio. Removed the old wxbr_kpi_icon path.
- Boards column sort: it sorted by total board count (all ~3, so no visible
  order). It now sorts by the number of ONLINE (green) boards, total count as a
  tiebreaker, so units with dead/missing boards surface.

wx-rs bridge/Rust changes mirrored into patches 0002 (widgets.rs) and 0003
(widgets_bridge.cpp) per ADR 0003.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-19 11:55:39 -06:00

1842 lines
74 KiB
Rust

//! Table data model: rows, columns, sort/filter state (UI-SPEC section "Table").
use std::collections::{HashMap, HashSet};
/// A miner counts as "slow" when it is mining but running below this fraction
/// of its model's expected hashrate (UI-SPEC "Slow" band). A missing expected
/// hashrate (0.0) means the band is unknown, so the miner is never "slow".
pub const SLOW_THRESHOLD: f64 = 0.8;
/// The single source of truth for the "slow" classification, shared by the
/// live scan (`scan::to_row`) and the fixtures/tests, so the expected-vs-actual
/// comparison exercises the same rule the app uses.
pub fn is_slow(is_mining: bool, hashrate_ths: f64, expected_ths: f64) -> bool {
is_mining && expected_ths > 0.0 && hashrate_ths < SLOW_THRESHOLD * expected_ths
}
/// Choose an SI prefix and a max-3-significant-digit mantissa string for a
/// base value, shared by `format_si` and `format_fan_rpm`: the prefix puts
/// the mantissa in [1, 1000), shown with 1 decimal below 100 and no decimal
/// from 100 up. `None` for a non-finite or non-positive value -- the caller
/// renders its own "absent" form ("0 <unit>" for `format_si`, "-" for
/// `format_fan_rpm`).
fn si_mantissa_and_prefix(value_base: f64) -> Option<(String, &'static str)> {
if !value_base.is_finite() || value_base <= 0.0 {
return None;
}
const PREFIXES: [&str; 8] = ["", "k", "M", "G", "T", "P", "E", "Z"];
let mut v = value_base;
let mut i = 0usize;
while v >= 1000.0 && i < PREFIXES.len() - 1 {
v /= 1000.0;
i += 1;
}
// Round first, then re-check the prefix. A mantissa that rounds up to 1000
// (e.g. 999.9 -> "1000") must roll over to the next prefix so the number
// never shows more than three integer digits; and a mantissa in [99.95,100)
// rounds to "100.0" and should drop its decimal (the >=100 branch's rule).
let render = |v: f64| if v >= 100.0 { format!("{v:.0}") } else { format!("{v:.1}") };
let mut num = render(v);
if (num == "1000" || num == "1000.0") && i < PREFIXES.len() - 1 {
v /= 1000.0;
i += 1;
num = render(v);
} else if num == "100.0" {
num = "100".to_string();
}
Some((num, PREFIXES[i]))
}
/// Format a value in its base unit with an SI prefix chosen so the number stays
/// compact: the prefix puts the mantissa in [1, 1000), then it is shown with 1
/// decimal below 100 and no decimal from 100 up (so 21300 W -> "21.3 kW",
/// 685e12 H/s -> "685 TH/s", 6.8e12 -> "6.8 TH/s"). Zero renders as "0 <unit>".
pub fn format_si(value_base: f64, unit: &str) -> String {
match si_mantissa_and_prefix(value_base) {
Some((num, prefix)) => format!("{num} {prefix}{unit}"),
None => format!("0 {unit}"),
}
}
/// Like `format_si` but for a cooling-fan RPM reading: no unit/space suffix,
/// and "-" (rather than "0") for an absent/non-positive reading, since a fan
/// column packs several of these per cell (see `Column::Cooling`).
pub fn format_fan_rpm(rpm: f64) -> String {
match si_mantissa_and_prefix(rpm) {
Some((num, prefix)) => format!("{num}{prefix}"),
None => "-".to_string(),
}
}
/// A hashrate reading (in TH/s) for the combined Hashrate column: mantissa + SI
/// prefix only, no unit and no space (80.5 TH/s -> "80.5T", 102 TH/s -> "102T"),
/// or `None` for an absent/non-positive reading.
pub fn format_hashrate_ths(ths: f64) -> Option<String> {
si_mantissa_and_prefix(ths * 1e12).map(|(num, prefix)| format!("{num}{prefix}"))
}
/// The actual/expected ratio, or `None` when the expected value is unknown
/// (<= 0.0) so a ratio-based color/warning never divides by zero or treats an
/// unknown expectation as a 0% shortfall.
pub fn actual_expected_ratio(actual: f64, expected: f64) -> Option<f64> {
if expected > 0.0 { Some(actual / expected) } else { None }
}
/// Render the combined Hashrate cell "actual/expected" (no spaces around the
/// slash, prefix-only unit): blank when neither is known, the bare actual when
/// only it is known, "-/<expected>" when only the expected is known, and
/// "<actual>/<expected>" when both are (e.g. "80.5T/95.0T").
fn combined_si(actual_ths: f64, expected_ths: f64) -> String {
match (format_hashrate_ths(actual_ths), format_hashrate_ths(expected_ths)) {
(None, None) => String::new(),
(Some(a), None) => a,
(None, Some(e)) => format!("-/{e}"),
(Some(a), Some(e)) => format!("{a}/{e}"),
}
}
/// Same combined rendering as `combined_si`, for a plain integer count
/// (hashboards, total chips) instead of an SI-formatted rate.
fn combined_count(actual: Option<u32>, expected: Option<u32>) -> String {
match (actual, expected) {
(None, None) => String::new(),
(Some(a), None) => a.to_string(),
(None, Some(e)) => format!("- / {e}"),
(Some(a), Some(e)) => format!("{a} / {e}"),
}
}
/// Encode colored text segments for a custom-rendered cell (see the wx-rs
/// `SegmentRenderer`): segments are joined by U+001F, and within a segment an
/// optional uppercase RRGGBB color is separated from its text by U+001E.
/// `decode_segments_plain` is the inverse for anything that just wants the
/// plain text (filtering, sorting, tests).
pub fn encode_segments(segs: &[(Option<(u8, u8, u8)>, String)]) -> String {
segs.iter()
.map(|(color, text)| {
let hex = color.map(|(r, g, b)| format!("{r:02X}{g:02X}{b:02X}")).unwrap_or_default();
format!("{hex}\u{1e}{text}")
})
.collect::<Vec<_>>()
.join("\u{1f}")
}
/// Strip the encoding `encode_segments` applies, returning just the
/// concatenated text. A plain string with no U+001E in it (i.e. never passed
/// through `encode_segments`) round-trips unchanged, so this is safe to call
/// on any cell value.
pub fn decode_segments_plain(s: &str) -> String {
if !s.contains('\u{1e}') {
return s.to_string();
}
s.split('\u{1f}')
.map(|seg| seg.split_once('\u{1e}').map(|(_, text)| text).unwrap_or(seg))
.collect::<String>()
}
/// Split a full pool worker "account.worker" into (account, worker). Mining
/// pools name a worker "<account>.<rig>"; split on the first '.'. With no '.',
/// the whole string is the account and the worker name is empty.
fn split_worker(full: &str) -> (&str, &str) {
match full.split_once('.') {
Some((account, worker)) => (account, worker),
None => (full, ""),
}
}
/// Compact human duration (e.g. "3d 4h", "5h 12m", "42m", "18s").
pub fn format_uptime(secs: u64) -> String {
if secs == 0 {
return String::new();
}
let d = secs / 86_400;
let h = (secs % 86_400) / 3600;
let m = (secs % 3600) / 60;
let s = secs % 60;
if d > 0 {
format!("{d}d {h}h")
} else if h > 0 {
format!("{h}h {m}m")
} else if m > 0 {
format!("{m}m")
} else {
format!("{s}s")
}
}
/// Pack a dotted-quad IPv4 string into a u32 for numeric ordering, so
/// "10.255.1.9" sorts before "10.255.1.10" (a plain string sort gets this
/// wrong). Anything unparseable sorts first (0). `pub(crate)` so the headless
/// self-test can build the same numeric order it asserts the view against.
pub(crate) fn ip_to_u32(s: &str) -> u32 {
let mut parts = s.split('.');
let mut acc = 0u32;
for _ in 0..4 {
let octet: u32 = parts.next().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
acc = (acc << 8) | (octet & 0xff);
}
acc
}
/// What a miner supports being told to do, probed from asic-rs' `supports_*`
/// capability methods at scan time. The right-click menu offers an action only
/// when every selected miner supports it (the intersection of capabilities).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MinerCaps {
pub fault_light: bool,
pub restart: bool,
pub pause: bool,
pub resume: bool,
pub power_limit: bool,
pub tuning: bool,
/// Whether this miner's asic-rs driver supports `upgrade_firmware`
/// (probed via `supports_upgrade_firmware()` at scan time).
pub firmware_flash: bool,
}
impl MinerCaps {
/// The capabilities common to `self` and `other` (logical AND per action).
pub fn intersect(self, other: MinerCaps) -> MinerCaps {
MinerCaps {
fault_light: self.fault_light && other.fault_light,
restart: self.restart && other.restart,
pause: self.pause && other.pause,
resume: self.resume && other.resume,
power_limit: self.power_limit && other.power_limit,
tuning: self.tuning && other.tuning,
firmware_flash: self.firmware_flash && other.firmware_flash,
}
}
/// The capabilities common to every miner in `caps` (all-true identity when
/// empty is intentionally avoided: an empty selection has no common caps).
pub fn intersect_all(caps: impl IntoIterator<Item = MinerCaps>) -> MinerCaps {
let mut it = caps.into_iter();
match it.next() {
Some(first) => it.fold(first, MinerCaps::intersect),
None => MinerCaps::default(),
}
}
/// True when no action is supported (nothing to offer in the menu).
pub fn is_empty(self) -> bool {
self == MinerCaps::default()
}
/// Whether the miner exposes any writable control action at all. Used to
/// infer the "Access" (locked/unlocked) column: no control -> view-only.
pub fn any_control(self) -> bool {
self.fault_light
|| self.restart
|| self.pause
|| self.resume
|| self.power_limit
|| self.tuning
|| self.firmware_flash
}
}
/// Per-hashboard health for the Boards column's status dots (round 11 #10):
/// green = present and hashing, red = present but idle/faulty, grey = expected
/// but not detected at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardHealth {
Ok,
Fault,
Missing,
}
/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the
/// scalar fields the table can display. Absent metrics are `None` / empty /
/// 0.0 and render as a blank cell.
#[derive(Debug, Clone, Default)]
pub struct MinerRow {
pub ip: String,
pub selected: bool,
/// What this miner supports being told to do (for the right-click menu).
pub caps: MinerCaps,
// identity
pub model: String,
/// Manufacturer brand ("Antminer", "WhatsMiner", ...), its own column so the
/// Model column can carry just the cleaned model name.
pub brand: String,
/// Model sub-variant: WhatsMiner's version block ("VE40"); blank for Antminer
/// (its hashboard type is not reported over the network by asic-rs).
pub submodel: String,
pub mac: String,
pub hostname: String,
pub serial: String,
/// Firmware family only ("Stock", "VNish", "Braiins", ...); the Firmware
/// column colours by this. The version string lives in `fw_version`.
pub firmware: String,
pub fw_version: String,
pub api_version: String,
/// Combined "CPU (code)" control-board label (e.g. "AML (C76)"); `cpu` and
/// `board_code` hold the split halves for their own columns.
pub control_board: String,
pub cpu: String,
pub board_code: String,
/// Mining algorithm (e.g. "SHA256", "Scrypt", "Equihash"), from asic-rs.
pub algorithm: String,
/// Whether the hashboards carry a PIC MCU. asic-rs does not report this over
/// the network, so it is a best-effort inference (model-string heuristic):
/// `None` = unknown, `Some(true)` = PIC, `Some(false)` = noPIC. True
/// detection needs an on-board SSH/I2C probe (a separate feature).
pub pic_present: Option<bool>,
/// Whether this miner is locked to view-only (no command writes). Inferred
/// from whether any control capability is available: `None` = unknown,
/// `Some(true)` = locked, `Some(false)` = unlocked/writable.
pub write_locked: Option<bool>,
/// Structured error/event lines from the miner (severity + text), most
/// severe first. Empty means none. The Error column shows a summary; the
/// full list is the hover tooltip (added with the tooltip bridge support).
pub errors: Vec<String>,
// performance
pub hashrate_ths: f64,
pub expected_ths: f64,
#[allow(dead_code)] // retained for the "slow" band; not shown as its own column
pub efficiency: f64,
pub power_w: f64,
pub tuning_percent: Option<u8>,
// thermal / cooling
/// Average chip temperature (used for sorting/colour banding of the
/// combined Chip-temp cell).
pub chip_temp_c: f64,
/// Per-hashboard chip temperature (hottest chip per board), shown in the
/// Chip-temp column as "77 / 64 / 74". Empty falls back to the average.
pub board_temps: Vec<f64>,
/// Coolant/immersion-fluid temperature (liquid-cooled miners only).
pub fluid_temp_c: f64,
/// Environment/ambient air temperature. asic-rs reports air-cooled miners'
/// ambient reading in its `fluid_temperature` field (see the WhatsMiner
/// backends' "Env Temp"/"environment-temperature" key); the scan routes it
/// here for air-cooled models so it isn't mislabelled as a fluid temp
/// (round 11 #17).
pub env_temp_c: f64,
pub outlet_temp_c: f64,
/// Individual cooling-fan RPMs (empty if unknown). PSU fan is tracked
/// separately below since it is not part of the cooling-fan set.
pub fan_rpms: Vec<f64>,
pub psu_fan_rpm: f64,
pub fan_count: Option<u32>,
pub expected_fans: Option<u32>,
// hardware counts
pub total_chips: Option<u32>,
pub expected_chips: Option<u32>,
pub hashboards: Option<u32>,
pub expected_hashboards: Option<u32>,
/// Per-hashboard health for the Boards status dots (round 11 #10), one entry
/// per expected board, ordered by position (index 0 = board 1). Empty = no
/// per-board data (the cell renders blank).
pub board_status: Vec<BoardHealth>,
// pool: active-pool convenience fields, plus the (url, worker) of each
// configured pool (miners usually allow up to 3 redundant pools).
pub worker: String,
pub pool_url: String,
pub pools: Vec<(String, String)>,
// shares
pub best_share: Option<f64>,
pub session_best_share: Option<f64>,
// state
pub uptime_secs: u64,
pub light_flashing: Option<bool>,
pub operating_state: String,
pub is_mining: bool,
pub slow: bool,
/// Not-mining because an operator paused it (distinct from simply idle);
/// see `is_paused`.
pub paused: bool,
}
impl MinerRow {
/// The row's status label. Only miners that actually responded to a scan
/// become rows, so there is no "offline" state: a responding miner that is
/// not mining is "not hashing".
pub fn status(&self) -> &'static str {
if self.slow {
"slow"
} else if self.paused {
"paused"
} else if self.is_mining {
"hashing"
} else {
"not hashing"
}
}
/// Upsert into `rows` by ip; returns true if the row is new.
pub fn upsert_into(self, rows: &mut Vec<MinerRow>) -> bool {
if let Some(r) = rows.iter_mut().find(|r| r.ip == self.ip) {
let selected = r.selected;
*r = self;
r.selected = selected;
return false;
}
rows.push(self);
true
}
}
/// The single source of truth for the "paused" classification: a miner is
/// counted as operator-paused when it is not currently mining and its raw
/// operating-state string says so (case-insensitively), shared by the live
/// scan (`scan::to_row`) and the fixtures/tests.
pub fn is_paused(operating_state: &str, is_mining: bool) -> bool {
!is_mining && operating_state.to_lowercase().contains("pause")
}
/// The typed-confirmation gate for the irreversible firmware-flash action: the
/// operator must type exactly "FLASH" (surrounding whitespace ignored, but not
/// case-folded and not a prefix). Pure so the guard is unit-testable without a
/// live dialog.
pub fn flash_confirmed(input: &str) -> bool {
input.trim() == "FLASH"
}
/// Model columns. Ip is fixed (always shown first); the rest map 1:1 to a
/// scannable metric and can be shown/hidden/reordered. Row selection replaces
/// the old checkbox column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Column {
Ip,
Hashrate,
/// Sort-only pseudo-column (round 11 #16): the actual/expected hashrate
/// ratio. Deliberately NOT in `ALL_COLUMNS`, so it never appears in the
/// column picker or the display order; it exists only as a `sort` target the
/// Hashrate header cycles into.
HashrateRel,
Power,
ChipTemp,
Cooling,
Firmware,
FwVersion,
Worker,
PoolAccount,
Model,
Brand,
Submodel,
Status,
Efficiency,
FluidTemp,
EnvTemp,
OutletTemp,
PsuFan,
FanCount,
ExpectedFans,
TotalChips,
Hashboards,
Mac,
Hostname,
Serial,
ApiVersion,
Cpu,
BoardCode,
Algorithm,
Pic,
Locked,
Error,
Uptime,
Light,
OperatingState,
BestShare,
SessionBestShare,
TuningPercent,
PoolUrl,
Pool1Url,
Pool1Worker,
Pool2Url,
Pool2Worker,
Pool3Url,
Pool3Worker,
}
/// Every column, in registry order. Ip first, then the default-visible set
/// (UI-SPEC order), then all remaining metrics.
pub const ALL_COLUMNS: [Column; 45] = [
Column::Ip,
Column::Hashrate,
Column::Power,
Column::ChipTemp,
Column::Cooling,
Column::Firmware,
Column::FwVersion,
Column::Worker,
Column::PoolAccount,
Column::Model,
Column::Brand,
Column::Submodel,
Column::Status,
Column::Efficiency,
Column::FluidTemp,
Column::EnvTemp,
Column::OutletTemp,
Column::PsuFan,
Column::FanCount,
Column::ExpectedFans,
Column::TotalChips,
Column::Hashboards,
Column::Mac,
Column::Hostname,
Column::Serial,
Column::ApiVersion,
Column::Cpu,
Column::BoardCode,
Column::Algorithm,
Column::Pic,
Column::Locked,
Column::Error,
Column::Uptime,
Column::Light,
Column::OperatingState,
Column::BestShare,
Column::SessionBestShare,
Column::TuningPercent,
Column::PoolUrl,
Column::Pool1Url,
Column::Pool1Worker,
Column::Pool2Url,
Column::Pool2Worker,
Column::Pool3Url,
Column::Pool3Worker,
];
/// The columns shown by default (UI-SPEC), after the fixed IP column, in display
/// order: model, errors, hashrate, power, chip temp, firmware, CPU, boards
/// (hashboard health), access.
pub const DEFAULT_VISIBLE: [Column; 9] = [
Column::Model,
Column::Error,
Column::Hashrate,
Column::Power,
Column::ChipTemp,
Column::Firmware,
Column::Cpu,
Column::Hashboards,
Column::Locked,
];
impl Column {
pub fn title(self) -> &'static str {
match self {
Column::Ip => "IP",
Column::Hashrate => "Hashrate",
Column::HashrateRel => "Rel. hashrate",
Column::Power => "Power",
Column::ChipTemp => "Chip temp",
Column::Cooling => "Fan (RPM)",
Column::Firmware => "Firmware",
Column::FwVersion => "FW Version",
Column::Worker => "Worker",
Column::PoolAccount => "Pool account",
Column::Model => "Model",
Column::Brand => "Brand",
Column::Submodel => "Submodel",
Column::Status => "Status",
Column::Efficiency => "Efficiency (J/TH)",
Column::FluidTemp => "Fluid temp",
Column::EnvTemp => "Env temp",
Column::OutletTemp => "Outlet temp",
Column::PsuFan => "PSU fan (RPM)",
Column::FanCount => "Fans",
Column::ExpectedFans => "Fans (exp)",
Column::TotalChips => "Chips",
Column::Hashboards => "Boards",
Column::Mac => "MAC",
Column::Hostname => "Hostname",
Column::Serial => "Serial",
Column::ApiVersion => "API ver",
Column::Cpu => "CPU",
Column::BoardCode => "Board",
Column::Algorithm => "Algorithm",
Column::Pic => "PIC",
Column::Locked => "Access",
Column::Error => "Errors",
Column::Uptime => "Uptime",
Column::Light => "Light",
Column::OperatingState => "State",
Column::BestShare => "Best share",
Column::SessionBestShare => "Session best",
Column::TuningPercent => "Tuning %",
Column::PoolUrl => "Pool URL",
Column::Pool1Url => "Pool 1 URL",
Column::Pool1Worker => "Pool 1 worker",
Column::Pool2Url => "Pool 2 URL",
Column::Pool2Worker => "Pool 2 worker",
Column::Pool3Url => "Pool 3 URL",
Column::Pool3Worker => "Pool 3 worker",
}
}
pub fn width(self) -> i32 {
match self {
Column::Ip => 130,
Column::Hashrate => 110,
Column::HashrateRel => 110,
Column::Power => 90,
Column::ChipTemp | Column::FluidTemp | Column::EnvTemp | Column::OutletTemp => 95,
Column::Cooling | Column::PsuFan => 100,
Column::Firmware => 110,
Column::FwVersion => 130,
Column::Worker => 130,
Column::PoolAccount => 120,
Column::Model => 150,
Column::Brand => 100,
Column::Submodel => 100,
Column::Status => 95,
Column::Efficiency => 120,
Column::FanCount | Column::TotalChips | Column::Hashboards => 70,
Column::ExpectedFans | Column::TuningPercent => 90,
Column::Mac | Column::Hostname | Column::Serial => 150,
Column::ApiVersion | Column::Light => 90,
Column::Cpu => 70,
Column::BoardCode => 70,
Column::Algorithm => 100,
Column::Pic => 70,
Column::Locked => 90,
Column::Error => 160,
Column::Uptime => 100,
Column::OperatingState => 100,
Column::BestShare | Column::SessionBestShare => 110,
Column::PoolUrl | Column::Pool1Url | Column::Pool2Url | Column::Pool3Url => 200,
Column::Pool1Worker | Column::Pool2Worker | Column::Pool3Worker => 150,
}
}
/// Whether the column holds a continuous numeric value. Such columns sort
/// numerically and are excluded from the Excel-style value filter (a
/// per-value checklist only makes sense for categorical data).
pub fn is_numeric(self) -> bool {
matches!(
self,
Column::Hashrate
| Column::HashrateRel
| Column::Power
| Column::Efficiency
| Column::ChipTemp
| Column::FluidTemp
| Column::EnvTemp
| Column::OutletTemp
| Column::Cooling
| Column::PsuFan
| Column::FanCount
| Column::ExpectedFans
| Column::TotalChips
| Column::Hashboards
| Column::Uptime
| Column::BestShare
| Column::SessionBestShare
| Column::TuningPercent
)
}
/// The numeric value used for numeric filtering, or `None` for a text column
/// or a blank/missing cell (so `> 0` never matches an absent metric). A
/// "blank" cell is exactly one the table renders empty -- several value-type
/// columns store an absent reading as 0.0, which `cell()` blanks; mirror that
/// here so a filter like "ChipTemp <= 50" cannot match a miner with no
/// temperature reading.
pub fn num_value(&self, r: &MinerRow) -> Option<f64> {
// The 3 combined (actual/expected) columns must never let a numeric
// filter match a row that only has an expected value: their cell()
// renders "- / <expected>" (non-empty) in that case, so the generic
// blank check below is not enough on its own.
match self {
Column::Hashrate if r.hashrate_ths <= 0.0 => return None,
Column::Hashboards if r.hashboards.is_none() => return None,
Column::TotalChips if r.total_chips.is_none() => return None,
_ => {}
}
if !self.is_numeric() || self.cell(r).is_empty() {
return None;
}
match self.sort_key(r) {
SortKey::Num(v) if v.is_finite() => Some(v),
_ => None,
}
}
/// Sort key. Numeric columns compare by their underlying number (absent =
/// -inf so blanks sort to the bottom of a descending sort); others compare
/// as lowercase strings.
pub fn sort_key(&self, r: &MinerRow) -> SortKey {
let none = f64::NEG_INFINITY;
match self {
Column::Hashrate => SortKey::Num(r.hashrate_ths),
// Relative hashrate = actual/expected; unknown expectation sorts to
// the bottom (round 11 #16).
Column::HashrateRel => {
SortKey::Num(actual_expected_ratio(r.hashrate_ths, r.expected_ths).unwrap_or(none))
}
Column::Power => SortKey::Num(r.power_w),
Column::Efficiency => SortKey::Num(if r.efficiency > 0.0 { r.efficiency } else { none }),
Column::ChipTemp => SortKey::Num(r.chip_temp_c),
Column::FluidTemp => SortKey::Num(r.fluid_temp_c),
Column::EnvTemp => SortKey::Num(r.env_temp_c),
Column::OutletTemp => SortKey::Num(r.outlet_temp_c),
Column::Cooling => SortKey::Num(if r.fan_rpms.is_empty() {
none
} else {
r.fan_rpms.iter().cloned().fold(f64::INFINITY, f64::min)
}),
Column::PsuFan => SortKey::Num(r.psu_fan_rpm),
Column::FanCount => SortKey::Num(r.fan_count.map(|v| v as f64).unwrap_or(none)),
Column::ExpectedFans => SortKey::Num(r.expected_fans.map(|v| v as f64).unwrap_or(none)),
Column::TotalChips => SortKey::Num(r.total_chips.map(|v| v as f64).unwrap_or(none)),
// The Boards column shows per-hashboard health dots, so sort by the
// number of ONLINE (green) boards -- surfacing units with dead/missing
// boards -- with the total board count as a tiebreaker (so full-health
// units still order by how many boards they have). Falls back to the
// reported board count when no per-board health is available (round 11).
Column::Hashboards => {
if r.board_status.is_empty() {
SortKey::Num(r.hashboards.map(|v| v as f64).unwrap_or(none))
} else {
let online =
r.board_status.iter().filter(|h| matches!(h, BoardHealth::Ok)).count();
let total = r.board_status.len();
SortKey::Num((online * 100 + total) as f64)
}
}
Column::Uptime => SortKey::Num(if r.uptime_secs > 0 { r.uptime_secs as f64 } else { none }),
Column::BestShare => SortKey::Num(r.best_share.unwrap_or(none)),
Column::SessionBestShare => SortKey::Num(r.session_best_share.unwrap_or(none)),
Column::TuningPercent => {
SortKey::Num(r.tuning_percent.map(|v| v as f64).unwrap_or(none))
}
// IP sorts numerically (u32 fits exactly in f64), not lexically.
Column::Ip => SortKey::Num(ip_to_u32(&r.ip) as f64),
_ => SortKey::Str(self.cell(r).to_lowercase()),
}
}
pub fn cell(&self, r: &MinerRow) -> String {
let num = |v: f64, dp: usize, suffix: &str| -> String {
if v > 0.0 {
match dp {
0 => format!("{v:.0}{suffix}"),
_ => format!("{v:.1}{suffix}"),
}
} else {
String::new()
}
};
let count = |v: Option<u32>| -> String { v.map(|n| n.to_string()).unwrap_or_default() };
let pool_url = |i: usize| r.pools.get(i).map(|(u, _)| u.clone()).unwrap_or_default();
let pool_worker = |i: usize| r.pools.get(i).map(|(_, w)| w.clone()).unwrap_or_default();
match self {
Column::Ip => r.ip.clone(),
Column::Hashrate => combined_si(r.hashrate_ths, r.expected_ths),
// Never displayed as its own column; rendered as a percentage only for
// completeness (e.g. a debug/self-test read of the cell).
Column::HashrateRel => actual_expected_ratio(r.hashrate_ths, r.expected_ths)
.map(|ratio| format!("{:.0}%", ratio * 100.0))
.unwrap_or_default(),
Column::Power => {
if r.power_w > 0.0 {
format_si(r.power_w, "W")
} else {
String::new()
}
}
Column::Efficiency => num(r.efficiency, 1, ""),
// Per-hashboard chip temps as integers ("77 / 64 / 74"); fall back to
// the average (integer) when per-board readings aren't available.
Column::ChipTemp => {
if r.board_temps.is_empty() {
if r.chip_temp_c > 0.0 { format!("{:.0}", r.chip_temp_c) } else { String::new() }
} else {
r.board_temps.iter().map(|&t| format!("{t:.0}")).collect::<Vec<_>>().join(" / ")
}
}
Column::FluidTemp => num(r.fluid_temp_c, 1, " C"),
Column::EnvTemp => num(r.env_temp_c, 1, " C"),
Column::OutletTemp => num(r.outlet_temp_c, 1, " C"),
Column::Cooling => {
r.fan_rpms.iter().map(|&v| format_fan_rpm(v)).collect::<Vec<_>>().join("/")
}
Column::PsuFan => num(r.psu_fan_rpm, 0, ""),
Column::FanCount => count(r.fan_count),
Column::ExpectedFans => count(r.expected_fans),
Column::TotalChips => combined_count(r.total_chips, r.expected_chips),
Column::Hashboards => combined_count(r.hashboards, r.expected_hashboards),
Column::Firmware => r.firmware.clone(),
Column::FwVersion => r.fw_version.clone(),
Column::Worker => split_worker(&r.worker).1.to_string(),
Column::PoolAccount => split_worker(&r.worker).0.to_string(),
Column::PoolUrl => r.pool_url.clone(),
Column::Model => r.model.clone(),
Column::Brand => r.brand.clone(),
Column::Submodel => r.submodel.clone(),
Column::Mac => r.mac.clone(),
Column::Hostname => r.hostname.clone(),
Column::Serial => r.serial.clone(),
Column::ApiVersion => r.api_version.clone(),
Column::Cpu => r.cpu.clone(),
Column::BoardCode => r.board_code.clone(),
Column::Algorithm => r.algorithm.clone(),
Column::Pic => match r.pic_present {
Some(true) => "PIC".to_string(),
Some(false) => "noPIC".to_string(),
None => "?".to_string(),
},
Column::Locked => match r.write_locked {
Some(true) => "locked".to_string(),
Some(false) => "unlocked".to_string(),
None => "?".to_string(),
},
// Just the count (blank when none); the full list is the hover
// tooltip (see fill_rows). No "errors" word, even for a single one.
Column::Error => match r.errors.len() {
0 => String::new(),
n => n.to_string(),
},
Column::Status => r.status().to_string(),
Column::Uptime => format_uptime(r.uptime_secs),
Column::Light => match r.light_flashing {
Some(true) => "on".to_string(),
Some(false) => "off".to_string(),
None => String::new(),
},
Column::OperatingState => r.operating_state.clone(),
Column::BestShare => r.best_share.map(|v| format_si(v, "")).unwrap_or_default(),
Column::SessionBestShare => {
r.session_best_share.map(|v| format_si(v, "")).unwrap_or_default()
}
Column::TuningPercent => r.tuning_percent.map(|v| format!("{v}%")).unwrap_or_default(),
Column::Pool1Url => pool_url(0),
Column::Pool1Worker => pool_worker(0),
Column::Pool2Url => pool_url(1),
Column::Pool2Worker => pool_worker(1),
Column::Pool3Url => pool_url(2),
Column::Pool3Worker => pool_worker(2),
}
}
}
pub enum SortKey {
Num(f64),
Str(String),
}
/// Text-column filter operators (Excel-style text filters).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum TextOp {
Contains,
NotContains,
BeginsWith,
EndsWith,
Equals,
}
/// Numeric-column filter operators (Excel-style number filters).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum NumOp {
Between,
Eq,
Ne,
Gt,
Ge,
Lt,
Le,
}
/// One column's active filter. Text columns can filter by a value checklist
/// ("is any of") or a text predicate; numeric columns by a numeric predicate.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum ColFilter {
Values(HashSet<String>),
Text { op: TextOp, needle: String },
Num { op: NumOp, a: f64, b: f64 },
}
impl ColFilter {
/// Does `r`'s value in `col` satisfy this filter?
pub fn matches(&self, col: Column, r: &MinerRow) -> bool {
match self {
ColFilter::Values(set) => set.contains(&col.cell(r)),
ColFilter::Text { op, needle } => {
let hay = col.cell(r).to_lowercase();
let n = needle.to_lowercase();
match op {
TextOp::Contains => hay.contains(&n),
TextOp::NotContains => !hay.contains(&n),
TextOp::BeginsWith => hay.starts_with(&n),
TextOp::EndsWith => hay.ends_with(&n),
TextOp::Equals => hay == n,
}
}
ColFilter::Num { op, a, b } => {
let Some(v) = col.num_value(r) else { return false };
let (a, b) = (*a, *b);
match op {
NumOp::Between => v >= a.min(b) && v <= a.max(b),
NumOp::Eq => v == a,
NumOp::Ne => v != a,
NumOp::Gt => v > a,
NumOp::Ge => v >= a,
NumOp::Lt => v < a,
NumOp::Le => v <= a,
}
}
}
}
}
/// Display state: order, visibility, sort, filter.
#[derive(Clone)]
pub struct ViewState {
/// Model column order as displayed (Ip is always the first visible column).
pub order: Vec<Column>,
pub visible: HashSet<Column>,
pub sort: Option<(Column, bool)>, // (column, ascending)
/// Active per-column filters (AND across columns); empty = unfiltered.
pub filters: HashMap<Column, ColFilter>,
}
impl Default for ViewState {
fn default() -> Self {
// Display order = Ip, then DEFAULT_VISIBLE in its own order, then every
// remaining metric (so the initial columns match the UI-SPEC order rather
// than the ALL_COLUMNS registry order). Default sort is by IP ascending.
let mut order: Vec<Column> = Vec::with_capacity(ALL_COLUMNS.len());
order.push(Column::Ip);
order.extend(DEFAULT_VISIBLE);
for c in ALL_COLUMNS {
if !order.contains(&c) {
order.push(c);
}
}
let mut visible: HashSet<Column> = DEFAULT_VISIBLE.iter().copied().collect();
visible.insert(Column::Ip);
ViewState { order, visible, sort: Some((Column::Ip, true)), filters: HashMap::new() }
}
}
impl ViewState {
pub fn display_columns(&self) -> Vec<Column> {
// Ip is always shown first; the rest follow `order` filtered by visibility.
self.order
.iter()
.copied()
.filter(|c| *c == Column::Ip || self.visible.contains(c))
.collect()
}
/// Every column available to filter on, independent of visibility: a filter
/// matches a row by that column's cell text whether or not the column is
/// shown, so (e.g.) Algorithm can be filtered without first un-hiding it.
/// Ip first, then the registry order.
pub fn filter_columns(&self) -> Vec<Column> {
let mut v = vec![Column::Ip];
v.extend(self.order.iter().copied().filter(|c| *c != Column::Ip));
v
}
pub fn is_fixed(&self, c: Column) -> bool {
c == Column::Ip
}
/// Apply a drag-reorder of the visible columns. `new_visible` is the visible
/// columns in their new display order; it must be a permutation of the
/// currently-visible set with Ip still first. The new order is spliced back
/// into `order`, leaving hidden columns in their existing slots, so a
/// reorder while some column is hidden never drops or duplicates a column.
pub fn apply_visible_reorder(&mut self, new_visible: &[Column]) {
let disp = self.display_columns();
if new_visible.len() != disp.len() || new_visible.first() != Some(&Column::Ip) {
return;
}
let want: HashSet<Column> = disp.iter().copied().collect();
let got: HashSet<Column> = new_visible.iter().copied().collect();
if want != got {
return; // not a permutation of the visible columns: ignore
}
let mut next = new_visible.iter().copied();
self.order = self
.order
.iter()
.map(|&c| if want.contains(&c) { next.next().unwrap_or(c) } else { c })
.collect();
}
/// Rows that pass every active filter (AND across columns).
pub fn passes_filters(&self, r: &MinerRow) -> bool {
self.filters.iter().all(|(col, f)| f.matches(*col, r))
}
/// Filtered + sorted rows in display order.
pub fn view(&self, rows: &[MinerRow]) -> Vec<usize> {
let mut idx: Vec<usize> = (0..rows.len())
.filter(|&i| self.passes_filters(&rows[i]))
.collect();
if let Some((col, asc)) = self.sort {
// Decorate-sort-undecorate: compute each row's sort key exactly once
// (a string key allocates), not twice per comparison.
let mut keyed: Vec<(SortKey, usize)> =
idx.iter().map(|&i| (col.sort_key(&rows[i]), i)).collect();
keyed.sort_by(|(ka, _), (kb, _)| {
let ord = match (ka, kb) {
(SortKey::Num(x), SortKey::Num(y)) => {
x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
}
(SortKey::Str(x), SortKey::Str(y)) => x.cmp(y),
_ => std::cmp::Ordering::Equal,
};
if asc { ord } else { ord.reverse() }
});
idx = keyed.into_iter().map(|(_, i)| i).collect();
}
idx
}
}
/// The KPIs (UI-SPEC header), derived from the filtered view. Every row is a
/// miner that responded to a scan; a responding non-mining miner counts as
/// `not_hashing`.
pub struct Kpis {
pub total: usize,
pub hashing: usize,
pub slow: usize,
pub not_hashing: usize,
pub paused: usize,
pub total_hashrate_ths: f64,
pub total_power_w: f64,
/// Per-algorithm hashrate totals (algorithm name, total TH/s), only for
/// algorithms actually producing hashrate, ordered by total descending then
/// name. The hashrate KPI card cycles through these when more than one
/// algorithm is running in the fleet.
pub hashrate_by_algo: Vec<(String, f64)>,
}
pub fn compute_kpis(rows: &[MinerRow], view_idx: &[usize]) -> Kpis {
let mut k = Kpis {
total: view_idx.len(),
hashing: 0,
slow: 0,
not_hashing: 0,
paused: 0,
total_hashrate_ths: 0.0,
total_power_w: 0.0,
hashrate_by_algo: Vec::new(),
};
// Accumulate per-algorithm totals in an insertion-ordered list (fleets have
// a handful of algorithms at most, so a linear scan is cheaper than a map).
let mut by_algo: Vec<(String, f64)> = Vec::new();
for &i in view_idx {
let r = &rows[i];
// Bucket by the same precedence status() uses, so the KPI header can
// never disagree with a row's own status text.
match r.status() {
"slow" => k.slow += 1,
"paused" => k.paused += 1,
"hashing" => k.hashing += 1,
_ => k.not_hashing += 1,
}
k.total_hashrate_ths += r.hashrate_ths;
k.total_power_w += r.power_w;
if r.hashrate_ths > 0.0 {
// Fall back to "SHA256" when a miner didn't report its algorithm, so
// a producing miner is never dropped from the per-algorithm cycle.
let algo = if r.algorithm.is_empty() { "SHA256" } else { r.algorithm.as_str() };
match by_algo.iter_mut().find(|(a, _)| a == algo) {
Some((_, t)) => *t += r.hashrate_ths,
None => by_algo.push((algo.to_string(), r.hashrate_ths)),
}
}
}
// Stable order: largest total first, ties broken alphabetically.
by_algo.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
k.hashrate_by_algo = by_algo;
k
}
#[cfg(test)]
mod tests {
//! Offline workflow tests: feed the bench-fleet fixtures (the expected
//! hardware output) through the app's transforms and assert the produced
//! result. These need no display and run under plain `cargo test`.
use super::*;
use crate::fixtures::bench_fleet;
fn full_view() -> (Vec<MinerRow>, ViewState, Vec<usize>) {
let rows = bench_fleet();
let view = ViewState::default();
let idx = view.view(&rows);
(rows, view, idx)
}
#[test]
fn kpis_match_expected_hardware_output() {
// This does not hardcode fixture counts: it independently recomputes
// each expected KPI bucket and sum straight from the rows (via
// `status()`) and cross-checks `compute_kpis`'s output against that.
let (rows, _v, idx) = full_view();
let k = compute_kpis(&rows, &idx);
let mut exp_hashing = 0usize;
let mut exp_slow = 0usize;
let mut exp_paused = 0usize;
let mut exp_not_hashing = 0usize;
for &i in &idx {
match rows[i].status() {
"slow" => exp_slow += 1,
"paused" => exp_paused += 1,
"hashing" => exp_hashing += 1,
"not hashing" => exp_not_hashing += 1,
other => panic!("unexpected status: {other}"),
}
}
assert_eq!(k.hashing, exp_hashing, "hashing");
assert_eq!(k.slow, exp_slow, "slow");
assert_eq!(k.paused, exp_paused, "paused");
assert_eq!(k.not_hashing, exp_not_hashing, "not hashing");
let exp_hashrate: f64 = idx.iter().map(|&i| rows[i].hashrate_ths).sum();
let exp_power: f64 = idx.iter().map(|&i| rows[i].power_w).sum();
assert!((k.total_hashrate_ths - exp_hashrate).abs() < 1e-9, "hashrate {}", k.total_hashrate_ths);
assert!((k.total_power_w - exp_power).abs() < 1e-9, "power {}", k.total_power_w);
assert_eq!(k.total, k.hashing + k.slow + k.not_hashing + k.paused);
}
#[test]
fn slow_band_classification() {
assert!(is_slow(true, 60.0, 200.0));
assert!(!is_slow(true, 90.0, 100.0));
assert!(!is_slow(true, 80.0, 100.0));
assert!(!is_slow(false, 0.0, 200.0));
assert!(!is_slow(true, 1.0, 0.0));
}
#[test]
fn si_formatting() {
assert_eq!(format_si(21300.0, "W"), "21.3 kW");
assert_eq!(format_si(685e12, "H/s"), "685 TH/s");
assert_eq!(format_si(95e12, "H/s"), "95.0 TH/s");
assert_eq!(format_si(6.8e12, "H/s"), "6.8 TH/s");
assert_eq!(format_si(3250.0, "W"), "3.2 kW");
assert_eq!(format_si(0.0, "W"), "0 W");
}
#[test]
fn cell_formatting_blanks_zeroes() {
let rows = bench_fleet();
let s17 = rows.iter().find(|r| r.ip == "10.255.1.112").unwrap();
assert_eq!(Column::Hashrate.cell(s17), "");
assert_eq!(Column::Power.cell(s17), "");
assert_eq!(Column::ChipTemp.cell(s17), "");
assert_eq!(Column::Status.cell(s17), "not hashing");
let s21 = rows.iter().find(|r| r.ip == "10.255.1.149").unwrap();
// Combined hashrate cell: both known -> "<actual>/<expected>" (no spaces).
assert_eq!(Column::Hashrate.cell(s21), "60.0T/200T");
assert_eq!(Column::Power.cell(s21), "1.5 kW");
assert_eq!(Column::Status.cell(s21), "slow");
}
#[test]
fn default_view_sorts_by_ip_ascending() {
// Fixture count/IPs are not hardcoded here (round-6 fixtures are being
// extended concurrently): recompute the expected numeric-IP order
// straight from the rows instead.
let (rows, _v, idx) = full_view();
let ips: Vec<String> = idx.iter().map(|&i| rows[i].ip.clone()).collect();
assert_eq!(ips.len(), rows.len(), "the default view has no filters");
let mut expected: Vec<String> = rows.iter().map(|r| r.ip.clone()).collect();
expected.sort_by_key(|ip| ip_to_u32(ip));
assert_eq!(ips, expected, "default view should be IP-ascending (numeric)");
}
#[test]
fn sort_by_hashrate() {
let rows = bench_fleet();
let mut view = ViewState::default();
view.sort = Some((Column::Hashrate, false));
let idx = view.view(&rows);
assert_eq!(rows[idx[0]].ip, "10.255.1.167");
assert!(rows[idx[0]].hashrate_ths >= rows[idx[1]].hashrate_ths);
view.sort = Some((Column::Hashrate, true));
let idx = view.view(&rows);
assert_eq!(rows[idx[0]].hashrate_ths, 0.0);
}
#[test]
fn filter_by_status_slow() {
let rows = bench_fleet();
let mut view = ViewState::default();
let mut allowed = HashSet::new();
allowed.insert("slow".to_string());
view.filters.insert(Column::Status, ColFilter::Values(allowed));
let idx = view.view(&rows);
assert_eq!(idx.len(), 1);
assert_eq!(rows[idx[0]].ip, "10.255.1.149");
}
#[test]
fn default_visible_is_the_ui_spec_set() {
let view = ViewState::default();
let disp = view.display_columns();
// Ip first, then the 8 default columns in order.
assert_eq!(disp[0], Column::Ip);
assert_eq!(&disp[1..], &DEFAULT_VISIBLE[..]);
// hidden-by-default metrics are still selectable (present in order).
assert!(view.order.contains(&Column::Mac));
assert!(view.order.contains(&Column::Pool2Url));
assert!(!view.visible.contains(&Column::Mac));
}
#[test]
fn hiding_a_column_shifts_display_columns() {
let mut view = ViewState::default();
let before = view.display_columns();
assert!(before.contains(&Column::Power));
view.visible.remove(&Column::Power);
let after = view.display_columns();
assert!(!after.contains(&Column::Power));
assert_eq!(after[0], Column::Ip);
assert_eq!(after.len(), before.len() - 1);
let hr = after.iter().position(|c| *c == Column::Hashrate).unwrap();
assert_eq!(after[hr + 1], Column::ChipTemp);
}
#[test]
fn showing_a_hidden_metric_adds_a_column() {
let mut view = ViewState::default();
assert!(!view.display_columns().contains(&Column::Uptime));
view.visible.insert(Column::Uptime);
assert!(view.display_columns().contains(&Column::Uptime));
}
#[test]
fn reorder_with_hidden_column_keeps_all_columns() {
let mut view = ViewState::default();
view.visible.remove(&Column::Power);
// Swap Hashrate and ChipTemp in the visible display order (order-agnostic:
// find them by identity rather than by a fixed index).
let mut vis = view.display_columns();
let hr0 = vis.iter().position(|c| *c == Column::Hashrate).unwrap();
let ct0 = vis.iter().position(|c| *c == Column::ChipTemp).unwrap();
vis.swap(hr0, ct0);
view.apply_visible_reorder(&vis);
assert!(view.order.contains(&Column::Power), "hidden column dropped!");
assert_eq!(view.order.len(), ALL_COLUMNS.len());
let set: HashSet<Column> = view.order.iter().copied().collect();
assert_eq!(set.len(), ALL_COLUMNS.len());
let disp = view.display_columns();
let hr = disp.iter().position(|c| *c == Column::Hashrate).unwrap();
let ct = disp.iter().position(|c| *c == Column::ChipTemp).unwrap();
assert!(ct < hr, "reorder not applied");
assert_eq!(view.order[0], Column::Ip);
}
#[test]
fn reorder_rejects_non_permutation() {
let mut view = ViewState::default();
let before = view.order.clone();
// Ip not first -> ignored
view.apply_visible_reorder(&[Column::Hashrate, Column::Ip, Column::Power]);
assert_eq!(view.order, before);
}
/// Build a large synthetic fleet for benchmarking the transform pipeline.
#[cfg(test)]
fn synthetic_fleet(n: u32) -> Vec<MinerRow> {
(0..n)
.map(|i| {
let mut r = MinerRow {
ip: format!("10.{}.{}.{}", (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff),
hashrate_ths: (i % 200) as f64 + 0.5,
expected_ths: 200.0,
power_w: 3000.0 + (i % 500) as f64,
chip_temp_c: 55.0 + (i % 25) as f64,
fan_rpms: vec![4000.0 + (i % 900) as f64],
is_mining: i % 7 != 0,
model: format!("Model-{}", i % 12),
firmware: format!("fw-{}", i % 6),
worker: format!("blueflare.{i}"),
..Default::default()
};
r.slow = is_slow(r.is_mining, r.hashrate_ths, r.expected_ths);
r
})
.collect()
}
/// Microbenchmark: the filter+sort view pipeline over a large fleet. Run with
/// cargo test -p alkane-gui --release -- --ignored --nocapture bench_
/// Acts as a perf-regression gate in CI.
#[test]
#[ignore]
fn bench_view_pipeline() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let mut view = ViewState::default();
view.sort = Some((Column::Hashrate, false));
let iters = 200u32;
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
println!(
"bench_view_pipeline: {} rows, filter+sort view() = {:?}/op (sink={sink})",
rows.len(),
per
);
assert!(per.as_millis() < 50, "view() regressed: {per:?}/op for 5000 rows");
}
/// Microbenchmark: KPI aggregation + cell rendering over a large fleet.
#[test]
#[ignore]
fn bench_render_cells() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let view = ViewState::default();
let idx = view.view(&rows);
let cols = view.display_columns();
let iters = 50u32;
let t = Instant::now();
let mut bytes = 0usize;
for _ in 0..iters {
let _k = compute_kpis(&rows, &idx);
for &ri in &idx {
for c in &cols {
bytes += c.cell(&rows[ri]).len();
}
}
}
let per = t.elapsed() / iters;
println!("bench_render_cells: {} rows x {} cols = {:?}/full-render (bytes={bytes})", rows.len(), cols.len(), per);
assert!(per.as_millis() < 100, "cell rendering regressed: {per:?}");
}
#[test]
fn selection_survives_upsert() {
let mut rows = bench_fleet();
rows[1].selected = true;
let ip = rows[1].ip.clone();
let mut update = bench_fleet()[1].clone();
update.hashrate_ths = 12.3;
let new = update.upsert_into(&mut rows);
assert!(!new, "same IP is an update, not an insert");
let r = rows.iter().find(|r| r.ip == ip).unwrap();
assert!(r.selected, "selection preserved across upsert");
assert_eq!(r.hashrate_ths, 12.3, "data updated");
}
// ---- harness-driven additions (correctness + coverage) ----
#[test]
fn format_si_handles_zero_negative_and_nonfinite() {
assert_eq!(format_si(0.0, "W"), "0 W");
assert_eq!(format_si(-5.0, "W"), "0 W");
assert_eq!(format_si(f64::NAN, "W"), "0 W");
assert_eq!(format_si(f64::INFINITY, "H/s"), "0 H/s");
}
#[test]
fn format_si_rolls_over_at_rounding_boundary() {
// A mantissa that rounds up to 1000 must advance the prefix, never print
// a 4-digit number (spec: at most 2 digits + 1 decimal after the prefix).
assert_eq!(format_si(999.9, "W"), "1.0 kW");
assert_eq!(format_si(999_990.0, "W"), "1.0 MW");
assert_eq!(format_si(1000.0, "W"), "1.0 kW");
// [99.95, 100) rounds to 100 and drops the decimal (>=100 rule).
assert_eq!(format_si(99.95, "W"), "100 W");
assert_eq!(format_si(45.6, "W"), "45.6 W");
assert_eq!(format_si(250.0, "W"), "250 W");
}
#[test]
fn format_uptime_boundaries() {
assert_eq!(format_uptime(0), "");
assert_eq!(format_uptime(59), "59s");
assert_eq!(format_uptime(60), "1m");
assert_eq!(format_uptime(3599), "59m");
assert_eq!(format_uptime(3600), "1h 0m");
assert_eq!(format_uptime(86_399), "23h 59m");
assert_eq!(format_uptime(86_400), "1d 0h");
assert_eq!(format_uptime(90_061), "1d 1h");
}
#[test]
fn pic_locked_error_columns_render() {
// PIC (best-effort): known -> PIC/noPIC, unknown -> "?".
let pic = MinerRow { pic_present: Some(true), ..Default::default() };
let nopic = MinerRow { pic_present: Some(false), ..Default::default() };
let pic_unknown = MinerRow { pic_present: None, ..Default::default() };
assert_eq!(Column::Pic.cell(&pic), "PIC");
assert_eq!(Column::Pic.cell(&nopic), "noPIC");
assert_eq!(Column::Pic.cell(&pic_unknown), "?");
// Access column.
let locked = MinerRow { write_locked: Some(true), ..Default::default() };
let unlocked = MinerRow { write_locked: Some(false), ..Default::default() };
assert_eq!(Column::Locked.cell(&locked), "locked");
assert_eq!(Column::Locked.cell(&unlocked), "unlocked");
assert_eq!(Column::Locked.cell(&MinerRow::default()), "?");
// Error column shows only the count (blank when none), even for one.
let none = MinerRow { errors: vec![], ..Default::default() };
let one = MinerRow { errors: vec!["boom".into()], ..Default::default() };
let many = MinerRow { errors: vec!["a".into(), "b".into(), "c".into()], ..Default::default() };
assert_eq!(Column::Error.cell(&none), "");
assert_eq!(Column::Error.cell(&one), "1");
assert_eq!(Column::Error.cell(&many), "3");
}
#[test]
fn caps_any_control() {
assert!(!MinerCaps::default().any_control(), "no caps -> view-only");
assert!(MinerCaps { restart: true, ..Default::default() }.any_control());
assert!(MinerCaps { firmware_flash: true, ..Default::default() }.any_control());
}
#[test]
fn ip_column_sorts_numerically() {
// A plain string sort puts "10.255.1.10" before "10.255.1.2"; the IP
// column must order by numeric value instead.
let rows = vec![
MinerRow { ip: "10.255.1.10".into(), ..Default::default() },
MinerRow { ip: "10.255.1.2".into(), ..Default::default() },
MinerRow { ip: "10.255.1.112".into(), ..Default::default() },
MinerRow { ip: "10.255.1.9".into(), ..Default::default() },
];
let idx = ViewState::default().view(&rows); // default = Ip ascending
let order: Vec<&str> = idx.iter().map(|&i| rows[i].ip.as_str()).collect();
assert_eq!(order, ["10.255.1.2", "10.255.1.9", "10.255.1.10", "10.255.1.112"]);
}
#[test]
fn upsert_into_new_ip_inserts_and_returns_true() {
let mut rows = bench_fleet();
let n0 = rows.len();
let fresh = MinerRow { ip: "10.9.9.9".into(), ..Default::default() };
let is_new = fresh.upsert_into(&mut rows);
assert!(is_new, "a never-seen IP is an insert");
assert_eq!(rows.len(), n0 + 1);
assert!(rows.iter().any(|r| r.ip == "10.9.9.9"));
}
#[test]
fn cell_light_three_states() {
let on = MinerRow { light_flashing: Some(true), ..Default::default() };
let off = MinerRow { light_flashing: Some(false), ..Default::default() };
let unknown = MinerRow { light_flashing: None, ..Default::default() };
assert_eq!(Column::Light.cell(&on), "on");
assert_eq!(Column::Light.cell(&off), "off");
assert_eq!(Column::Light.cell(&unknown), "");
}
#[test]
fn cell_pool_slots_including_out_of_range() {
let r = MinerRow {
pools: vec![
("stratum+tcp://a:1".into(), "wA".into()),
("stratum+tcp://b:2".into(), "wB".into()),
],
..Default::default()
};
assert_eq!(Column::Pool1Url.cell(&r), "stratum+tcp://a:1");
assert_eq!(Column::Pool1Worker.cell(&r), "wA");
assert_eq!(Column::Pool2Url.cell(&r), "stratum+tcp://b:2");
assert_eq!(Column::Pool2Worker.cell(&r), "wB");
// Third pool is unconfigured -> blank, not a panic.
assert_eq!(Column::Pool3Url.cell(&r), "");
assert_eq!(Column::Pool3Worker.cell(&r), "");
}
#[test]
fn passes_filters_ands_across_columns() {
let rows = vec![
MinerRow { ip: "10.0.0.1".into(), is_mining: true, model: "A".into(), ..Default::default() },
MinerRow { ip: "10.0.0.2".into(), is_mining: true, model: "B".into(), ..Default::default() },
MinerRow { ip: "10.0.0.3".into(), is_mining: false, model: "A".into(), ..Default::default() },
];
let mut view = ViewState::default();
view.filters.insert(Column::Status, ColFilter::Values(HashSet::from(["hashing".to_string()])));
view.filters.insert(Column::Model, ColFilter::Values(HashSet::from(["A".to_string()])));
let idx = view.view(&rows);
assert_eq!(idx.len(), 1, "only the hashing AND model-A row passes");
assert_eq!(rows[idx[0]].ip, "10.0.0.1");
}
#[test]
fn passes_filters_ors_within_one_column() {
let rows = bench_fleet();
// Not hardcoded (fixture composition is changing concurrently):
// recompute the expected count straight from the rows' own status().
let expected = rows.iter().filter(|r| matches!(r.status(), "slow" | "not hashing")).count();
let mut view = ViewState::default();
view.filters.insert(
Column::Status,
ColFilter::Values(HashSet::from(["slow".to_string(), "not hashing".to_string()])),
);
let idx = view.view(&rows);
assert_eq!(idx.len(), expected);
}
#[test]
fn apply_visible_reorder_rejects_non_permutation_same_length() {
let mut view = ViewState::default();
let before = view.order.clone();
let hidden = *view
.order
.iter()
.find(|c| **c != Column::Ip && !view.visible.contains(c))
.expect("a hidden column exists by default");
let mut disp = view.display_columns(); // Ip first, correct length
disp[1] = hidden; // same length + Ip first, but no longer a permutation
view.apply_visible_reorder(&disp);
assert_eq!(view.order, before, "a same-length non-permutation must be ignored");
}
/// Microbenchmark: the DEFAULT view (Ip ascending) at 5000 rows. The existing
/// bench_view_pipeline overrides sort to Hashrate, so it never exercised the
/// default path (previously a lexical string sort).
#[test]
#[ignore]
fn bench_view_pipeline_default_sort() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let view = ViewState::default();
let iters = 200u32;
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
println!("bench_view_pipeline_default_sort: {:?}/op (sink={sink})", per);
assert!(per.as_millis() < 60, "default (Ip) sort regressed: {per:?}/op");
}
/// Microbenchmark: sort by every column once, at 5000 rows. Guards the
/// decorate-sort-undecorate path (string columns must not re-allocate keys
/// per comparison).
#[test]
#[ignore]
fn bench_sort_by_each_column() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let iters = 10u32;
let mut worst = std::time::Duration::ZERO;
for &col in ALL_COLUMNS.iter() {
let mut view = ViewState::default();
view.sort = Some((col, false));
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
if per > worst {
worst = per;
}
assert!(per.as_millis() < 120, "{col:?} sort regressed: {per:?}/op (sink={sink})");
}
println!("bench_sort_by_each_column: worst column = {:?}/op", worst);
}
/// Microbenchmark: filtered view (one selective predicate) at 5000 rows.
#[test]
#[ignore]
fn bench_view_pipeline_with_filter() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let mut view = ViewState::default();
view.filters.insert(Column::Model, ColFilter::Values(HashSet::from(["Model-3".to_string()])));
view.sort = Some((Column::Hashrate, false));
let iters = 200u32;
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
println!("bench_view_pipeline_with_filter: {sink} avg matches, {:?}/op", per);
assert!(per.as_millis() < 60, "filtered view() regressed: {per:?}/op");
}
/// Microbenchmark: cold-start fleet population via upsert_into (the O(n) scan
/// per insert; documents the quadratic worst case).
#[test]
#[ignore]
fn bench_upsert_cold_start_population() {
use std::time::Instant;
let n = 3000u32;
let fresh = synthetic_fleet(n);
let t = Instant::now();
let mut rows: Vec<MinerRow> = Vec::new();
for r in fresh {
r.upsert_into(&mut rows);
}
let elapsed = t.elapsed();
println!("bench_upsert_cold_start_population: {n} rows cold-start = {:?}", elapsed);
assert!(elapsed.as_millis() < 2000, "cold-start upsert regressed: {elapsed:?} for {n} rows");
}
// ---- Excel-style column filters (round 3) ----
#[test]
fn text_filter_operators_are_case_insensitive() {
let r = MinerRow { firmware: "WMOS H616".into(), ..Default::default() };
let c = Column::Firmware;
let t = |op, needle: &str| ColFilter::Text { op, needle: needle.into() }.matches(c, &r);
assert!(t(TextOp::Contains, "wmos"));
assert!(!t(TextOp::Contains, "vnish"));
assert!(!t(TextOp::NotContains, "wmos"));
assert!(t(TextOp::NotContains, "vnish"));
assert!(t(TextOp::BeginsWith, "WMOS"));
assert!(!t(TextOp::BeginsWith, "616"));
assert!(t(TextOp::EndsWith, "h616"));
assert!(t(TextOp::Equals, "wmos h616"));
assert!(!t(TextOp::Equals, "wmos"));
}
#[test]
fn numeric_filter_operators() {
let r = MinerRow { hashrate_ths: 100.0, is_mining: true, ..Default::default() };
let c = Column::Hashrate;
let n = |op, a: f64, b: f64| ColFilter::Num { op, a, b }.matches(c, &r);
assert!(n(NumOp::Gt, 50.0, 0.0));
assert!(!n(NumOp::Gt, 150.0, 0.0));
assert!(n(NumOp::Ge, 100.0, 0.0));
assert!(n(NumOp::Lt, 150.0, 0.0));
assert!(n(NumOp::Le, 100.0, 0.0));
assert!(n(NumOp::Eq, 100.0, 0.0));
assert!(n(NumOp::Ne, 99.0, 0.0));
assert!(n(NumOp::Between, 90.0, 110.0));
assert!(n(NumOp::Between, 110.0, 90.0), "bounds are order-agnostic");
assert!(!n(NumOp::Between, 0.0, 50.0));
}
#[test]
fn num_value_none_for_text_and_blank() {
let r = MinerRow { firmware: "x".into(), efficiency: 0.0, ..Default::default() };
assert_eq!(Column::Firmware.num_value(&r), None, "text column");
assert_eq!(Column::Ip.num_value(&r), None, "IP is text, not numeric");
assert_eq!(Column::Efficiency.num_value(&r), None, "blank numeric -> None");
let r2 = MinerRow { hashrate_ths: 42.0, ..Default::default() };
assert_eq!(Column::Hashrate.num_value(&r2), Some(42.0));
}
#[test]
fn caps_intersection_is_the_common_actions() {
let full = MinerCaps {
fault_light: true,
restart: true,
pause: true,
resume: true,
power_limit: true,
tuning: true,
firmware_flash: true,
};
let idle = MinerCaps { fault_light: true, restart: true, ..Default::default() };
// Two full miners keep every action.
assert_eq!(MinerCaps::intersect_all([full, full]), full);
// A full + idle mix keeps only what both support.
assert_eq!(MinerCaps::intersect_all([full, idle]), idle);
// A single miner's caps are its own.
assert_eq!(MinerCaps::intersect_all([full]), full);
// Empty selection -> nothing common.
assert_eq!(MinerCaps::intersect_all([]), MinerCaps::default());
assert!(MinerCaps::default().is_empty());
assert!(!full.is_empty());
}
#[test]
fn numeric_filter_excludes_blank_cells() {
// A blank-displaying value-type cell (absent reading stored as 0.0) must
// not match a numeric predicate -- it has no value to compare.
let blank = MinerRow { hashrate_ths: 0.0, chip_temp_c: 0.0, power_w: 0.0, is_mining: false, ..Default::default() };
assert_eq!(Column::Hashrate.num_value(&blank), None);
assert_eq!(Column::ChipTemp.num_value(&blank), None);
assert_eq!(Column::Power.num_value(&blank), None);
// "<= 50" and "<= 1000" must NOT match a miner with no temp / power.
assert!(!ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 }.matches(Column::ChipTemp, &blank));
assert!(!ColFilter::Num { op: NumOp::Lt, a: 1000.0, b: 0.0 }.matches(Column::Power, &blank));
// A real reading still matches.
let live = MinerRow { chip_temp_c: 45.0, is_mining: true, ..Default::default() };
assert!(ColFilter::Num { op: NumOp::Le, a: 50.0, b: 0.0 }.matches(Column::ChipTemp, &live));
}
// ---- round 6: offline/paused rows, combined columns, fan RPMs, segments ----
#[test]
fn format_fan_rpm_boundaries() {
assert_eq!(format_fan_rpm(0.0), "-");
assert_eq!(format_fan_rpm(-100.0), "-");
assert_eq!(format_fan_rpm(f64::NAN), "-");
assert_eq!(format_fan_rpm(f64::INFINITY), "-");
assert_eq!(format_fan_rpm(950.0), "950");
assert_eq!(format_fan_rpm(4200.0), "4.2k");
// Shares format_si's rounding-rollover and >=100 rules.
assert_eq!(format_fan_rpm(99.95), "100");
assert_eq!(format_fan_rpm(999.9), "1.0k");
}
#[test]
fn combined_cell_all_four_cases() {
let neither = MinerRow::default();
assert_eq!(Column::Hashrate.cell(&neither), "", "both unknown -> blank");
assert_eq!(Column::Hashboards.cell(&neither), "");
assert_eq!(Column::TotalChips.cell(&neither), "");
let actual_only = MinerRow {
hashrate_ths: 60.0,
hashboards: Some(3),
total_chips: Some(210),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&actual_only), "60.0T", "only actual -> bare actual");
assert_eq!(Column::Hashboards.cell(&actual_only), "3");
assert_eq!(Column::TotalChips.cell(&actual_only), "210");
let expected_only = MinerRow {
expected_ths: 200.0,
expected_hashboards: Some(3),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&expected_only), "-/200T", "only expected -> '-/<expected>'");
assert_eq!(Column::Hashboards.cell(&expected_only), "- / 3");
assert_eq!(Column::TotalChips.cell(&expected_only), "- / 228");
let both = MinerRow {
hashrate_ths: 60.0,
expected_ths: 200.0,
hashboards: Some(3),
expected_hashboards: Some(3),
total_chips: Some(190),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.cell(&both), "60.0T/200T", "both known -> '<actual>/<expected>'");
assert_eq!(Column::Hashboards.cell(&both), "3 / 3");
assert_eq!(Column::TotalChips.cell(&both), "190 / 228");
}
#[test]
fn num_value_none_when_only_expected_known() {
// A numeric filter must never match a row that only has an expected
// value -- there is no actual reading to compare.
let expected_only = MinerRow {
expected_ths: 200.0,
expected_hashboards: Some(3),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.num_value(&expected_only), None);
assert_eq!(Column::Hashboards.num_value(&expected_only), None);
assert_eq!(Column::TotalChips.num_value(&expected_only), None);
let both = MinerRow {
hashrate_ths: 60.0,
expected_ths: 200.0,
hashboards: Some(3),
expected_hashboards: Some(3),
total_chips: Some(190),
expected_chips: Some(228),
..Default::default()
};
assert_eq!(Column::Hashrate.num_value(&both), Some(60.0));
assert_eq!(Column::Hashboards.num_value(&both), Some(3.0));
assert_eq!(Column::TotalChips.num_value(&both), Some(190.0));
}
#[test]
fn cooling_column_joins_fan_rpms_and_sorts_by_min() {
let r = MinerRow { fan_rpms: vec![4200.0, 3990.0, 4500.0], ..Default::default() };
assert_eq!(Column::Cooling.cell(&r), "4.2k/4.0k/4.5k");
assert_eq!(Column::Cooling.num_value(&r), Some(3990.0));
let none = MinerRow::default();
assert_eq!(Column::Cooling.cell(&none), "");
assert_eq!(Column::Cooling.num_value(&none), None);
}
#[test]
fn segments_round_trip_and_plain_passthrough() {
let segs = vec![(Some((255u8, 0u8, 0u8)), "Err".to_string()), (None, ": offline".to_string())];
let encoded = encode_segments(&segs);
assert_eq!(encoded, "FF0000\u{1e}Err\u{1f}\u{1e}: offline");
assert_eq!(decode_segments_plain(&encoded), "Err: offline");
// A plain string with no segment markers round-trips unchanged.
assert_eq!(decode_segments_plain("10.255.1.9"), "10.255.1.9");
assert_eq!(decode_segments_plain(""), "");
}
#[test]
fn actual_expected_ratio_handles_unknown_expected() {
// 50/200 = 0.25 is exactly representable, so this is a safe exact
// comparison (unlike e.g. 60/200, whose nearest-double result is not
// guaranteed to bit-match a decimal literal).
assert_eq!(actual_expected_ratio(50.0, 200.0), Some(0.25));
assert_eq!(actual_expected_ratio(60.0, 0.0), None);
assert_eq!(actual_expected_ratio(0.0, 0.0), None);
}
#[test]
fn status_precedence() {
// A plain default row is a reachable, non-mining miner.
let default_row = MinerRow { ..Default::default() };
assert_eq!(default_row.status(), "not hashing");
let paused = MinerRow { paused: true, ..Default::default() };
assert_eq!(paused.status(), "paused");
let hashing = MinerRow { is_mining: true, ..Default::default() };
assert_eq!(hashing.status(), "hashing");
// slow outranks paused (and hashing).
let slow_and_paused = MinerRow { slow: true, paused: true, is_mining: true, ..Default::default() };
assert_eq!(slow_and_paused.status(), "slow");
// paused outranks hashing.
let paused_but_mining = MinerRow { paused: true, is_mining: true, ..Default::default() };
assert_eq!(paused_but_mining.status(), "paused");
}
#[test]
fn is_paused_detection() {
assert!(is_paused("Paused", false));
assert!(is_paused("PAUSED (manual)", false));
assert!(!is_paused("Paused", true), "mining overrides an even stale 'paused' state string");
assert!(!is_paused("Mining", false));
assert!(!is_paused("", false));
}
#[test]
fn kpis_bucket_by_status_not_raw_flags() {
// compute_kpis must bucket by status()'s precedence, so a row's KPI
// bucket can never disagree with its status text.
let rows = vec![
MinerRow { slow: true, paused: true, is_mining: true, ..Default::default() }, // slow wins
MinerRow { paused: true, is_mining: true, ..Default::default() }, // paused over hashing
MinerRow { is_mining: true, ..Default::default() }, // hashing
MinerRow { ..Default::default() }, // not hashing
];
let idx: Vec<usize> = (0..rows.len()).collect();
let k = compute_kpis(&rows, &idx);
assert_eq!(k.slow, 1);
assert_eq!(k.paused, 1, "paused outranks the mining flag");
assert_eq!(k.hashing, 1);
assert_eq!(k.not_hashing, 1);
assert_eq!(k.total, 4);
}
#[test]
fn flash_confirmed_requires_exact_word() {
assert!(flash_confirmed("FLASH"));
assert!(flash_confirmed(" FLASH "), "surrounding whitespace is trimmed");
assert!(!flash_confirmed("flash"), "case-sensitive");
assert!(!flash_confirmed("Flash"));
assert!(!flash_confirmed("FLASHING"), "not a prefix match");
assert!(!flash_confirmed("FLASH NOW"));
assert!(!flash_confirmed(""));
}
}