Skip to content

2500× hashrate boost: 20k → up to 50m ops/s (cpu-fast, metrics, throttling, stable) - #1

Merged
grenade merged 14 commits into
mainfrom
feat/optimisation
Sep 10, 2025
Merged

grenade merged 14 commits into
mainfrom
feat/optimisation

Conversation

@grenade

@grenade grenade commented Sep 9, 2025

Copy link
Copy Markdown
Contributor

overview
this pr implements the 01–07 implementation docs and delivers a production-ready, observable cpu miner with a clean service boundary, consistent cli, and ci/toolchain hygiene. it intentionally defers select items from the 00 roadmap for post-merge follow-ups.

what’s included (docs/implementation)

  • 01: metrics toggle and soc restructure
    • clear separation of concerns across crates (service, engines, pow-core, metrics).
    • optional prometheus exporter via --metrics-port; default off.
  • 02: optimized cpu engine and richer metrics
    • new cpu-fast engine based on precompute + incremental modular multiplication (fast path).
    • vendored pow-core with refined api for optimization (future montgomery hook preserved).
    • per-engine/job/thread metrics foundation.
  • 03: engine comparability
    • consistent resource settings and terminology for fair, reproducible comparisons.
    • guidance on apples-to-apples testing across engines and instances.
  • 04: metrics chunking and dashboards
    • thread-level progress/throughput using chunked subranges with ema smoothing.
    • remove-on-end metrics semantics to avoid scrape artifacts; dashboard composition updated.
  • 05: workers and dashboards sync
    • cli clarifies worker semantics (--workers); auto-detects effective cpus honoring cpusets.
    • range partitioning safety (saturating arithmetic, clamped boundaries).
    • test fixes to remove flakiness and align runtime vs. dashboard views.
  • 06: throttling engine and difficulty overlay
    • new cpu-chain-manipulator engine that slows incrementally per solved block to help reduce difficulty overshoot on testnets.
    • configurable knobs: --manip-solved-blocks, --manip-base-delay-ns, --manip-step-batch, --manip-throttle-cap.
  • 07: stable toolchain, clippy/taplo hygiene, gpu engine placeholders
    • move to stable toolchain (with clippy, rustfmt); remove unused wasm target.
    • clippy cleanup (inline format args, doc lint fixes) and taplo formatting; ci-ready.
    • keep cpu-prefixed cli engine variants; add gpu-cuda/gpu-opencl placeholders.
    • selecting gpu engines errs early with a clear, user-facing message.

cli highlights

  • engine selection: --engine cpu-fast (default), cpu-baseline, cpu-chain-manipulator; gpu-cuda|gpu-opencl return a clear “unimplemented” error.
  • resource control: --workers (respects cgroups cpuset); balanced default when unspecified.
  • observability: --metrics-port to enable prometheus exporter.
  • metrics cadence: --progress-chunk-ms to tune per-thread update frequency.
  • throttling controls for cpu-chain-manipulator: --manip-solved-blocks, --manip-base-delay-ns, --manip-step-batch, --manip-throttle-cap.

validation

  • cargo +stable test --locked --workspace: green.
  • cargo clippy --workspace --all-targets (clean).
  • taplo fmt --check (clean).
  • manual runtime sanity across engines with and without metrics enabled.

deferred (from 00 roadmap; to follow after merge)

  • montgomery multiplication/accelerated modular arithmetic in pow-core.
  • gpu offloading engines (cuda/opencl) and corresponding metrics/dashboards.
  • additional integration/e2e coverage and advanced dashboard alerting/recording rules.

reviewer guide

  • full iteration docs: docs/implementation/readme.md
    • 07-prompt/response: stable toolchain, clippy/taplo, gpu enum placeholders
    • 06-prompt/response: manipulator engine and difficulty overlay
    • 05-prompt/response: workers and dashboards sync
    • 04-prompt/response: metrics chunking and dashboards
    • 03-prompt/response: engine comparability
    • 02-prompt/response: cpu-fast engine and metrics
    • 01-prompt/response: metrics toggle and soc restructure

Convert repository into Cargo workspace with modular crates

