Skip to content

Stop serializing the full block on every accepted share - #162

Merged
kiwidream merged 2 commits into
2.x.xfrom
skip-block-serialization-on-share-path
Aug 19, 2026
Merged

kiwidream merged 2 commits into
2.x.xfrom
skip-block-serialization-on-share-path

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Problem

assemble_submission serializes the entire block on every accepted share
(lab/prism/direct_stratum.py:500). serialize_block bytes.fromhex-decodes the coinbase plus
every entry of job.transaction_hexes — each through validate_hex, which decodes once more and
throws 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_hex is consumed only on the
block-candidate landing path: block_candidates.py:278 (the durable restart intent), :334,
:1870 (the submitblock RPC), and the hasattr guard 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 qbit
consensus.h with WITNESS_SCALE_FACTOR = 1, so weight units are bytes — corroborated by
compose.yaml:114 and by docker/ckpool/qbit-ckpool-preflight.py:494-544, which hard-fails
unless live getblocktemplate.weightlimit is exactly 2000000. The 0-transaction baseline is the
repo'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:

block bytes tx before µs/share after µs/share speedup term % of composite, before
158 (0-tx baseline) 0 9.0 8.3 1.1× 7.1%
100,000 200 255.6 13.8 18.5× 94.3%
500,000 1,000 1,235.2 15.1 81.7× 97.7%
1,000,000 2,000 2,447.4 15.9 154× 98.8%
2,000,000 (ceiling) 4,000 4,888.6 16.5 296× 99.9%

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 reaching
4,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:

block bytes shares/s before shares/s after % of one core at 273/s before after
158 85,889 91,261 0.32% 0.30%
500,000 808 56,189 33.79% 0.49%
1,000,000 408 53,912 66.89% 0.51%
1,500,000 272 51,995 100.45% 0.53%
2,000,000 204 52,060 133.53% 0.52%

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_time excludes
descheduled 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_pass is not a heuristic here — it is the exact precondition. classify_submit_work
(share_submission.py:374) sets block_worthy = submission.block_pass and credit_policy is not stale_grace, and every route that constructs a PrismBlockCandidate requires
block_worthy. So block_pass is necessary for a candidate to exist at all, and gating on it
computes 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_submission call 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:

where what it validates when
direct_stratum.py:323-333 transaction_hexes_from_template validate_hex on every tx["data"] job build
direct_stratum.py:393-396 explicit-tuple path validate_hex on every element job build
direct_stratum.py:413 merkle_branch_for_coinbase strip_witness_transaction parses every transaction — strictly stronger than a hex check job build
template_artifacts.py:328-329 transaction_hexes_from_template + witness_merkle_leaves_hex, decoding every transaction again artifact store

make_job_from_builder_manifest (direct_stratum.py:414) is the only DirectQbitStratumJob
constructor in lab/, DirectQbitStratumJob is frozen, and the per-client stamp at
job_delivery.py:416 replaces only job_id, extranonce1_hex, share_target,
share_difficulty and clean_jobs — never transaction_hexes. So the tuple every share reads
is the validated one from build.

The only per-share-varying input to serialize_block was the assembled coinbase, and that is
still parsed unconditionally on every share by strip_witness_transaction(full_coinbase_hex) at
direct_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_hex is 55% of the
term at MB scale, split between a bytes.fromhex probe whose result is discarded and a
value.lower() copy that allocates even when the string is already lowercase.

The durable boundary

block_candidate_intent persists block_hex into the restart intent. A new
_candidate_block_hex helper refuses to write an empty one for a real DirectQbitSubmission,
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. The
    attribute always exists on DirectQbitSubmission; only its value is conditional. An ordinary
    share 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 the
    attribute entirely, and raises only for a real submission carrying an empty one.

Both are covered by tests.

Tests

  • assemble_submission on an ordinary share does not call serialize_block at all (patched to
    raise) and leaves block_hex empty.
  • A block-worthy share materializes block_hex byte-identically to the previous unconditional
    call.
  • The block_hex attribute exists on every submission, so the landing path's hasattr guard
    keeps its meaning.
  • The coinbase/txid-preimage check still fires on a share that missed the block — validation did
    not move.
  • A malformed template transaction is rejected at job build, on both the template and
    explicit-tuple routes, before any share can be assembled against that job; a well-formed one is
    normalized at build.
  • block_candidate_intent refuses a real submission with no serialized block, and still tolerates
    an embedder that retains none.
  • classify_submit_work across the full (share_pass, block_pass, credit_policy) matrix: every
    non-share route implies block_pass. This is the coupling the gate rests on, pinned next to
    the routing it constrains.

Two existing assertions in test_prism_direct_stratum.py gained an explicit
assertTrue(submission.block_pass), and test_witness_commitment_uses_template_wtxids_for_serialized_block
moved from nonce 0 to nonce 1: bits 207fffff puts the network target at roughly half the hash
space, 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.py lands as a test instrument, stated explicitly per the
profiling-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 exists
so 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.md is its report.

Verification

  • Full Python unit suite: python -m unittest discover -s tests -p 'test_*.py' — 2,169 tests,
    only the five pre-existing os.splice failures in test_prism_job_builder, which fail
    identically on unmodified 413f51e (macOS has no os.splice; they pass on Linux CI).
  • make test-prism-postgres-ledger — PASS.
  • make test-prism-postgres-scale — PASS (carry=120000 shares=200000).
  • Lint in docker: python -m compileall -q docker lab tests examples scripts — OK;
    shellcheck -x over all tracked *.sh — OK; bash -n — OK.
  • Test commands that build temporary Git repositories were run with GIT_CONFIG_GLOBAL=/dev/null
    so fixture commits did not inherit global signing settings.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

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]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

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]>
@kiwidream

Copy link
Copy Markdown
Member Author

Review follow-up (9ec3b4d)

An independent Fable review of this branch returned MERGE with three findings. Two were actionable and are fixed here; the third is an observation I'm recording rather than changing.

F1 — the guard was stricter across a restart than the PR claimed (fixed)

The PR text said embedders that retain no block bytes "keep the historical empty-string behaviour." True at write time, but decode erases duck-typing: block_candidate_from_intent rebuilds every replayed candidate as a real DirectQbitSubmission, so a tolerated "" comes back wearing the strict type. The only caller that re-encodes a replayed candidate is the credit-on-accept append at block_finalization.py:1780, which runs after the block has landed — so the guard would have failed a credit for a block already in the chain.

I reproduced it end to end before fixing:

1. embedder intent written, block_hex = ''
2. replayed submission type: DirectQbitSubmission block_hex = '' block_pass = True
   credit_share_on_accept = True durable_replay = True
3. re-encode RAISED: block candidate submission carries no serialized block

Re-persisting an intent the durable row already holds is not the write this guard exists to stop, so it is now keyed on candidate.durable_replay. It 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 bytes for a block-worthy hash — but the claim and the code now agree.

F2 — the instrument's term columns were meaningless post-fix (fixed)

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. Detecting this from the numbers alone is unsafe — at the 0-tx point the isolated term is still smaller than the composite, so the ratio looks plausible while meaning nothing. The driver now asks the assembled submission whether its block_hex was materialized, renders both derived columns as n/a when it was not, explains why in a footnote, and emits null rather than NaN so --json stays strict JSON.

F3 — stale-grace block solves still serialize (no change)

A hash that solves the block on a stale-tip job sets block_pass and serializes, then classify_submit_work makes it non-block-worthy and the bytes are discarded. This is exactly the superset the gate is documented to compute, requires a block solve on a stale tip to occur at all, and is correctness-neutral. Seen and judged acceptable.

Independently checked by the review

  • Attack 1-3 clean. block_pass is necessary for every consumer of block_hex; validation ordering verified exhaustively against every dataclass_replace in lab/ touching a job or its containers; no unguarded "" consumer in lab/, tests/, the Rust crates, docker/, or scripts/.
  • The nonce change is a genuine fix, not a papered-over regression. Rebuilt independently: at nonce 00000000 that fixture's hash misses both targets, so the old test inspected a serialized block for a hash that had solved nothing and passed only because serialization was unconditional.
  • Numbers replicate in shape. On different hardware, term slope 8.088 µs/KB at R² 0.99922; divided by the 3.134× anchor-derived host factor that is 2.58 µs/KB against the claimed 2.43, and 0.249 µs/tx against the claimed 0.25 — inside the run-to-run spread the report documents. The flat after-column replicated directly.
  • Instrument landing endorsed, with non-collection by CI verified three ways (the workflow's exact discover pattern, the filename, and the absent __init__.py).

Verification

Full suite 2,171 tests, only the five pre-existing macOS-only os.splice failures; make test-prism-postgres-ledger PASS; compileall and shellcheck in docker OK.

@kiwidream
kiwidream merged commit e4dc8d9 into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the skip-block-serialization-on-share-path branch August 19, 2026 20:53
kiwidream added a commit that referenced this pull request Aug 25, 2026
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]>
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.

1 participant