Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77237023e3 | ||
|
|
fc573f075a | ||
|
|
1c364d4ff1 | ||
|
|
d54bd6473f |
@@ -38,6 +38,9 @@ jobs:
|
|||||||
- name: Benchmark history checks
|
- name: Benchmark history checks
|
||||||
run: python3 ci/test-bench-history.py
|
run: python3 ci/test-bench-history.py
|
||||||
|
|
||||||
|
- name: Benchmark suite checks
|
||||||
|
run: python3 ci/test-bench-badge.py
|
||||||
|
|
||||||
- name: Install build dependencies
|
- name: Install build dependencies
|
||||||
run: |
|
run: |
|
||||||
apt-get update -qq
|
apt-get update -qq
|
||||||
@@ -89,12 +92,12 @@ jobs:
|
|||||||
|
|
||||||
- name: Microbenchmarks
|
- name: Microbenchmarks
|
||||||
run: |
|
run: |
|
||||||
# Capture the bench stdout for the weighted-average delta badge (round 19
|
# Require every declared benchmark before publishing history or a release.
|
||||||
# #1) while keeping the step a hard gate: pipefail preserves cargo's exit
|
|
||||||
# code (each bench asserts its own absolute ceiling) even through tee.
|
|
||||||
set -o pipefail
|
set -o pipefail
|
||||||
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
|
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
|
||||||
| tee bench-current.txt
|
| tee bench-current.txt
|
||||||
|
python3 ci/bench-badge.py --current bench-current.txt \
|
||||||
|
--baseline badges/bench-baseline.json --no-write
|
||||||
|
|
||||||
- name: Record private benchmark history
|
- name: Record private benchmark history
|
||||||
env:
|
env:
|
||||||
|
|||||||
Generated
+1
@@ -75,6 +75,7 @@ dependencies = [
|
|||||||
"alkane-artifacts",
|
"alkane-artifacts",
|
||||||
"alkane-core",
|
"alkane-core",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+40
-38
@@ -1,27 +1,8 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Compute the weighted-average microbenchmark delta versus the previous release.
|
"""Check the Toolkit benchmark suite and compare it with the prior release."""
|
||||||
|
|
||||||
Reads the captured stdout of `cargo test ... --ignored --nocapture bench_` (whose
|
|
||||||
timings are Rust `Duration` Debug strings: "12.3ms", "512us"/"512µs", "840ns",
|
|
||||||
"1.2s"), compares each bench to a committed baseline of the previous release's
|
|
||||||
numbers, and prints the time-weighted average change as a signed percentage:
|
|
||||||
|
|
||||||
(sum(current) / sum(baseline) - 1) * 100 over benches present in both
|
|
||||||
|
|
||||||
Weighting by duration means the slow benches dominate, so the number tracks
|
|
||||||
overall wall-time change rather than giving a tiny bench equal say. Then the
|
|
||||||
baseline is rewritten with the current numbers, so the next release compares
|
|
||||||
against this one ("the previous commit").
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
bench-badge.py --current bench-current.txt --baseline badges/bench-baseline.json
|
|
||||||
|
|
||||||
Prints the delta as a plain number (e.g. "-3.2", or "NEW" when there is no
|
|
||||||
usable baseline) to stdout. The baseline JSON lives under badges/ so committing
|
|
||||||
it back does not trip compute-version.sh's path-based release bump.
|
|
||||||
"""
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -29,9 +10,17 @@ import sys
|
|||||||
# A Duration Debug token: a number immediately followed by a time unit, with the
|
# A Duration Debug token: a number immediately followed by a time unit, with the
|
||||||
# multi-char units listed before the bare "s" so alternation prefers them. The
|
# multi-char units listed before the bare "s" so alternation prefers them. The
|
||||||
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
|
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
|
||||||
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|µs|us|ms|s)(?![a-zA-Z])")
|
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|\u00b5s|us|ms|s)(?![a-zA-Z])")
|
||||||
_UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9}
|
_UNIT_NS = {"ns": 1.0, "us": 1e3, "\u00b5s": 1e3, "ms": 1e6, "s": 1e9}
|
||||||
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
|
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
|
||||||
|
EXPECTED_BENCHES = {
|
||||||
|
"bench_verify_artifact", "bench_naming_transforms",
|
||||||
|
"bench_parse_line_near_max_addrs", "bench_parse_targets_many_ranges_near_cap",
|
||||||
|
"bench_targets_to_cidrs_large_range", "bench_view_pipeline",
|
||||||
|
"bench_render_cells", "bench_health_diagnostics",
|
||||||
|
"bench_view_pipeline_default_sort", "bench_sort_by_each_column",
|
||||||
|
"bench_view_pipeline_with_filter", "bench_upsert_cold_start_population",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def parse_bench(text: str) -> dict:
|
def parse_bench(text: str) -> dict:
|
||||||
@@ -44,12 +33,21 @@ def parse_bench(text: str) -> dict:
|
|||||||
continue
|
continue
|
||||||
durs = _DUR.findall(line)
|
durs = _DUR.findall(line)
|
||||||
if not durs:
|
if not durs:
|
||||||
continue
|
raise ValueError(f"missing timing for {m.group(1)}")
|
||||||
val, unit = durs[-1]
|
val, unit = durs[-1]
|
||||||
out[m.group(1)] = float(val) * _UNIT_NS[unit]
|
elapsed = float(val) * _UNIT_NS[unit]
|
||||||
|
if m.group(1) in out or not math.isfinite(elapsed) or elapsed <= 0:
|
||||||
|
raise ValueError(f"duplicate or invalid timing for {m.group(1)}")
|
||||||
|
out[m.group(1)] = elapsed
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def require_suite(results: dict) -> dict:
|
||||||
|
if results.keys() != EXPECTED_BENCHES:
|
||||||
|
raise ValueError("microbenchmark results differ from the declared suite")
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
ap = argparse.ArgumentParser()
|
ap = argparse.ArgumentParser()
|
||||||
ap.add_argument("--current", required=True, help="captured bench stdout")
|
ap.add_argument("--current", required=True, help="captured bench stdout")
|
||||||
@@ -59,25 +57,29 @@ def main() -> int:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
with open(args.current, encoding="utf-8") as fh:
|
with open(args.current, encoding="utf-8") as fh:
|
||||||
current = parse_bench(fh.read())
|
current = require_suite(parse_bench(fh.read()))
|
||||||
except OSError as e:
|
except (OSError, ValueError) as e:
|
||||||
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
|
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
|
||||||
print("NEW")
|
return 1
|
||||||
return 0
|
|
||||||
|
|
||||||
if not current:
|
|
||||||
print("bench-badge: no bench lines parsed from current results", file=sys.stderr)
|
|
||||||
print("NEW")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
baseline = {}
|
baseline = {}
|
||||||
try:
|
try:
|
||||||
with open(args.baseline, encoding="utf-8") as fh:
|
with open(args.baseline, encoding="utf-8") as fh:
|
||||||
baseline = {k: float(v) for k, v in json.load(fh).items()}
|
baseline = json.load(fh)
|
||||||
except (OSError, ValueError):
|
except FileNotFoundError:
|
||||||
baseline = {}
|
pass
|
||||||
|
except (OSError, ValueError) as e:
|
||||||
|
print(f"bench-badge: invalid baseline: {e}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
if (not isinstance(baseline, dict)
|
||||||
|
or not set(baseline).issubset(current)
|
||||||
|
or any(not isinstance(value, (int, float)) or isinstance(value, bool)
|
||||||
|
or not math.isfinite(value) or value <= 0
|
||||||
|
for value in baseline.values())):
|
||||||
|
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
common = [k for k in current if k in baseline and baseline[k] > 0]
|
common = list(baseline)
|
||||||
if common:
|
if common:
|
||||||
sum_new = sum(current[k] for k in common)
|
sum_new = sum(current[k] for k in common)
|
||||||
sum_old = sum(baseline[k] for k in common)
|
sum_old = sum(baseline[k] for k in common)
|
||||||
|
|||||||
+2
-2
@@ -141,8 +141,8 @@ def main() -> None:
|
|||||||
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
||||||
print(f"Loaded {len(baseline)} prior benchmark measurements")
|
print(f"Loaded {len(baseline)} prior benchmark measurements")
|
||||||
return
|
return
|
||||||
metrics = {"bench_ns_per_op": bench_badge.parse_bench(
|
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
|
||||||
Path("bench-current.txt").read_text()), "bench_host": benchmark_host()}
|
Path("bench-current.txt").read_text())), "bench_host": benchmark_host()}
|
||||||
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
index = updated_index(index, sha, metrics, timestamp)
|
index = updated_index(index, sha, metrics, timestamp)
|
||||||
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
|
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
|
||||||
|
|||||||
+13
-12
@@ -2,10 +2,11 @@
|
|||||||
# Measure line coverage from BOTH the unit tests AND the headless UI self-test.
|
# Measure line coverage from BOTH the unit tests AND the headless UI self-test.
|
||||||
#
|
#
|
||||||
# The self-test (ALKANE_SELFTEST=1) builds the real wxWidgets table, renders every
|
# The self-test (ALKANE_SELFTEST=1) builds the real wxWidgets table, renders every
|
||||||
# fixture through the real widgets, and checks each cell against the model -- it
|
# fixture through the real widgets, and checks each cell against the model.
|
||||||
# exercises most of ui.rs. Because it runs as a separate binary invocation, a plain
|
# It covers the fixture-rendering path, while interactive event handlers need
|
||||||
# `cargo llvm-cov` (which only runs the #[test]s) never counts it, so ui.rs shows
|
# separate tests. Because it runs as a separate binary invocation, a plain
|
||||||
# ~4% even though it is integration-tested. This combines both runs' coverage.
|
# `cargo llvm-cov` (which only runs the #[test]s) never counts it. This
|
||||||
|
# combines both runs' coverage.
|
||||||
#
|
#
|
||||||
# Usage: ci/coverage.sh [extra `cargo llvm-cov report` args, e.g. --summary-only]
|
# Usage: ci/coverage.sh [extra `cargo llvm-cov report` args, e.g. --summary-only]
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -16,8 +17,12 @@ export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$HOME/.cache/wx-3.3.3-linux/bin/wx-conf
|
|||||||
# default; override with CARGO_LLVM_COV_FLAGS if you need something else.
|
# default; override with CARGO_LLVM_COV_FLAGS if you need something else.
|
||||||
read -ra CARGO_FLAGS <<<"${CARGO_LLVM_COV_FLAGS:---offline}"
|
read -ra CARGO_FLAGS <<<"${CARGO_LLVM_COV_FLAGS:---offline}"
|
||||||
|
|
||||||
# A display for the self-test's real widgets.
|
# A display is required for the self-test; skipping it would publish an
|
||||||
need_xvfb() { command -v xvfb-run >/dev/null 2>&1; }
|
# incomplete coverage number as if the measured test set had run.
|
||||||
|
if ! command -v xvfb-run >/dev/null 2>&1; then
|
||||||
|
echo "coverage.sh: xvfb-run is required for the UI self-test" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
cargo llvm-cov clean --workspace
|
cargo llvm-cov clean --workspace
|
||||||
|
|
||||||
@@ -27,12 +32,8 @@ cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" \
|
|||||||
-p alkane-artifacts -p alkane-flash -p alkane-cli
|
-p alkane-artifacts -p alkane-flash -p alkane-cli
|
||||||
|
|
||||||
# 2. Headless UI self-test, under the same instrumentation, its coverage appended.
|
# 2. Headless UI self-test, under the same instrumentation, its coverage appended.
|
||||||
if need_xvfb; then
|
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
|
||||||
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
|
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
|
||||||
cargo llvm-cov run --no-report "${CARGO_FLAGS[@]}" --bin alkane-toolkit
|
|
||||||
else
|
|
||||||
echo "coverage.sh: xvfb-run not found; skipping the self-test run (unit tests only)" >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 3. Merged report, our source only (vendored asic-rs + the patched wx-rs bridge
|
# 3. Merged report, our source only (vendored asic-rs + the patched wx-rs bridge
|
||||||
# are out of scope).
|
# are out of scope).
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
|
"""Check that every Toolkit benchmark contributes to the release badge."""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
spec = importlib.util.spec_from_file_location("bench_badge", ROOT / "ci/bench-badge.py")
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
badge = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(badge)
|
||||||
|
|
||||||
|
|
||||||
|
class BenchBadgeTests(unittest.TestCase):
|
||||||
|
def test_declared_suite_matches_rust_benchmarks(self):
|
||||||
|
names = set()
|
||||||
|
for directory in (ROOT / "crates/alkane-gui/src", ROOT / "crates/alkane-artifacts/src"):
|
||||||
|
for path in directory.rglob("*.rs"):
|
||||||
|
names.update(re.findall(
|
||||||
|
r'#\[test\]\s*#\[ignore(?:\s*=\s*"[^"]*")?\]\s*'
|
||||||
|
r'fn (bench_[A-Za-z0-9_]+)\s*\(', path.read_text()))
|
||||||
|
self.assertEqual(names, badge.EXPECTED_BENCHES)
|
||||||
|
|
||||||
|
def test_incomplete_duplicate_and_malformed_results_fail(self):
|
||||||
|
lines = [f"test tests::{name} ... {name}: 10ms/op"
|
||||||
|
for name in sorted(badge.EXPECTED_BENCHES)]
|
||||||
|
values = badge.require_suite(badge.parse_bench("\n".join(lines)))
|
||||||
|
self.assertEqual(len(values), 12)
|
||||||
|
with self.assertRaisesRegex(ValueError, "declared suite"):
|
||||||
|
badge.require_suite(badge.parse_bench("\n".join(lines[:-1])))
|
||||||
|
with self.assertRaisesRegex(ValueError, "duplicate"):
|
||||||
|
badge.parse_bench("\n".join(lines + [lines[0]]))
|
||||||
|
with self.assertRaisesRegex(ValueError, "missing timing"):
|
||||||
|
badge.parse_bench(lines[0].replace("10ms/op", "missing"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -9,3 +9,4 @@ alkane-core = { path = "../alkane-core" }
|
|||||||
alkane-artifacts = { path = "../alkane-artifacts" }
|
alkane-artifacts = { path = "../alkane-artifacts" }
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
|
tempfile = "3"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
use alkane_artifacts::VerifiedArtifact;
|
use alkane_artifacts::VerifiedArtifact;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
use std::io::{Read, Seek, SeekFrom, Write};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
pub struct PartitionSpec {
|
pub struct PartitionSpec {
|
||||||
@@ -90,6 +90,34 @@ fn digest_bytes(hex: &str) -> Result<[u8; 32], FlashError> {
|
|||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn stage_verified_artifact(
|
||||||
|
artifact: &mut VerifiedArtifact,
|
||||||
|
size: u64,
|
||||||
|
expected: [u8; 32],
|
||||||
|
) -> Result<std::fs::File, FlashError> {
|
||||||
|
let mut staged = tempfile::tempfile().map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
||||||
|
artifact
|
||||||
|
.reader()
|
||||||
|
.seek(SeekFrom::Start(0))
|
||||||
|
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
||||||
|
let mut source = DigestReader {
|
||||||
|
inner: artifact.reader(),
|
||||||
|
remaining: size,
|
||||||
|
digest: Sha256::new(),
|
||||||
|
};
|
||||||
|
std::io::copy(&mut source, &mut staged).map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
||||||
|
if source.remaining != 0 || <[u8; 32]>::from(source.digest.finalize()) != expected {
|
||||||
|
return Err(FlashError::ArtifactChanged);
|
||||||
|
}
|
||||||
|
staged
|
||||||
|
.flush()
|
||||||
|
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
||||||
|
staged
|
||||||
|
.seek(SeekFrom::Start(0))
|
||||||
|
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
||||||
|
Ok(staged)
|
||||||
|
}
|
||||||
|
|
||||||
struct DigestReader<'a> {
|
struct DigestReader<'a> {
|
||||||
inner: &'a mut dyn Read,
|
inner: &'a mut dyn Read,
|
||||||
remaining: u64,
|
remaining: u64,
|
||||||
@@ -145,6 +173,10 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
|
|||||||
artifact
|
artifact
|
||||||
.revalidate()
|
.revalidate()
|
||||||
.map_err(|_| FlashError::ArtifactChanged)?;
|
.map_err(|_| FlashError::ArtifactChanged)?;
|
||||||
|
let expected = digest_bytes(&artifact.record().sha256)?;
|
||||||
|
// The source path may change while backup or transport I/O runs. Copy and
|
||||||
|
// verify it before any device write; the anonymous file is removed on drop.
|
||||||
|
let mut staged = stage_verified_artifact(artifact, size, expected)?;
|
||||||
let backup = writer
|
let backup = writer
|
||||||
.backup(partition)
|
.backup(partition)
|
||||||
.map_err(|e| FlashError::Write(e.to_string()))?;
|
.map_err(|e| FlashError::Write(e.to_string()))?;
|
||||||
@@ -154,13 +186,8 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
|
|||||||
{
|
{
|
||||||
return Err(FlashError::BackupIncomplete);
|
return Err(FlashError::BackupIncomplete);
|
||||||
}
|
}
|
||||||
let expected = digest_bytes(&artifact.record().sha256)?;
|
|
||||||
artifact
|
|
||||||
.reader()
|
|
||||||
.seek(SeekFrom::Start(0))
|
|
||||||
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
|
|
||||||
let mut stream = DigestReader {
|
let mut stream = DigestReader {
|
||||||
inner: artifact.reader(),
|
inner: &mut staged,
|
||||||
remaining: size,
|
remaining: size,
|
||||||
digest: Sha256::new(),
|
digest: Sha256::new(),
|
||||||
};
|
};
|
||||||
@@ -203,6 +230,7 @@ mod tests {
|
|||||||
max_read: Option<u64>,
|
max_read: Option<u64>,
|
||||||
writes: usize,
|
writes: usize,
|
||||||
contents: Vec<u8>,
|
contents: Vec<u8>,
|
||||||
|
mutate_source_on_write: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Writer for MockWriter {
|
impl Writer for MockWriter {
|
||||||
@@ -231,6 +259,9 @@ mod tests {
|
|||||||
_: u64,
|
_: u64,
|
||||||
) -> Result<(), Self::Error> {
|
) -> Result<(), Self::Error> {
|
||||||
self.writes += 1;
|
self.writes += 1;
|
||||||
|
if let Some(path) = &self.mutate_source_on_write {
|
||||||
|
std::fs::write(path, b"PK\x03\x04changed").map_err(|_| "mutation failed")?;
|
||||||
|
}
|
||||||
if let Some(limit) = self.max_read {
|
if let Some(limit) = self.max_read {
|
||||||
image
|
image
|
||||||
.take(limit)
|
.take(limit)
|
||||||
@@ -285,6 +316,7 @@ mod tests {
|
|||||||
max_read: None,
|
max_read: None,
|
||||||
writes: 0,
|
writes: 0,
|
||||||
contents: Vec::new(),
|
contents: Vec::new(),
|
||||||
|
mutate_source_on_write: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,4 +427,20 @@ mod tests {
|
|||||||
assert_eq!(writer.writes, 1);
|
assert_eq!(writer.writes, 1);
|
||||||
std::fs::remove_file(path).unwrap();
|
std::fs::remove_file(path).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn writes_verified_snapshot_when_source_changes_during_transport() {
|
||||||
|
let (path, mut image) = artifact("mutated-during-write");
|
||||||
|
let mut writer = writer();
|
||||||
|
writer.mutate_source_on_write = Some(path.clone());
|
||||||
|
let mut readback = MockReadback {
|
||||||
|
channel: "serial",
|
||||||
|
digest: digest_bytes(SHA).unwrap(),
|
||||||
|
};
|
||||||
|
let receipt = write_verified(&partition(), &mut image, &mut writer, &mut readback).unwrap();
|
||||||
|
assert_eq!(receipt.image_sha256, digest_bytes(SHA).unwrap());
|
||||||
|
assert_eq!(writer.contents, IMAGE);
|
||||||
|
assert_eq!(std::fs::read(&path).unwrap(), b"PK\x03\x04changed");
|
||||||
|
std::fs::remove_file(path).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2604,6 +2604,38 @@ mod tests {
|
|||||||
assert!(per.as_millis() < 100, "cell rendering regressed: {per:?}");
|
assert!(per.as_millis() < 100, "cell rendering regressed: {per:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Microbenchmark: component health scores and operator-facing diagnostics
|
||||||
|
/// recomputed when scan results refresh the table.
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn bench_health_diagnostics() {
|
||||||
|
use std::hint::black_box;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
let rows = bench_fleet();
|
||||||
|
let iters = 1000u32;
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut sink = 0usize;
|
||||||
|
for _ in 0..iters {
|
||||||
|
for row in &rows {
|
||||||
|
for facet in [
|
||||||
|
HealthFacet::Overall,
|
||||||
|
HealthFacet::Power,
|
||||||
|
HealthFacet::Fans,
|
||||||
|
HealthFacet::Boards,
|
||||||
|
] {
|
||||||
|
sink += black_box(row.health_score(facet)) as usize;
|
||||||
|
}
|
||||||
|
sink += row.health_summary().len();
|
||||||
|
sink += row.health_tooltips(4, 3).iter().map(String::len).sum::<usize>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
black_box(sink);
|
||||||
|
let per = start.elapsed() / iters;
|
||||||
|
println!("bench_health_diagnostics: {} rows = {:?}/refresh", rows.len(), per);
|
||||||
|
assert!(per.as_millis() < 20, "health diagnostics regressed: {per:?}/refresh");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn selection_survives_upsert() {
|
fn selection_survives_upsert() {
|
||||||
let mut rows = bench_fleet();
|
let mut rows = bench_fleet();
|
||||||
|
|||||||
@@ -58,7 +58,11 @@ pub fn firmware_family(raw: &str) -> (String, Option<String>) {
|
|||||||
// Vendor prefixes asic-rs prepends on stock-firmware family strings, matched
|
// Vendor prefixes asic-rs prepends on stock-firmware family strings, matched
|
||||||
// case-insensitively.
|
// case-insensitively.
|
||||||
for vendor in ["AntMiner", "WhatsMiner"] {
|
for vendor in ["AntMiner", "WhatsMiner"] {
|
||||||
if trimmed.len() > vendor.len() && trimmed[..vendor.len()].eq_ignore_ascii_case(vendor) {
|
if trimmed.len() > vendor.len()
|
||||||
|
&& trimmed
|
||||||
|
.get(..vendor.len())
|
||||||
|
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(vendor))
|
||||||
|
{
|
||||||
let rest = trimmed[vendor.len()..].trim();
|
let rest = trimmed[vendor.len()..].trim();
|
||||||
if !rest.is_empty() {
|
if !rest.is_empty() {
|
||||||
return (rest.to_string(), Some(vendor.to_string()));
|
return (rest.to_string(), Some(vendor.to_string()));
|
||||||
@@ -477,6 +481,35 @@ mod tests {
|
|||||||
assert_eq!(firmware_family("Braiins"), ("Braiins".to_string(), None));
|
assert_eq!(firmware_family("Braiins"), ("Braiins".to_string(), None));
|
||||||
// A bare vendor word with nothing after it is left as-is (not emptied).
|
// A bare vendor word with nothing after it is left as-is (not emptied).
|
||||||
assert_eq!(firmware_family("AntMiner"), ("AntMiner".to_string(), None));
|
assert_eq!(firmware_family("AntMiner"), ("AntMiner".to_string(), None));
|
||||||
|
// Firmware strings arrive from the network and may contain UTF-8 at
|
||||||
|
// the byte position used to check a vendor prefix.
|
||||||
|
let non_ascii = "AntMine\u{e9} Stock";
|
||||||
|
assert_eq!(firmware_family(non_ascii), (non_ascii.to_string(), None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "microbenchmark"]
|
||||||
|
fn bench_naming_transforms() {
|
||||||
|
let cases = [
|
||||||
|
("Antminer", "S19jPro", "AntMiner Stock", "Xilinx"),
|
||||||
|
("Antminer", "S21Pro", "VNish", "CVITek"),
|
||||||
|
("Whatsminer", "M30SPlusVE40", "WhatsMiner Stock", "H616"),
|
||||||
|
("Whatsminer", "M50SPlusPlusVK30", "Braiins", "H6"),
|
||||||
|
];
|
||||||
|
let iterations = 20_000;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
for index in 0..iterations {
|
||||||
|
let (make, model, firmware, board) = cases[index % cases.len()];
|
||||||
|
let clean = clean_model(make, model);
|
||||||
|
std::hint::black_box(firmware_family(firmware));
|
||||||
|
std::hint::black_box(control_board_code(make, board, &clean));
|
||||||
|
std::hint::black_box(chip_type_for_model(make, model));
|
||||||
|
std::hint::black_box(clean);
|
||||||
|
}
|
||||||
|
let elapsed = started.elapsed();
|
||||||
|
let per = elapsed / iterations as u32;
|
||||||
|
println!("bench_naming_transforms: {per:?}/record");
|
||||||
|
assert!(elapsed < std::time::Duration::from_millis(500));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+27
-17
@@ -8,13 +8,13 @@
|
|||||||
#
|
#
|
||||||
# Usage: scripts/ui-screenshot.sh [out.png] [--live] [binary]
|
# Usage: scripts/ui-screenshot.sh [out.png] [--live] [binary]
|
||||||
set -u
|
set -u
|
||||||
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
REPO=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}"
|
WX_PREFIX="${WX_PREFIX:-$HOME/.cache/wx-3.3.3-linux}"
|
||||||
export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}"
|
export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$WX_PREFIX/bin/wx-config}"
|
||||||
|
|
||||||
OUT="${1:-alkane-toolkit.png}"
|
OUT="${1:-alkane-toolkit.png}"
|
||||||
LIVE=0; BIN=""
|
LIVE=0; BIN=""
|
||||||
shift 2>/dev/null || true
|
[ "$#" -eq 0 ] || shift
|
||||||
for a in "$@"; do
|
for a in "$@"; do
|
||||||
case "$a" in
|
case "$a" in
|
||||||
--live) LIVE=1 ;;
|
--live) LIVE=1 ;;
|
||||||
@@ -32,17 +32,31 @@ if [ -z "$BIN" ]; then
|
|||||||
fi
|
fi
|
||||||
[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; }
|
[ -x "$BIN" ] || { echo "binary not found: $BIN" >&2; exit 3; }
|
||||||
|
|
||||||
DISP=":98"
|
DISPLAY_FILE=$(mktemp)
|
||||||
FAKE_ENV="ALKANE_FAKE_SCAN=1"
|
XPID=""; APID=""; WARM=""
|
||||||
[ "$LIVE" = "1" ] && FAKE_ENV=""
|
cleanup() {
|
||||||
|
[ -z "$APID" ] || kill "$APID" 2>/dev/null || true
|
||||||
Xvfb "$DISP" -screen 0 1280x850x24 -nolisten tcp >/dev/null 2>&1 &
|
[ -z "$WARM" ] || kill "$WARM" 2>/dev/null || true
|
||||||
|
[ -z "$XPID" ] || kill "$XPID" 2>/dev/null || true
|
||||||
|
rm -f "$DISPLAY_FILE"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
Xvfb -displayfd 3 -screen 0 1280x850x24 -nolisten tcp 3>"$DISPLAY_FILE" >/dev/null 2>&1 &
|
||||||
XPID=$!
|
XPID=$!
|
||||||
sleep 1.2
|
for _ in {1..30}; do
|
||||||
|
[ -s "$DISPLAY_FILE" ] && break
|
||||||
|
kill -0 "$XPID" 2>/dev/null || { echo "Xvfb exited before startup" >&2; exit 3; }
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
[ -s "$DISPLAY_FILE" ] || { echo "Xvfb did not start" >&2; exit 3; }
|
||||||
|
DISP=":$(cat "$DISPLAY_FILE")"
|
||||||
# warm the font/GTK caches so the first window map is not stalled
|
# warm the font/GTK caches so the first window map is not stalled
|
||||||
DISPLAY="$DISP" xclock >/dev/null 2>&1 & WARM=$!; sleep 1.2; kill "$WARM" 2>/dev/null
|
DISPLAY="$DISP" xclock >/dev/null 2>&1 & WARM=$!; sleep 1.2; kill "$WARM" 2>/dev/null
|
||||||
# shellcheck disable=SC2086
|
if [ "$LIVE" = "1" ]; then
|
||||||
DISPLAY="$DISP" GDK_BACKEND=x11 $FAKE_ENV "$BIN" >/dev/null 2>&1 &
|
DISPLAY="$DISP" GDK_BACKEND=x11 "$BIN" >/dev/null 2>&1 &
|
||||||
|
else
|
||||||
|
DISPLAY="$DISP" GDK_BACKEND=x11 ALKANE_FAKE_SCAN=1 "$BIN" >/dev/null 2>&1 &
|
||||||
|
fi
|
||||||
APID=$!
|
APID=$!
|
||||||
WID=""; t=0
|
WID=""; t=0
|
||||||
while [ "$t" -lt 25 ]; do
|
while [ "$t" -lt 25 ]; do
|
||||||
@@ -52,10 +66,6 @@ while [ "$t" -lt 25 ]; do
|
|||||||
[ -n "$line" ] && { WID=$(echo "$line" | awk '{print $1}'); break; }
|
[ -n "$line" ] && { WID=$(echo "$line" | awk '{print $1}'); break; }
|
||||||
done
|
done
|
||||||
sleep 2 # let it paint and drain a scan tick
|
sleep 2 # let it paint and drain a scan tick
|
||||||
if [ -n "$WID" ]; then
|
[ -n "$WID" ] || { echo "no app window mapped" >&2; exit 1; }
|
||||||
DISPLAY="$DISP" import -window "$WID" "$OUT" && echo "wrote $OUT (window $WID, ${t}s)"
|
DISPLAY="$DISP" import -window "$WID" "$OUT" || exit 1
|
||||||
else
|
echo "wrote $OUT (window $WID, ${t}s)"
|
||||||
DISPLAY="$DISP" import -window root "$OUT"; echo "no app window; captured root -> $OUT" >&2
|
|
||||||
fi
|
|
||||||
kill "$APID" 2>/dev/null
|
|
||||||
kill "$XPID" 2>/dev/null
|
|
||||||
|
|||||||
Reference in New Issue
Block a user