Repository navigation
Stop serializing the full block on every accepted share - #162
Conversation
assemble_submission built block_hex for every accepted share, and serialize_block is O(block bytes): it bytes.fromhex-decodes the coinbase plus every transaction (each through validate_hex, which decodes once more and discards the result), concatenates, and the caller re-encodes the whole block to hex. Nothing on the share-accept path reads it -- block_hex is consumed only by the block-candidate landing path. Issue #143's findings comment measured the accept path against a 0-transaction template and named this as the largest open number in the report. Measured across the consensus range, the term is linear at 2.43 us of interpreter CPU per KB of block plus 0.25 us per transaction: an accepted share cost 2,447 us at a 1 MB template and 4,889 us at the 2,000,000-byte ceiling, of which 98.8% and 99.9% was serialization. Single-core share capacity collapsed from ~86,000/s at 0 transactions to 408/s at 1 MB, and the accept path alone crossed one full core at the deployed ~273 shares/s design point at ~1.45 MB -- inside the consensus range. Serialize only for a hash that solved the block. block_pass is the exact precondition, not a heuristic: classify_submit_work requires it for every route that constructs a PrismBlockCandidate, so gating on it computes a superset of what the landing path can ever ask for. The bytes are still built eagerly, on the client thread, in the same call that validates the coinbase -- before a candidate exists and long before its durable intent is written. Validation ordering does not move. Per-template transaction validation is already hoisted to job build and amortized across every share of that job: transaction_hexes_from_template validates each tx["data"], merkle_branch_for_coinbase structurally parses each transaction, and template_artifacts decodes them again when storing artifacts. make_job_from_builder_manifest is the only DirectQbitStratumJob constructor in lab/, the dataclass is frozen, and the per-client stamp in job_delivery never replaces transaction_hexes. The one per-share-varying input, the assembled coinbase, is still parsed unconditionally by strip_witness_transaction at assembly. The removed work was revalidating immutable, already-validated data -- measured at 55% of the term. block_candidate_intent now refuses to persist an empty block_hex for a real DirectQbitSubmission, failing on the client thread rather than resurrecting an unsubmittable candidate after every restart. Embedders that retain no block bytes keep the historical empty-string behaviour, and the attribute still exists on every submission so the landing path's hasattr guard keeps its meaning. After the fix the per-share composite is flat at 8.3-16.5 us across a 12,600x range of block size -- the residual is the merkle-branch fold, not serialization -- and single-core capacity is template-size independent at 52k-91k shares/s. The profiling driver lands under tests/ as a test instrument: standard library only, no database, network or coordinator, and not collected by unittest discover, so it costs no CI time. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Review of the previous commit found an asymmetry in _candidate_block_hex. The guard tolerates an embedder that retains no block bytes at write time, but block_candidate_from_intent rebuilds every replayed candidate as a real DirectQbitSubmission -- so on restart that tolerated empty value comes back wearing the strict type. The only caller that re-encodes a replayed candidate is the credit-on-accept append at block_finalization, which runs after the block has landed: raising there would fail a credit for a block already in the chain, strictly worse than re-persisting the same empty value the durable row already holds. Re-persisting an existing intent is not the write the guard exists to stop, so key it on the candidate's durable_replay flag. The guard still fires on every fresh candidate, which is where it protects something. Two tests cover the round trip: an embedder intent replays and re-encodes without raising, and a real serialized block survives the same path intact. Not reachable in this tree -- every durable intent writer goes through assemble_submission, which always carried non-empty block bytes for a block-worthy hash -- but the previous commit's message claimed embedders keep the historical empty-string behaviour, and across a restart they did not. Also fix the shipped instrument's term columns, which the same review found meaningless on the fixed tree: with the share path no longer serializing the block, the composite does not contain the term, so "term % of composite" printed ratios in the thousands of percent. The driver now asks the assembled submission whether the composite includes the term, renders both derived columns as n/a when it does not, explains why in a footnote, and emits null rather than NaN so the --json output stays strict JSON. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review follow-up (
|
PRISM is interpreter-bound on the paths that matter. #162 established that directly: once block serialization left the accept path, what remained was 16.5 us of pure interpreter work, flat across a 12,600x range of template size. Interpreter version is therefore a first-order lever on this workload, and the tree was two feature releases behind. Eight pins move: three Dockerfiles, four CI jobs, and the documented compileall validation command. No code changes. The Debian release is now pinned explicitly rather than inherited. The unsuffixed -slim tags track whatever Debian is current, so today's agreement between 3.12-slim and 3.14-slim is luck rather than contract; without the suffix a future rebuild silently becomes a distro bump that moves the apt Rust toolchain under cargo build --locked. Verified both bases resolve identically today: trixie, rustc 1.85.0+dfsg3-1, postgresql-client 17+278. Compatibility was checked rather than assumed. The coordinator image has one third-party dependency and psycopg-binary ships cp314 wheels, so the 3.2.* pin does not move -- confirmed by installing and importing psycopg 3.2.13 on 3.14.7 in the new base. Nothing in the tree imports a stdlib module removed in 3.13 or 3.14. Behaviour is unchanged on the suite. Full discovery run in both containers under identical conditions: 2,675 tests, 7 failures and 36 errors on each, and the failing test-name sets diff clean. Those 43 are environmental -- the bare container has no make or git, so the Makefile-lifecycle, source-staging and production-gate suites fail the same way on both interpreters. One consequence to record: this invalidates the absolute numbers in #143, #162 and #131, which were all measured on 3.12. The direction of every conclusion survives; the figures quoted in those issue comments should be re-baselined rather than carried forward. Closes #169. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Problem
assemble_submissionserializes the entire block on every accepted share(
lab/prism/direct_stratum.py:500).serialize_blockbytes.fromhex-decodes the coinbase plusevery entry of
job.transaction_hexes— each throughvalidate_hex, which decodes once more andthrows the result away — concatenates them, and the caller
.hex()-re-encodes the whole block.Roughly 3× block bytes of GIL-held allocation, per share.
Nothing on the ordinary share-accept path reads the result.
block_hexis consumed only on theblock-candidate landing path:
block_candidates.py:278(the durable restart intent),:334,:1870(thesubmitblockRPC), and thehasattrguard at:1972.Issue #143's findings comment measured the accept path against a 0-transaction template and
named this as the largest open number in the report. It is now measured.
Measurement
Reproduced the findings comment's methodology (primitives, min-of-7, composite submission path)
across a template-size sweep. Instrument and full report ship with this PR
(
tests/perf/serialize_block_share_cost.md).The sizes are tree-derived, not guessed. The ceiling is
crates/qbit-pool-builder/src/lib.rs:16-17—MAX_BLOCK_WEIGHT = 2_000_000, commented as qbitconsensus.hwithWITNESS_SCALE_FACTOR = 1, so weight units are bytes — corroborated bycompose.yaml:114and bydocker/ckpool/qbit-ckpool-preflight.py:494-544, which hard-failsunless live
getblocktemplate.weightlimitis exactly 2000000. The 0-transaction baseline is therepo's own (
lab/prism/job_build_benchmark.py:208-217).The tree contains no evidence of typical qbit block fullness, and #143 records that production
telemetry is a 21-connection snapshot that does not generalise. So rather than pick a
representative size, the sweep covers the whole consensus range and reports the law:
the term is linear at 2.43 µs of interpreter CPU per KB of block (R² = 0.99996 over eight
points), plus 0.25 µs per transaction. Anyone with a real template size can compute their own
point. The decision does not depend on the guess — the fix removes the term at every point on
the curve, including zero.
Anchor: the 0-transaction composite measures 8.96 µs against the findings comment's published
9.0 µs, a ratio of 0.995. The measuring machine is the same speed as the one the findings
comment ran on, so its numbers carry over.
Before / after, same driver, same machine, three runs each taken alternating so machine drift
falls on both sides equally; medians of three:
Above ~100 KB of template the accepted-share path essentially was block serialization.
Everything the findings comment measured at the 0-tx point — header assembly, the two
double_sha256s, the coinbase strip, the JSON — is a fixed 8-20 µs against a term reaching4,888 µs.
The after column is flat: 8.3 → 16.5 µs across a 12,600× range of block size. That residual is
not serialization but the per-share merkle-branch fold, ~0.9 µs per level over 0-12 levels.
Block bytes no longer enter the share path.
What it means for capacity. Against the deployed design point the issue names — ~4,096
connections at
PRISM_STRATUM_VARDIFF_TARGET_SECONDS=15, so ~273 shares/s:The findings comment's headline — 64k-81k shares/s of single-core capacity, "~230-300× headroom
over the design point" — held only at 0 transactions. Pre-fix it collapsed to ~408 shares/s at a
1 MB template, and the accept path alone crossed one full core at ~1.45 MB, inside the consensus
range. Post-fix, single-core capacity is template-size independent: 52k-91k shares/s and
0.30-0.53% of a core at every size measured.
Load average was 4.7-5.9 across the six runs; the machine was not idle.
thread_timeexcludesdescheduled time, the min-of-N statistic resists transient contention, and the alternating run
order is what makes the delta trustworthy under that load rather than the absolute values.
Fix
Serialize the block only for a hash that actually solved one.
block_passis not a heuristic here — it is the exact precondition.classify_submit_work(
share_submission.py:374) setsblock_worthy = submission.block_pass and credit_policy is not stale_grace, and every route that constructs aPrismBlockCandidaterequiresblock_worthy. Soblock_passis necessary for a candidate to exist at all, and gating on itcomputes a superset of what the landing path can ever ask for. An ordinary share can never need
the bytes.
This is deliberately not lazy materialization. The bytes are still built eagerly, on the
client thread, inside the same
assemble_submissioncall that already validates the coinbase —before a candidate object exists, and long before its durable intent is written. There is no
thunk to force, no cache to race, and no unmaterialized value that can reach the durable intent.
Validation ordering — the deliberate decision
Deferring serialization would normally move malformed-template detection off submission-assembly
and onto block landing, i.e. onto the money path at the worst possible moment. It does not here,
because per-template validation is already hoisted to job build, and has been all along:
direct_stratum.py:323-333transaction_hexes_from_templatevalidate_hexon everytx["data"]direct_stratum.py:393-396explicit-tuple pathvalidate_hexon every elementdirect_stratum.py:413merkle_branch_for_coinbasestrip_witness_transactionparses every transaction — strictly stronger than a hex checktemplate_artifacts.py:328-329transaction_hexes_from_template+witness_merkle_leaves_hex, decoding every transaction againmake_job_from_builder_manifest(direct_stratum.py:414) is the onlyDirectQbitStratumJobconstructor in
lab/,DirectQbitStratumJobis frozen, and the per-client stamp atjob_delivery.py:416replaces onlyjob_id,extranonce1_hex,share_target,share_difficultyandclean_jobs— nevertransaction_hexes. So the tuple every share readsis the validated one from build.
The only per-share-varying input to
serialize_blockwas the assembled coinbase, and that isstill parsed unconditionally on every share by
strip_witness_transaction(full_coinbase_hex)atdirect_stratum.py:493. That check is untouched and remains eager.So the per-share work removed here was re-validating immutable data that was already validated
at build. The measurement confirms the redundancy independently:
validate_hexis 55% of theterm at MB scale, split between a
bytes.fromhexprobe whose result is discarded and avalue.lower()copy that allocates even when the string is already lowercase.The durable boundary
block_candidate_intentpersistsblock_hexinto the restart intent. A new_candidate_block_hexhelper refuses to write an empty one for a realDirectQbitSubmission,raising on the client thread before the durable write. If the classifier coupling above were ever
broken, the block is already lost; persisting the empty value would lose it again after every
restart, as a candidate that can never be offered to the node.
Behaviour under the duck-typed landing guards
Both guards were stated requirements of this change:
hasattr(candidate.submission, "block_hex")(block_candidates.py:1972) — unchanged. Theattribute always exists on
DirectQbitSubmission; only its value is conditional. An ordinaryshare must not start looking like an embedder that retains no block bytes, and it does not.
getattr(submission, "block_hex", "")(block_candidates.py:278) — now routed through_candidate_block_hex, which preserves the historical""for embedders that lack theattribute entirely, and raises only for a real submission carrying an empty one.
Both are covered by tests.
Tests
assemble_submissionon an ordinary share does not callserialize_blockat all (patched toraise) and leaves
block_hexempty.block_hexbyte-identically to the previous unconditionalcall.
block_hexattribute exists on every submission, so the landing path'shasattrguardkeeps its meaning.
not move.
explicit-tuple routes, before any share can be assembled against that job; a well-formed one is
normalized at build.
block_candidate_intentrefuses a real submission with no serialized block, and still toleratesan embedder that retains none.
classify_submit_workacross the full(share_pass, block_pass, credit_policy)matrix: everynon-
shareroute impliesblock_pass. This is the coupling the gate rests on, pinned next tothe routing it constrains.
Two existing assertions in
test_prism_direct_stratum.pygained an explicitassertTrue(submission.block_pass), andtest_witness_commitment_uses_template_wtxids_for_serialized_blockmoved from nonce 0 to nonce 1:
bits 207fffffputs the network target at roughly half the hashspace, so a test that inspects a serialized block now has to use a hash that actually solved one.
Instrument
tests/perf/serialize_block_share_cost.pylands as a test instrument, stated explicitly per theprofiling-script rule. It is standard-library only, needs no database, network or coordinator,
and is not collected by
unittest discover -p 'test_*.py', so it adds no CI time. It existsso this number can be re-derived rather than trusted, and because #143's findings comment recorded
"performance work needs the real-threads/wall-clock driver class this investigation built" as an
open harness limitation.
tests/perf/serialize_block_share_cost.mdis its report.Verification
python -m unittest discover -s tests -p 'test_*.py'— 2,169 tests,only the five pre-existing
os.splicefailures intest_prism_job_builder, which failidentically on unmodified
413f51e(macOS has noos.splice; they pass on Linux CI).make test-prism-postgres-ledger— PASS.make test-prism-postgres-scale— PASS (carry=120000 shares=200000).python -m compileall -q docker lab tests examples scripts— OK;shellcheck -xover all tracked*.sh— OK;bash -n— OK.GIT_CONFIG_GLOBAL=/dev/nullso fixture commits did not inherit global signing settings.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.