02: cpu fast engine and metrics

This commit is contained in:
rob thijssen
2025-09-07 20:48:01 +08:00
parent 0d5adf583b
commit 6cd53557d7
6 changed files with 562 additions and 7 deletions
+66 -1
View File
@@ -138,4 +138,69 @@ impl MinerEngine for BaselineCpuEngine {
}
// Re-export commonly used items for convenience by consumers.
pub use {BaselineCpuEngine as DefaultEngine, Candidate as EngineCandidate, Range as EngineRange};
// Fast CPU engine using incremental pow-core helpers (init_worker_y0 + step_mul)
#[derive(Default)]
pub struct FastCpuEngine;
impl FastCpuEngine {
pub fn new() -> Self {
Self
}
}
impl MinerEngine for FastCpuEngine {
fn name(&self) -> &'static str {
"cpu-fast"
}
fn prepare_context(&self, header_hash: [u8; 32], threshold: U512) -> JobContext {
JobContext::new(header_hash, threshold)
}
fn search_range(&self, ctx: &JobContext, range: Range, cancel: &AtomicBool) -> EngineStatus {
use pow_core::{distance_from_y, init_worker_y0, is_valid_distance, step_mul};
// Ensure start <= end (inclusive range). If not, treat as exhausted.
if range.start > range.end {
return EngineStatus::Exhausted { hash_count: 0 };
}
let mut current = range.start;
let mut y = init_worker_y0(ctx, current);
let mut hash_count: u64 = 0;
loop {
// Cancellation check
if cancel.load(AtomicOrdering::Relaxed) {
return EngineStatus::Cancelled { hash_count };
}
// Compute distance from current accumulator
let distance = distance_from_y(ctx, y);
hash_count = hash_count.saturating_add(1);
if is_valid_distance(ctx, distance) {
let work = current.to_big_endian();
return EngineStatus::Found(Candidate {
nonce: current,
work,
distance,
});
}
if current == range.end {
break EngineStatus::Exhausted { hash_count };
}
// Advance to next nonce: y <- y * m (mod n), current <- current + 1
y = step_mul(ctx, y);
current = current.saturating_add(U512::one());
}
}
}
pub use {
BaselineCpuEngine as DefaultEngine, Candidate as EngineCandidate, FastCpuEngine as FastEngine,
Range as EngineRange,
};
+131 -1
View File
@@ -22,7 +22,7 @@
use once_cell::sync::Lazy;
use prometheus::{
opts, Encoder, Gauge, IntCounter, IntCounterVec, Registry, TextEncoder,
opts, Encoder, Gauge, GaugeVec, IntCounter, IntCounterVec, IntGauge, IntGaugeVec, Registry, TextEncoder,
};
#[cfg(feature = "http-exporter")]
@@ -85,6 +85,98 @@ static HTTP_REQUESTS_TOTAL: Lazy<IntCounterVec> = Lazy::new(|| {
});
/// Access the global Prometheus registry used by this crate.
// Engine-aware, per-job, and per-thread labeled metrics
static JOB_HASHES_TOTAL: Lazy<IntCounterVec> = Lazy::new(|| {
let c = IntCounterVec::new(
opts!(
"miner_job_hashes_total",
"Total nonces tested per job and engine"
),
&["engine", "job_id"],
)
.expect("create miner_job_hashes_total");
REGISTRY
.register(Box::new(c.clone()))
.expect("register miner_job_hashes_total");
c
});
static JOB_HASH_RATE: Lazy<GaugeVec> = Lazy::new(|| {
let g = GaugeVec::new(
opts!(
"miner_job_hash_rate",
"Estimated hash rate (nonces per second) per job and engine"
),
&["engine", "job_id"],
)
.expect("create miner_job_hash_rate");
REGISTRY
.register(Box::new(g.clone()))
.expect("register miner_job_hash_rate");
g
});
static THREAD_HASHES_TOTAL: Lazy<IntCounterVec> = Lazy::new(|| {
let c = IntCounterVec::new(
opts!(
"miner_thread_hashes_total",
"Total nonces tested per thread, job, and engine"
),
&["engine", "job_id", "thread_id"],
)
.expect("create miner_thread_hashes_total");
REGISTRY
.register(Box::new(c.clone()))
.expect("register miner_thread_hashes_total");
c
});
static THREAD_HASH_RATE: Lazy<GaugeVec> = Lazy::new(|| {
let g = GaugeVec::new(
opts!(
"miner_thread_hash_rate",
"Estimated hash rate (nonces per second) per thread, job, and engine"
),
&["engine", "job_id", "thread_id"],
)
.expect("create miner_thread_hash_rate");
REGISTRY
.register(Box::new(g.clone()))
.expect("register miner_thread_hash_rate");
g
});
static JOBS_BY_ENGINE_TOTAL: Lazy<IntCounterVec> = Lazy::new(|| {
let c = IntCounterVec::new(
opts!(
"miner_jobs_by_engine_total",
"Number of jobs by engine and terminal status"
),
&["engine", "status"],
)
.expect("create miner_jobs_by_engine_total");
REGISTRY
.register(Box::new(c.clone()))
.expect("register miner_jobs_by_engine_total");
c
});
static JOB_STATUS_GAUGE: Lazy<IntGaugeVec> = Lazy::new(|| {
let g = IntGaugeVec::new(
opts!(
"miner_job_status",
"Job status gauge (set to 1 for current status)"
),
&["engine", "job_id", "status"],
)
.expect("create miner_job_status");
REGISTRY
.register(Box::new(g.clone()))
.expect("register miner_job_status");
g
});
pub fn default_registry() -> &'static Registry {
&REGISTRY
}
@@ -94,6 +186,44 @@ pub fn default_registry() -> &'static Registry {
// -------------------------------------------------------------------------------------
/// Increment the total hashes counter by `n` (number of nonces tested).
// Labeled helpers for engine/job/thread metrics
pub fn inc_job_hashes(engine: &str, job_id: &str, n: u64) {
JOB_HASHES_TOTAL
.with_label_values(&[engine, job_id])
.inc_by(n);
}
pub fn set_job_hash_rate(engine: &str, job_id: &str, rate: f64) {
JOB_HASH_RATE
.with_label_values(&[engine, job_id])
.set(rate);
}
pub fn inc_thread_hashes(engine: &str, job_id: &str, thread_id: &str, n: u64) {
THREAD_HASHES_TOTAL
.with_label_values(&[engine, job_id, thread_id])
.inc_by(n);
}
pub fn set_thread_hash_rate(engine: &str, job_id: &str, thread_id: &str, rate: f64) {
THREAD_HASH_RATE
.with_label_values(&[engine, job_id, thread_id])
.set(rate);
}
pub fn inc_jobs_by_engine(engine: &str, status: &str) {
JOBS_BY_ENGINE_TOTAL
.with_label_values(&[engine, status])
.inc();
}
pub fn set_job_status_gauge(engine: &str, job_id: &str, status: &str, value: i64) {
JOB_STATUS_GAUGE
.with_label_values(&[engine, job_id, status])
.set(value);
}
pub fn inc_hashes(n: u64) {
HASHES_TOTAL.inc_by(n);
}
+5 -4
View File
@@ -18,8 +18,8 @@ struct Args {
#[arg(long, env = "MINER_METRICS_PORT")]
metrics_port: Option<u16>,
/// Mining engine to use
#[arg(long, env = "MINER_ENGINE", value_enum, default_value_t = EngineCli::CpuBaseline)]
/// Mining engine to use (default: cpu-fast). Options: cpu-baseline, cpu-fast
#[arg(long, env = "MINER_ENGINE", value_enum, default_value_t = EngineCli::CpuFast)]
engine: EngineCli,
}
@@ -27,7 +27,8 @@ struct Args {
enum EngineCli {
/// Baseline CPU engine (reference implementation)
CpuBaseline,
// CpuFast, // planned: incremental + Montgomery
/// Optimized CPU engine (incremental precompute + step_mul)
CpuFast,
// Cuda, // planned: CUDA GPU engine
// Opencl, // planned: OpenCL GPU engine
}
@@ -36,7 +37,7 @@ impl From<EngineCli> for EngineSelection {
fn from(value: EngineCli) -> Self {
match value {
EngineCli::CpuBaseline => EngineSelection::CpuBaseline,
// EngineCli::CpuFast => EngineSelection::CpuFast,
EngineCli::CpuFast => EngineSelection::CpuFast,
// EngineCli::Cuda => EngineSelection::Cuda,
// EngineCli::Opencl => EngineSelection::OpenCl,
}
+121 -1
View File
@@ -13,6 +13,8 @@ use std::time::Instant;
use tokio::sync::Mutex;
use warp::{Filter, Rejection, Reply};
const THREAD_RATE_EMA_ALPHA: f64 = 0.2;
/// Service runtime configuration provided by the CLI/binary.
#[derive(Clone, Debug)]
pub struct ServiceConfig {
@@ -30,7 +32,7 @@ pub struct ServiceConfig {
#[derive(Clone, Debug)]
pub enum EngineSelection {
CpuBaseline,
// CpuFast, // placeholder for incremental/Montgomery path
CpuFast,
// Cuda,
// OpenCl,
}
@@ -71,6 +73,14 @@ impl MiningService {
}
log::debug!(target: "miner", "Adding job: {} with {} cores", job_id, self.num_cores);
job.job_id = Some(job_id.clone());
#[cfg(feature = "metrics")]
{
metrics::set_job_status_gauge(self.engine.name(), &job_id, "running", 1);
metrics::set_job_status_gauge(self.engine.name(), &job_id, "completed", 0);
metrics::set_job_status_gauge(self.engine.name(), &job_id, "failed", 0);
metrics::set_job_status_gauge(self.engine.name(), &job_id, "cancelled", 0);
}
job.start_mining(self.engine.clone(), self.num_cores);
jobs.insert(job_id, job);
Ok(())
@@ -131,6 +141,22 @@ impl MiningService {
retain
});
#[cfg(feature = "metrics")]
{
// Aggregate and per-job hash-rate estimate across running jobs (nonces/sec)
let mut total_rate = 0.0;
for (job_id, job) in jobs_guard.iter() {
if job.status == JobStatus::Running {
let elapsed = job.start_time.elapsed().as_secs_f64();
if elapsed > 0.0 {
let rate = job.total_hash_count as f64 / elapsed;
total_rate += rate;
metrics::set_job_hash_rate(job.engine_name, job_id, rate);
}
}
}
metrics::set_hash_rate(total_rate);
}
drop(jobs_guard);
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
@@ -168,9 +194,13 @@ pub struct MiningJob {
pub total_hash_count: u64,
pub best_result: Option<MiningJobResult>,
pub engine_name: &'static str,
pub job_id: Option<String>,
pub cancel_flag: Arc<AtomicBool>,
pub result_receiver: Option<Receiver<ThreadResult>>,
pub thread_handles: Vec<thread::JoinHandle<()>>,
pub thread_last_update: std::collections::HashMap<usize, std::time::Instant>,
pub thread_rate_ema: std::collections::HashMap<usize, f64>,
completed_threads: usize,
}
@@ -191,6 +221,8 @@ impl Clone for MiningJob {
// Do not clone crossbeam receiver or thread handles; they are runtime artifacts.
result_receiver: None,
thread_handles: Vec::new(),
thread_last_update: self.thread_last_update.clone(),
thread_rate_ema: self.thread_rate_ema.clone(),
completed_threads: self.completed_threads,
}
}
@@ -220,9 +252,13 @@ impl MiningJob {
start_time: Instant::now(),
total_hash_count: 0,
best_result: None,
engine_name: "unknown",
job_id: None,
cancel_flag: Arc::new(AtomicBool::new(false)),
result_receiver: None,
thread_handles: Vec::new(),
thread_last_update: std::collections::HashMap::new(),
thread_rate_ema: std::collections::HashMap::new(),
completed_threads: 0,
}
}
@@ -230,6 +266,7 @@ impl MiningJob {
pub fn start_mining(&mut self, engine: Arc<dyn MinerEngine>, num_cores: usize) {
let (sender, receiver) = bounded(num_cores * 2);
self.result_receiver = Some(receiver);
self.engine_name = engine.name();
let total_range = (self.nonce_end - self.nonce_start).saturating_add(U512::from(1));
let range_per_core = total_range / U512::from(num_cores as u64);
@@ -281,6 +318,17 @@ impl MiningJob {
log::debug!(target: "miner", "Cancelling mining job");
self.cancel_flag.store(true, Ordering::Relaxed);
self.status = JobStatus::Cancelled;
#[cfg(feature = "metrics")]
{
metrics::inc_job_status("cancelled");
if let Some(job_id) = &self.job_id {
metrics::inc_jobs_by_engine(self.engine_name, "cancelled");
metrics::set_job_status_gauge(self.engine_name, job_id, "running", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "completed", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "failed", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "cancelled", 1);
}
}
while let Some(handle) = self.thread_handles.pop() {
let _ = handle.join();
@@ -295,9 +343,58 @@ impl MiningJob {
while let Ok(thread_result) = receiver.try_recv() {
self.total_hash_count += thread_result.hash_count;
#[cfg(feature = "metrics")]
{
metrics::inc_hashes(thread_result.hash_count);
if let Some(job_id) = &self.job_id {
metrics::inc_job_hashes(self.engine_name, job_id, thread_result.hash_count);
metrics::inc_thread_hashes(
self.engine_name,
job_id,
&thread_result.thread_id.to_string(),
thread_result.hash_count,
);
// Compute per-thread delta hash rate since the last update for this thread
let now = std::time::Instant::now();
let last = self
.thread_last_update
.get(&thread_result.thread_id)
.copied()
.unwrap_or(self.start_time);
let dt = now.duration_since(last).as_secs_f64();
if dt > 0.0 && thread_result.hash_count > 0 {
let instant_rate = thread_result.hash_count as f64 / dt;
// Exponential Moving Average smoothing
let prev = self
.thread_rate_ema
.get(&thread_result.thread_id)
.copied()
.unwrap_or(instant_rate);
let ema = THREAD_RATE_EMA_ALPHA * instant_rate + (1.0 - THREAD_RATE_EMA_ALPHA) * prev;
metrics::set_thread_hash_rate(
self.engine_name,
job_id,
&thread_result.thread_id.to_string(),
ema,
);
// Store updated EMA for next delta
self.thread_rate_ema
.insert(thread_result.thread_id, ema);
}
// Update last-seen timestamp for this thread
self.thread_last_update
.insert(thread_result.thread_id, now);
}
}
if thread_result.completed {
self.completed_threads += 1;
#[cfg(feature = "metrics")]
{
// Cleanup per-thread tracking on completion
self.thread_last_update.remove(&thread_result.thread_id);
self.thread_rate_ema.remove(&thread_result.thread_id);
}
}
if let Some(result) = thread_result.result {
@@ -322,10 +419,32 @@ impl MiningJob {
if self.status == JobStatus::Running {
if self.best_result.is_some() {
self.status = JobStatus::Completed;
#[cfg(feature = "metrics")]
{
metrics::inc_job_status("completed");
if let Some(job_id) = &self.job_id {
metrics::inc_jobs_by_engine(self.engine_name, "completed");
metrics::set_job_status_gauge(self.engine_name, job_id, "running", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "completed", 1);
metrics::set_job_status_gauge(self.engine_name, job_id, "failed", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "cancelled", 0);
}
}
} else if self.completed_threads >= self.thread_handles.len()
&& !self.thread_handles.is_empty()
{
self.status = JobStatus::Failed;
#[cfg(feature = "metrics")]
{
metrics::inc_job_status("failed");
if let Some(job_id) = &self.job_id {
metrics::inc_jobs_by_engine(self.engine_name, "failed");
metrics::set_job_status_gauge(self.engine_name, job_id, "running", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "completed", 0);
metrics::set_job_status_gauge(self.engine_name, job_id, "failed", 1);
metrics::set_job_status_gauge(self.engine_name, job_id, "cancelled", 0);
}
}
}
}
@@ -610,6 +729,7 @@ pub async fn run(config: ServiceConfig) -> anyhow::Result<()> {
#[allow(unused_mut)]
let mut engine: Arc<dyn MinerEngine> = match config.engine {
EngineSelection::CpuBaseline => Arc::new(engine_cpu::BaselineCpuEngine::new()),
EngineSelection::CpuFast => Arc::new(engine_cpu::FastCpuEngine::new()),
};
log::info!("Using engine: {}", engine.name());
@@ -0,0 +1,94 @@
# Prompt Summary: CPU Fast Engine and Metrics Integration (Extended with Engine-/Job-/Thread-aware Metrics and Smoothing)
## Context
Following the prior repository restructuring into a Cargo workspace with clear separation of concerns (CLI, service, engines, and math core), you requested the next implementation steps focusing on performance and observability:
- Introduce an optimized CPU mining engine leveraging the new `pow-core` incremental helpers.
- Integrate Prometheus metrics into the service layer with a runtime toggle based on `--metrics-port`.
- Extend metrics to be engine-, job-, and thread-aware with labeled counters/gauges.
- Add per-thread hash rate gauges computed via delta-rate in the service, with EMA smoothing and a code-level constant for alpha.
This work must preserve API compatibility with the node and fit into the existing engine abstraction.
## Objectives
1. Add a new `cpu-fast` engine in `engine-cpu`:
- Implement the `MinerEngine` trait using the optimized, incremental path from `pow-core`:
- Initialize `y0` for the range start using `init_worker_y0`.
- Iterate nonces using `step_mul` per step (O(1) modular multiplication) instead of per-nonce exponentiation.
- Compute distances via `distance_from_y` and evaluate against the threshold with `is_valid_distance`.
- Ensure cancellation and range handling semantics remain identical to the baseline engine.
- Keep the public HTTP API unchanged.
2. Hook up foundational metrics in `miner-service`:
- Add counters for job terminal states: `completed`, `failed`, `cancelled`.
- Track total number of nonces evaluated (hashes total).
- Compute and expose a basic aggregate hash rate (nonces/second) across running jobs.
- Respect the runtime toggle: metrics are enabled only when `--metrics-port` is provided; otherwise metrics are disabled entirely.
3. Extend metrics with engine-aware per-job and per-thread labels:
- Per-job totals and rates labeled by `{engine, job_id}`.
- Per-thread totals and rates labeled by `{engine, job_id, thread_id}`.
- A gauge series to reflect current job status labeled by `{engine, job_id, status}`.
- A counter for jobs by engine and terminal status `{engine, status}`.
4. Implement per-thread delta-rate calculation with EMA smoothing:
- Compute per-thread hash rate as `delta_hashes / delta_time` on each worker update.
- Smooth the per-thread rate using EMA with a code constant (e.g., `THREAD_RATE_EMA_ALPHA = 0.2`).
## Requirements and Constraints
- Maintain full compatibility with the node’s HTTP API and `resonance-miner-api` types.
- Keep orchestration and compute concerns separate via the `MinerEngine` trait.
- Metrics must impose no runtime cost or bindings when `--metrics-port` is not provided.
- Preserve existing job lifecycle and cancellation behavior.
- Ensure code compiles cleanly in release mode.
- Avoid protocol or public API changes; all metrics additions are internal and optional.
## Acceptance Criteria
- A new `FastCpuEngine` exists in `engine-cpu` implementing `MinerEngine` and using:
- `pow-core::init_worker_y0` at the start of the range;
- `pow-core::step_mul` for each subsequent nonce in the range;
- `pow-core::distance_from_y` and `pow-core::is_valid_distance` for validation.
- The service can select this engine via CLI (e.g., `--engine cpu-fast`) without breaking other engines.
- When metrics are enabled (via `--metrics-port`), the service:
- Increments a jobs counter by status on completion/failure/cancellation.
- Increments total hashes by the amount of work reported from workers.
- Exposes:
- A global hash rate gauge computed from aggregate hashes/elapsed time across running jobs.
- Per-job hash rate gauges labeled `{engine, job_id}`.
- Per-thread hash rate gauges labeled `{engine, job_id, thread_id}` computed via delta-rate in the service.
- Exposes labeled totals:
- `miner_job_hashes_total{engine,job_id}`
- `miner_thread_hashes_total{engine,job_id,thread_id}`
- Tracks job status via:
- `miner_job_status{engine,job_id,status}` IntGauge set to 1 for the current status
- `miner_jobs_by_engine_total{engine,status}` counters
- No changes to the node-facing HTTP endpoints or payload formats.
- Successful `cargo build --release`.
## Deliverables (Code-Level)
- `engine-cpu`:
- `FastCpuEngine` implementing the incremental mining loop.
- `miner-service`:
- Engine selection supporting `cpu-fast`.
- Metrics integration points for job status, total hashes, aggregate and per-job hash rates.
- Per-thread delta-rate computation and EMA smoothing with a code constant (`THREAD_RATE_EMA_ALPHA`).
- `metrics` crate:
- Labeled metrics (engine/job/thread) and helper functions for increments/sets.
- Optional HTTP exporter gated by the `--metrics-port` runtime toggle.
## Out of Scope (for this prompt)
- Montgomery multiplication integration (future optimization).
- GPU engines (CUDA/OpenCL) implementation.
- Persisted metrics storage or external observability systems (Grafana dashboards can be configured separately).
## Notes
- The fast engine enables substantial performance gains by replacing per-nonce modular exponentiation with per-nonce modular multiplication after a single initialization exponentiation per worker.
- Metrics integration provides observability for benchmarking and tuning while remaining fully optional at runtime.
- Per-thread hash rate smoothing reduces jitter and produces more stable telemetry; we’ll revisit `THREAD_RATE_EMA_ALPHA` after collecting real-world data.
@@ -0,0 +1,145 @@
# Response Summary: CPU Fast Engine and Metrics Integration (Extended)
This document summarizes the implementation of an optimized CPU mining engine and the integration of Prometheus metrics into the miner service, including engine-/job-/thread-aware metrics and per-thread rate smoothing. It corresponds to the prompt captured in `02-prompt-cpu-fast-engine-and-metrics.md`.
## Overview
- Added a new optimized CPU engine (`cpu-fast`) that leverages precomputation and incremental updates to drastically reduce per-nonce work.
- Integrated Prometheus metrics (optional at runtime) for:
- Job terminal states (completed/failed/cancelled),
- Total number of nonces tested,
- Aggregate hash rate (nonces/sec) across running jobs,
- Engine-aware per-job and per-thread totals and rates (via labels).
- Implemented per-thread hash rate gauges computed via delta-rate in the service and smoothed using EMA with a code constant.
- Preserved the node-facing HTTP API and maintained separation of concerns via a clean engine abstraction.
## Changes Implemented
- New engine implementation in `crates/engine-cpu/src/lib.rs`:
- `FastCpuEngine` implements `MinerEngine` using pow-core’s optimized helpers.
- Keeps cancellation and range semantics identical to baseline.
- CLI engine selection in `crates/miner-cli/src/main.rs`:
- `--engine` now accepts `cpu-baseline` and `cpu-fast`.
- Default is `cpu-fast`.
- Service updates in `crates/miner-service/src/lib.rs`:
- `EngineSelection` supports `CpuFast`.
- When `CpuFast` is selected, the service instantiates `FastCpuEngine`.
- Metrics integration:
- Runtime toggle: exporter starts only when `--metrics-port` is provided.
- Counters and gauges in `crates/metrics/src/lib.rs` and called from the service:
- Global:
- `miner_jobs_total{status="completed|failed|cancelled"}`
- `miner_hashes_total`
- `miner_hash_rate`
- Engine-/job-aware:
- `miner_job_hashes_total{engine,job_id}`
- `miner_job_hash_rate{engine,job_id}`
- `miner_job_status{engine,job_id,status}` (IntGauge set to 1 for current status)
- `miner_jobs_by_engine_total{engine,status}`
- Engine-/job-/thread-aware:
- `miner_thread_hashes_total{engine,job_id,thread_id}`
- `miner_thread_hash_rate{engine,job_id,thread_id}`
## Fast CPU Engine: Algorithm Details
File: `crates/engine-cpu/src/lib.rs`
- `FastCpuEngine::prepare_context`:
- Builds a `pow_core::JobContext` that precomputes `(m, n)` and the `target` value from the header and threshold.
- `FastCpuEngine::search_range`:
- Initializes `y0` for the starting nonce using `pow_core::init_worker_y0(ctx, start)`.
- Loops over the inclusive nonce range:
- Uses `pow_core::distance_from_y(ctx, y)` to compute the current distance.
- Checks validity via `pow_core::is_valid_distance(ctx, distance)`.
- If not valid, advances one step with `pow_core::step_mul(ctx, y)` (O(1) modular multiplication).
- Supports prompt cancellation via an atomic flag.
- Returns `Found(candidate)`, `Exhausted`, or `Cancelled` with an accumulated `hash_count`.
Correctness:
- The incremental path (y <- y*m mod n) is equivalent to computing `m^(h + nonce)` via exponentiation, but avoids the heavy per-nonce modular exponentiation.
- We validate per-nonce by computing distance from `y` and comparing it to the threshold.
## Service Integration
File: `crates/miner-service/src/lib.rs`
- Engine selection extended:
- `EngineSelection::CpuFast` added.
- `run(ServiceConfig)` branches to instantiate `FastCpuEngine` when selected.
- Mining loop unchanged:
- Orchestration retains responsibility for job lifecycle, range partitioning, cancellation, and result aggregation.
- The engine’s interface abstracts the compute details.
## Metrics Integration
Files:
- `crates/metrics/src/lib.rs` (Prometheus registry and HTTP exporter)
- `crates/miner-service/src/lib.rs` (hook points for updates)
Key behavior:
- Metrics are disabled by default and only activated when `--metrics-port` is provided in the CLI.
- When active:
- Global metrics:
- `miner_jobs_total{status="completed"}` increments on job completion.
- `miner_jobs_total{status="failed"}` increments when a job fails.
- `miner_jobs_total{status="cancelled"}` increments when cancelled.
- `miner_hashes_total` increments by `hash_count` deltas from worker threads.
- `miner_hash_rate` is periodically set from aggregate job progress.
- Engine-/job metrics:
- `miner_job_hashes_total{engine,job_id}` increments by deltas.
- `miner_job_hash_rate{engine,job_id}` set from per-job aggregate progress.
- `miner_job_status{engine,job_id,status}` gauges kept mutually exclusive (1 for current state).
- `miner_jobs_by_engine_total{engine,status}` increments on terminal transitions.
- Engine-/job-/thread metrics:
- `miner_thread_hashes_total{engine,job_id,thread_id}` increments by per-thread deltas.
- `miner_thread_hash_rate{engine,job_id,thread_id}` set via delta-rate with EMA smoothing.
Exporter:
- Serves `/metrics` on the specified port when enabled.
## Per-thread Delta Rate and EMA Smoothing
- Each `MiningJob` tracks:
- `thread_last_update: HashMap<usize, Instant>`
- `thread_rate_ema: HashMap<usize, f64>`
- On each `ThreadResult`:
- Compute `dt = now - last_update(thread_id)`; if `dt > 0` and `hash_count > 0`, compute `instant_rate = hash_count / dt`.
- Smooth with EMA: `ema = alpha * instant_rate + (1 - alpha) * prev_ema`.
- Set `miner_thread_hash_rate{engine,job_id,thread_id} = ema`.
- Update `thread_last_update` and `thread_rate_ema`.
- On thread completion, remove its tracking entries.
- The EMA coefficient is a code constant in the service:
- `THREAD_RATE_EMA_ALPHA: f64 = 0.2`
- We’ll revisit this value once we collect real-world data.
## Backward Compatibility
- The HTTP API exposed to the node is unchanged:
- Endpoints: `POST /mine`, `GET /result/{job_id}`, `POST /cancel/{job_id}`.
- Types sourced from `resonance-miner-api` remain intact.
- All metrics additions are internal and optional.
## Build and Run
- Build (release):
- `cargo build -p miner-cli --release`
- Run (fast engine, no metrics):
- `cargo run -p miner-cli -- --port 9833 --engine cpu-fast`
- Run with metrics:
- `cargo run -p miner-cli -- --port 9833 --engine cpu-fast --metrics-port 9900`
- Scrape: `http://localhost:9900/metrics`
CLI defaults:
- `--engine` defaults to `cpu-fast`.
- Metrics remain off unless `--metrics-port` is supplied.
## Verification
- Compilation in release mode completes successfully after minor fixes.
- Runtime behavior mirrors baseline engine semantics with improved performance potential.
- Metrics endpoint activates only when requested and otherwise remains inert.
- Per-thread hash rate gauges reflect smoothed rates, reducing jitter.
## Notes and Next Steps
- Integrate Montgomery multiplication into `pow-core` and switch the fast engine to use it for even higher throughput.
- Optional: add per-job/engine labels to result responses for correlation (kept internal to metrics for now).
- Optional: promote the `MinerEngine` trait to a small shared crate (e.g., `engine-api`) for GPU engine implementations.