Skip to content

Land PRISM concurrency instruments and fix harness classification - #170

Merged
kiwidream merged 5 commits into
2.x.xfrom
land-prism-concurrency-instruments
Aug 20, 2026
Merged

kiwidream merged 5 commits into
2.x.xfrom
land-prism-concurrency-instruments

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • fix the deterministic harness classifier so the share-ledger append_batch statement cannot be mistaken for an outbox insert
  • land the recovered payout-window GIL-scaling instrument with positive/negative controls, a control-floor abort, JSON capture, and render replay
  • add an on-demand real-thread PRISM session driver with paced, saturating, and reconnect-herd modes over the shipped coordinator/session/vardiff/share services
  • teach the harness model the explicit writer-lease retry arm used by Name writer-lease races and enforce read-only sessions #168, preserving loud rejection of unknown statement shapes

Why

The deterministic harness and a real-thread load driver answer different questions. The former pins exact interleavings under a baton scheduler and virtual clock; the latter measures wall-clock concurrency, latency, contention, and per-session herd recovery. Keeping both instruments in-tree makes future PRISM performance decisions repeatable without weakening the deterministic harness.

The lease retry-arm fixture is captured from #168 and is self-contained: tests perform no Git or network operations at runtime.

Validation

  • 266 harness and dependent unit tests passed
  • real-thread driver --selftest passed
  • paced, saturating, reconnect-herd, and PostgreSQL-backed smoke runs passed
  • recovered GIL instrument measurement and --render replay passed
  • mutation checks caught classifier and lease-arm policy regressions
  • Docker compile passed for docker, lab, tests, examples, and scripts
  • Docker Ruff passed on every changed Python path

Recorded baseline and limitations

The 1,024-session reconnect-herd baseline re-established 691 sessions and left 333 outstanding in the 50-second census, with zero admission rejections and watchdog misses. It recorded 49,106 coordinator-lock acquisitions but only one contended acquisition, so it did not reproduce the historical 30–82% contention range. That non-reproduction is retained as evidence, not presented as a resolved diagnosis.

These are on-demand instruments, not CI performance gates. Absolute figures remain host-dependent. The real-thread driver includes its own Python driver overhead, fakes node RPC plus the audit-bundle subprocess, and does not use a live qbitd; its in-memory and PostgreSQL ledger modes must be interpreted separately.

This test-only prerequisite lands before #167, #168, and the #159 admission fix.

Closes #156.
Closes #160.


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

kiwidream and others added 5 commits August 20, 2026 10:46
…lassifier (#156)

`OUTBOX_RECORD` was identified by two fragments that
`_append_batch_with_replay_outcomes` also emits: it opens the same
`INSERT INTO qbit_block_candidate_outbox (` and raises the same
`'block candidate payload mismatch'` as `persist_block_candidate_intent`.
A captured share submission therefore matched the outbox signature first
and was answered by the outbox evaluator, so the harness reported the
statement against the wrong state machine — arguing for an outbox defect
that did not exist while hiding the deferral that did.

Add the conflict action as a third required fragment. The intent writer
inserts a candidate with no share attached and leaves a colliding row
alone (`ON CONFLICT (block_hash) DO NOTHING`); the share append claims
that row (`ON CONFLICT (block_hash) DO UPDATE`). That difference is the
SQL-level statement of which caller owns the row, so it is a load-bearing
identity rather than an incidental token. At this baseline the fragment
occurs in exactly one ledger method.

Self-tests pin all three directions: the shipped `append_batch`,
captured at the port, now reaches `_DEFERRED_SIGNATURES` and names the
share-submission machine; `persist_block_candidate_intent` still
classifies as `OUTBOX_RECORD`; and the discriminator is asserted unique
to the intent writer, so a second emitter fails here rather than at the
next confusing scenario failure. Unknown SQL stays loud.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two on-demand drivers under tests/perf/, neither collected by test
discovery: their filenames do not begin with `test_` and nothing imports
them.

window_pipeline_gil_scaling measures how much of the payout-window
materialization pipeline is actually GIL-held rather than assumed to be.
This is recovered work, restored byte-for-byte from the artifact that
was already written rather than re-derived: cores-used via
process_time/perf_counter, positive and negative controls, a
control-floor abort, a wall-clock floor, alternating repetitions, load
average, a memory guard, JSON capture and render replay. The one
deviation from the recovered bytes is a `# noqa: F821` with its
reasoning: `inputs` is bound at the top of the loop body and released by
`del inputs` at the end of it, which is enough for Ruff to read the
closure as unbound, and measure_cores joins every thread before
returning so no invocation outlives the binding.

stratum_session_concurrency_load is rebuilt, because the original was
lost with its workspace and no reachable object contained it. It drives
the shipped StratumSessionService, VardiffService and
ShareSubmissionService through a real PrismCoordinator with real
threads, real sockets and a real wall clock -- deliberately not the
baton harness, which replaces the scheduler, clock and lock that this
question is about. Paced, saturating and herd modes; herd reports a
per-session re-establishment census including the exact count that never
returned, because a storm that settles at high throughput while a third
of the pool gets no work back is a failure a throughput-only report
would call a success. Metrics: cores-used, shares/s, CPU us/share, ack
p50/p95/p99/max, lock acquisitions/contentions with hold attribution by
call site, watchdog misses, rejections, and a fixed-work GIL-wait probe
that charges its own CPU so it cannot inflate the coordinator's.

Hold attribution lives in the driver, not in production: _ObservedRLock
is right that a clock read per acquire/release is the fast-path cost it
exists to avoid, so the wrapper is paid for only while measuring and
--no-lock-attribution quantifies it. No production code changes.

Ledger mode is selectable and named in every output -- in-memory to
isolate interpreter cost, or a real PsqlShareLedger through the
repository's real-server gate, since a shares/s figure means something
different with and without a durable write. Difficulty is not
permanently pinned: resume and climb both exercise the real retarget
path. The health abort refuses to report any settle, load, herd or lock
number when the host cannot demonstrate parallelism, and --selftest
asserts that the abort report contains none of them.

Co-Authored-By: Claude Opus 5 <[email protected]>
)