- Split code into workspace members: miner-cli, miner-service, pow-core,
engine-cpu, engine-gpu-cuda, engine-gpu-opencl, metrics - Moved QPoW
math logic into local pow-core crate with compatibility API and
incremental helpers - Defined MinerEngine trait and baseline CPU engine
in engine-cpu crate - Rewrote service layer in miner-service: job
management, HTTP API, engine orchestration - Added CLI binary crate
miner-cli with flags: --port, --num-cores, --metrics-port, --engine -
Implemented runtime toggle for Prometheus metrics exporter enabled only
when --metrics-port provided - Deprecated root src/lib.rs and
src/main.rs with notices pointing to new CLI/workspace entrypoints
Improve mining metrics with chunked progress updates and dashboards

- Emit periodic per-thread progress updates by chunking search ranges,
enabling fresher and more accurate job/global hash rates. - Smooth
per-thread hash rates with EMA; derive per-job and global rates from
thread aggregates. - Remove job/thread rate series on
completion/cancellation to avoid scrape-timing zero artifacts. - Add
service-level metrics: `miner_active_jobs` gauge and
`miner_mine_requests_total` counter with result labels. - Introduce
CLI/env knob `--progress-chunk-ms` to control progress update frequency
(default 2000ms). - Update Grafana dashboards for trend-friendly
queries, cleaned labels, 24h/1h peak views, and job-level filtering. -
Add detailed documentation summarizing metrics improvements, usage, and
operational guidance.
- Replace `--cores`/`--num-cores` with `--workers` to clarify intent
(logical CPU threads) - Detect cpuset-aware default for workers, leaving
~50% headroom on shared hosts - Clamp user-specified workers to
effective cpuset size - Update logs, configs, and APIs accordingly
- Introduce ChainManipulatorEngine using fast incremental hashing path -
Throttle mining speed per solved block using sleeps after nonce batches
- Add CLI/env options to control base delay, batch size, throttle cap,
and resume state - Wire engine selection and parameters through
miner-service and miner-cli - Add debug logs for throttle state at job
start and on block found - Add new Grafana panel showing robust
difficulty median per chain for visibility
- Switch toolchain to stable with clippy and rustfmt components - Clean
up Clippy warnings with inline format args and hygiene fixes - Add GPU
engine placeholders (gpu-cuda, gpu-opencl) in CLI and service - Return
clear runtime error and exit for unimplemented GPU engines - Format all
TOML files with Taplo and ensure taplo fmt --check passes - Improve
mining nonce partitioning for safe range splits - Update tests to pass
cleanly on stable without warnings
@grenade
grenade requested review from illuzen and n13 September 9, 2025 14:03
@n13

n13 commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

Would like to see some unit tests for the protocol implementation and if possible also for the calculations.

- Detect effective CPUs with cpuset awareness (cgroup v2/v1 fallback) -
Log detected cpuset mask or fallback info at startup (debug) - Expose
miner_effective_cpus Prometheus gauge (metrics feature) - Add
production-ready systemd unit and example CPU affinity overrides -
Include documentation for installation, overrides, and validation

@n13 n13 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO anything goes in the external miner, since we don't really care how it arrives at good results.

So there's duplicate code to the node, but it's OK.

Protocol was not changed.

@@ -0,0 +1,99 @@
#![deny(rust_2018_idioms)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this code is not used, let's remove it and put it in a branch for the time being. Dead code has a habit of accumulating.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code does absolutely nothing and should not be here.

@dastansam dastansam left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest running this through clippy once. there are a lot of places to reduce the code size. a lot of implicit returns missed, etc.

Comment thread crates/miner-cli/src/main.rs Resolved
Comment thread crates/miner-cli/src/main.rs Resolved
Comment thread crates/miner-service/src/lib.rs Resolved
n13
n13 previously requested changes Sep 10, 2025

@n13 n13 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok requesting this

  • remove dead code
  • run through clippy
  • remove "explanations" which are not neded - the whole /implementation segment

Other than that, Dastan pointed out there's many things that could be done in much fewer lines of code but I don't think it's worth our time rewriting what AI wrote.

So just requesting the above.

- Verify Baseline and Fast CPU engines produce matching results - Test
Exhausted and Cancelled engine states with precise hash counts - Cover
miner-service request validation error branches - Test miner-service
HTTP endpoints for expected status codes - Confirm chunked mining sends
progress and completion messages
@grenade