The acquire model hardcoded the pre-#140 result: when a first-acquire
race loser could see neither its own upsert nor a committed holder, the
evaluator returned SQL NULL unconditionally, and
test_first_acquire_race_loser_gets_an_unhelpful_error pinned the generic
"postgres query returned no JSON" diagnostic that produces. Once the
ledger PR adds an explicit not-acquired/retry arm that outcome is no
longer reachable, and a model that kept producing it would let a
scenario assert something the server can no longer do.

Read the shape off the statement instead. `acquire_result_arms` counts
the result arms of the final SELECT COALESCE and
`acquire_terminal_arm_keys` names the keys of the last one, both
computed from the SQL PsqlShareLedger actually emitted. Two arms is
today's shape and still evaluates to NULL; three or more carries a
terminal arm and cannot, so the evaluator answers it. Counting arms
rather than matching a chosen literal is deliberate: the arm has to
exist for the fix to work, whatever its author names its keys.

Unknown SQL stays loud in both new directions. A statement without the
recognised COALESCE, or with fewer than two arms, raises
UnsupportedStatement naming the shape; and the terminal arm's value
policy is narrow on purpose -- `acquired` is false, holder and lease
columns are null because nothing is visible, a retry flag is true, and
any other key raises rather than being guessed at.

The tests switch with the statement rather than being rewritten, and are
not vacuous. The forward branch is exercised now, against a terminal-arm
statement built from the shipped one, so a mistake in it surfaces here
rather than as a harness failure blamed on the ledger PR. Both
directions are pinned: the baseline is asserted to have exactly two arms
and the old diagnostic, and the new branch is asserted to retire it.
Mutating the arm counter to a constant, forcing either branch, or
letting an unteachable key through each fail this suite.

No production files are touched, and this stays green on the current
baseline.

Co-Authored-By: Claude Opus 5 <[email protected]>
The signed ledger branch renders a terminal arm with four keys:
`acquired` false, `lease_snapshot_retry` true, `lease` naming the
subject, and `retry_reason` carrying a sentence. The narrow policy
landed earlier answered two of them wrongly. It refused `lease`
outright, because the key was on neither of its lists. Worse, it
answered `retry_reason` with `True`, because the policy keyed on the
key's *name* and the name contains "retry" -- so it got
`lease_snapshot_retry` right by luck and would have reported a boolean
where production emits an explanation.

Answer what the statement says instead of what the key is called.
`acquire_terminal_arm_fields` pairs the terminal `json_build_object`
arguments and returns each value's raw SQL text, and the value reader
resolves `true`/`false`/`null` and single-quoted literals from it. The
subject and the reason therefore come out of the shipped SQL verbatim
and cannot drift from the wording the ledger PR chose. Splitting the
arguments respects parenthesised sub-expressions and quoted literals,
because the holder arm nests `GREATEST(0, EXTRACT(...))` and a reason
sentence must survive as one argument.

Unknown keys stay loud. The key set is still an allowlist, so a key this
model has never seen is refused even when its value is a perfectly
readable literal, and a literal key given a non-literal value is refused
rather than guessed at.

The new integration self-test reads `share_ledger.py` out of the signed
ledger commit read-only, renders its final COALESCE with that commit's
own retry constants, splices it onto the statement production emits
here, and requires the exact terminal object -- not NULL and not a
substitute. It matters that this reads the real arm: the synthetic
fixtures the first attempt was written against were chosen to match its
policy, which is exactly why both defects survived them. The expected
object is written out independently rather than derived from the same
parse, so the assertion cannot agree with itself.

Mutations checked: name-based values, a fixed guess for string literals,
a quote-blind splitter, a paren-blind splitter, a silently accepted
unknown key, a three-arm shape still answered as NULL, and the baseline
wrongly answered with the terminal object all fail this suite. Dropping
the doubled-quote branch does not, and is an equivalent mutant --
toggling the quote state twice over adjacent quotes yields identical
output -- rather than an untested path.

No production files are touched, and the current baseline stays green.

Co-Authored-By: Claude Opus 5 <[email protected]>
The integration self-test in a2ec459 read `share_ledger.py` out of a
foreign commit object and fetched it when absent. That is the wrong
trade for a test suite. It makes a result depend on the network and on
objects this repository does not own, so it fails on a shallow clone, a
pruned object or an offline runner for reasons that say nothing about
the tree under test -- and its skip-when-missing fallback was worse
still, because coverage that quietly disappears reads as coverage.

Remove it, along with the machinery it needed: the subprocess and
pathlib imports, `_git`, `_share_ledger_source_at`,
`_acquire_coalesce_tail`, and the `LEDGER_RETRY_COMMIT` constant. No
test path invokes git or opens a socket now, checked statically and by
running the suite with subprocess and socket replaced by tripwires that
raise: 34 tests, zero failures, zero skips.

What that test was protecting is kept. The terminal arm stays as the
captured fixture, spliced onto the statement production emits here, and
the exact expected object stays written out independently of it, so the
assertion still cannot agree with itself. The value-type assertions move
across with it -- a boolean in `retry_reason` is the precise defect the
first policy had, and dict equality alone would read as a typo check.
The provenance of the fixture bytes (PR #168, commit 869bb7e) is now a
comment documenting where to re-capture from, and nothing reaches for
it.

The literal-valued parser policy and the punctuation/quote regression
are untouched; `prism_concurrency_harness.py` does not change in this
commit. Coverage did not regress with the removal: name-based values, a
fixed guess for string literals, a quote-blind splitter, a paren-blind
splitter, a silently accepted unknown key, a three-arm shape answered as
NULL, and the baseline answered with the terminal object all still fail
this suite.

Co-Authored-By: Claude Opus 5 <[email protected]>

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 594b6b1891

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def bring_up(session: MinerSession) -> None:
started.wait()
try:
session.establish()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor the configured session-establishment window

Pass the census deadline into establish() rather than letting every client use connect_timeout_seconds. With the defaults, --herd-return-seconds 50 still gives each returning session only the 20-second connection deadline, so the reported “never re-established within 50s” count—and the recorded 333-session baseline—actually classifies clients after roughly 20 seconds. Conversely, when the connection timeout exceeds the census window, the join grace can count sessions that completed late.

Useful? React with 👍 / 👎.

control_floor = args.control_floor_fraction * max(threads)
results["methodology"]["control_floor_cores"] = control_floor
results["methodology"]["control_floor_fraction"] = args.control_floor_fraction
if positive_at_max is not None and positive_at_max < control_floor:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Gate stage results on the negative control too

Abort when the pure-Python negative control does not remain near one core, not only when the positive control misses its floor. On a free-threaded build or any host where the negative control unexpectedly scales, this code still emits stage results and interprets cores above 1 as GIL release even though the measurement model is invalid; the sibling session instrument already rejects this condition at 1.5 cores.

Useful? React with 👍 / 👎.

Comment on lines +1504 to +1505
if peak_rss is not None and peak_rss > config.max_rss_mb:
results["memory_guard"] = {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Withhold results when the memory guard is exceeded

Treat an exceeded RSS limit as an abort rather than merely attaching a warning after measurement. For runs whose working set crosses --max-rss-mb and may swap, the report still prints settle, load, herd, and lock numbers as normal, contradicting the instrument's stated health-abort contract and allowing host memory pressure to be mistaken for coordinator behavior.

Useful? React with 👍 / 👎.

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