grenade commented Sep 10, 2025

Copy link
Copy Markdown
Contributor Author
  • clippy: was run many times during implementation and it runs on every push thanks to ci.yml. i'm struggling to understand why it was flagged twice since it is really obvious in ci, that it is being run and passing. i must assume that this was overlooked.
  • the “dead code” feedback, appears to be about placeholder code (e.g., gpu placeholders). gpu placeholders are used intentionally for ux and erroring early with a clear message; they are exercised by tests and keep cli consistent. i did not remove them because they are intentional placeholders with a defined behavior and tests. they are the next order of business for implementation once these changes land, so ripping them out now to satisfy a whim is busy-work-for-bureaucrats twice, since i would be putting them back in immediately following the merge. they exist intentionally and support the next batch of changes. i'm not inclined to jump through this hoop since it creates busy work for me with no upside.
  • logging and serviceconfig: good suggestion. i've implemented display for serviceconfig and switched cli startup to log a concise ‘effective config’ line. the miner-service also logs the final resolved configuration after engine selection.
  • usize comparison note: agreed. i removed that useless comparison in tests. there’s no remaining usize-negative comparison in the updated code.
  • implementation docs: removed.

@grenade

grenade commented Sep 10, 2025 •

Copy link
Copy Markdown
Contributor Author
image for reference:
  • the blue line at 0 ops/s in Global Hash Rate by Instance represents miners with the old 20k hashrate on resonance
  • the hashrates in the 20m to 40m range represent miners running the optimisations in this pr. on heisenberg
  • the yellow line in Difficulty (by chain) represents mining difficulty (automatically adjusted by the network, to account for network hashrate), on resonance
  • the green line in Difficulty (by chain) represents mining difficulty on heisenberg, where the faster mining algo has pushed difficulty higher

@grenade
grenade dismissed n13’s stale review September 10, 2025 03:52
  • remove dead code: done (gpu placeholders aren't dead)
  • run through clippy: done
  • remove "explanations": done

@n13 n13 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're already lenient to the extreme with this AI generated code.

It's a new era, ok, we can use AI gen code. There's a lot that could be made a lot better here but we can't use human hours to fix AI code- it doesn't make sense.

Still if we don't uphold the most basic of engineering principles, we have no principles.

Dead code should not go into a production PR.

Call it placeholder, comments, things I really like to do in the future, doesn't really matter. It's dead code. It creates more work for human reviewers.

It really was not a frivolous request.

@grenade

grenade commented Sep 10, 2025

Copy link
Copy Markdown
Contributor Author

It really was not a frivolous request.

  • In Rust, “dead code” has a precise, compiler-enforced meaning: items that are never used/referenced in any compiled target. See rustc’s dead_code lint:

  • Our GPU engine variants and code paths are not dead by that definition:

    • The CLI exposes gpu-cuda/gpu-opencl and maps them into miner-service’s EngineSelection. That mapping is code usage.
    • miner-service::run() matches EngineSelection::{GpuCuda, GpuOpenCl} and returns a clear Err. Those match arms reference the variants and are reachable when a user passes those flags. This is “unimplemented placeholder behavior,” not dead code.
    • Clippy is run with --all-targets in CI, and the placeholder GPU crates have tests that exercise their symbols, which also counts as usage.
  • Distinctions worth noting:

    • “Dead code” (compiler sense) ≠ “Not yet feature-complete.” A runtime error with a clear message when the option is selected is a valid, intentional behavior.
    • “Unreachable code” (e.g., behind a condition that can never be true) would be an issue. That’s not the case here; these branches are exercised if a user selects a GPU engine.
  • This pattern is standard practice in CLI/runtime design:

    • Keep forward-compatible flags/variants visible, and fail early with a descriptive error until the backend ships. It stabilizes UX/automation ahead of implementation and avoids future breaking changes in the CLI/API surface.

@n13

n13 commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

Ok well it is a rule and there's always exceptions to the rules.

So this is the exception to the rule 🙏

Hopefully we can resolve such things faster in the future and thanks Rob for coming and hashing it out in person

@n13

n13 commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

Approved

@grenade
grenade merged commit fc6a6b1 into main Sep 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants