Skip to content

Remove the meaningless shares-per-second gauge and give the coordinator lock a contention denominator - #161

Merged
kiwidream merged 2 commits into
2.x.xfrom
prism-shares-per-second-gauge-and-lock-total
Aug 19, 2026
Merged

kiwidream merged 2 commits into
2.x.xfrom
prism-shares-per-second-gauge-and-lock-total

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Two independent observability defects that #143's gate-evidence pass turned up
and spun out. Both are in the metrics tier, both are small, and neither touches
the share path's behaviour — only what it reports about itself.

  1. qbit_prism_shares_per_second published a number that was never a share
    rate. Removed.
  2. _ObservedRLock counted contended acquisitions with no denominator, so a
    contended percentage could not be derived from a live process. It now counts
    granted acquisitions too.

1. The gauge was measuring uptime, not throughput

lab/prism/metrics.py divided accepted_share_stats()[0] by
time.monotonic() - started_monotonic. The numerator is the durable
ledger's lifetime accepted count
— PrismCoordinator.accepted_share_stats
prefers ledger.accepted_share_stats, a whole-table aggregate maintained
incrementally across the ledger's entire history. The denominator is this
process's uptime
.

Those are different domains, so the published value tracked 1/uptime:
enormous immediately after a restart, decaying as the process aged, and at no
point the pool's throughput. The observed 3855.57 back-solves to roughly
4 h 23 min of uptime against a ~61M-share ledger — a fact about when the
coordinator last restarted, published under a name that reads as a share rate.
The design point for the deployed 4,096-connection cap is ~273 shares/s.

Removed rather than redefined. A process-local numerator would have been a
different metric wearing the same name, and a series that silently changes
meaning is worse for an operator than one that disappears — the second is
loud, the first is not. Nothing in this repository consumed the gauge.

What replaces it already exists:

  • qbit_prism_accepted_shares_total is unchanged and untouched. It is the
    trustworthy counter, and rate(qbit_prism_accepted_shares_total[5m]) is what
    the gauge was being reached for in the first place.
  • qbit_prism_vardiff_lane_accepted_shares_per_second already publishes a
    process-local since-start average per lane. Its numerator comes from
    VardiffService.note_accepted, which counts before the vardiff-enabled
    early-out precisely so lane share-rate accounting survives where vardiff is
    off. It is narrower than "accepted", and the help text now says so: the
    share writer gates that call on a newly inserted ledger row, and the startup
    recovery-journal replay bypasses it entirely, so an exact replay of an
    already-durable share and a recovered share are both acked accepted without
    being lane-counted. The lanes sum to this coordinator's commit rate.

The removal site carries a comment saying what the metric was and why it is
gone, so the next reader does not re-add it.

The lane gauge's help text was wrong in the same way

It advertised that it was "kept on the same elapsed formula as
qbit_prism_shares_per_second so the two stay comparable". They shared a
denominator and never shared a numerator — one was process-local, the other was
the ledger lifetime total — so the two were never comparable, and an operator
who trusted that sentence would have concluded the lanes were failing to sum to
the global figure. The help and the owning docstring now state what the
numerator actually is and what it does and does not sum to.

2. A contention counter needs a denominator

lab/prism/prism_coordinator.py — _ObservedRLock recorded contended
acquisitions, wait sum and wait max. All three are absolute numbers. From a
live process there was no way to turn them into a rate, because the count of
acquisitions that didn't wait was never recorded.

That gap is load-bearing for the incident this lock exists to diagnose. The
#143 evidence pass measured 0 contended acquisitions in ~48k during settled
steady state — even under saturating share load — flipping to 30–82%
contended
during a reconnect herd. Production reports
contentions_total = 1 at 21 connections. Without a denominator those three
observations are not comparable to each other, and "1" cannot be distinguished
from "not currently reproducing".

New: qbit_prism_coordinator_lock_acquisitions_total, published alongside
qbit_prism_coordinator_lock_contentions_total.

Why it is not a counter under _metrics_lock

The class docstring states the constraint: no shared mutex is taken on an
uncontended acquisition
, so that observing the lock cannot recreate the
share-path convoy the metrics exist to diagnose. A counter guarded by
_metrics_lock would put a second mutex acquisition on the fast path of the
coordinator lock — instrumentation that manufactures the contention it reports.

Instead the increment happens while the underlying RLock is already held,
on both the uncontended probe path and after a contended grant. That places it
inside a critical section the lock has already serialised: no mutex
acquisition, no atomic, and no cross-thread ordering that the lock did not
already impose. It cannot convoy the fast path, because at the moment it runs
no other thread can be in that region.

Explicitly: this does not add a GIL-atomicity assumption (#150)

Flagging this for #150's audit of load-bearing atomic-under-the-GIL assumptions
in this tree, since a bare += on a shared counter is exactly the shape that
audit is looking for:

  • The increment does not rely on being atomic under the GIL. The lock, not
    the interpreter, is what makes it safe. Every write happens with the RLock
    held, so it stays correct on a free-threaded build with no change.
  • One unsynchronised access exists and is deliberate: the read in
    contention_snapshot, which holds only _metrics_lock. It assumes an
    attribute read yields a whole value rather than a torn one, and may observe
    the counter one increment stale. Both are acceptable for a monotonic counter
    read by a metrics scrape, and neither is load-bearing anywhere else. Taking
    the coordinator lock to publish a metric would be the observation cost this
    class refuses to pay.

Both facts are stated in the class docstring at the point of the assumption,
not only here.

What it does and does not make derivable

Does: contended fraction, from a live process, comparable across steady
state and incident.

Does not: hold duty cycle, which needs hold duration. Not added, and the
reason is in the docstring: a re-entrant lock would need per-thread depth
tracking to avoid double-counting nested holds, and a clock read on every
acquire and release is the fast-path cost this class exists to avoid. The
herd-time hold attribution (note_tip_work_delivered 605–1388 µs,
accept_loop 1016 µs, schedule_initial_job 752 µs against 16–20 µs
share-path holds) came from out-of-band instrumentation and stays there.

Counting is by granted acquisition, including re-entrant re-acquisition,
because the contended counter is per acquire() call and the denominator must
match it. A wait that times out records contention without an acquisition, so
where a caller passes a timeout the derived fraction is an upper bound — the
help text says so and a test pins it.

Review follow-up

A mergeability review of the first commit returned no blocking findings and two
documentation corrections, applied in 4ce3a94 with no behaviour change:

  • The _ObservedRLock summary line still said "zero shared-metrics work on
    uncontended acquisitions", which the new counter makes literally false — it
    runs on every acquisition. The property that still holds is that no shared
    mutex is taken on an uncontended acquisition, and the docstring now says
    that, and says the counter preserves it by where it runs rather than by how
    often.
  • The lane gauge's replacement help text overstated its own numerator, as
    described above. Replacing wrong help text with narrower-than-stated help
    text would have repeated the defect this PR exists to fix.

Two further non-blocking observations were left alone deliberately. The new
contended-grant test signals before its waiter blocks and leans on a 20 ms
sleep — a false failure is possible under heavy descheduling, a false pass is
not, and it mirrors the existing idiom at
tests/test_prism_coordinator_metrics.py:139. And the
getattr(..., "contention_snapshot", None) fallback checks presence rather
than shape, so an out-of-tree embedder supplying the old 3-tuple would raise
rather than degrade to zeros; no such producer exists in this repository.

Tests

tests/test_prism_coordinator_metrics.py, three added:

  • every granted acquisition counts — uncontended, re-entrant, non-blocking, and
    a genuinely contended grant from a second thread — and the pair renders into
    the metrics lines;
  • a timed-out wait is contention without an acquisition, pinning the upper-bound
    semantics rather than leaving them to the help text;
  • the accepted-share rate is left to the counter: qbit_prism_shares_per_second
    is absent, qbit_prism_accepted_shares_total and the per-lane counter are
    present.

tests/test_prism_metrics.py mirrors the renderer's exact output line for line;
its reference implementation is updated in step.

Verification

Full CI-equivalent run in Docker (python -m compileall -q over
docker lab tests examples scripts, then unittest discover -s tests):
compileall clean; 2129 tests, and the failure set is identical to
origin/2.x.x at 413f51e in the same container
— 42 pre-existing
failures and errors that need a live PostgreSQL service, byte-for-byte the same
set on both. This branch adds 3 tests and no new failures.

Follow-ups filed, not fixed here

The same findings comment carried two items too large for this PR, filed as
their own issues rather than smuggled in:

Refs #143, #150, #159, #160.

…or lock a denominator

qbit_prism_shares_per_second divided the durable ledger's lifetime accepted
count by this process's uptime. The two are different domains, so the value
tracked 1/uptime rather than any share rate -- enormous right after a restart
and decaying as the process aged. The published 3855.57 back-solves to about
4 h 23 min of uptime, not to the pool's throughput.

Removed rather than redefined. A process-local numerator would be a different
metric wearing the same name, and a series that silently changes meaning is
worse for an operator than one that disappears. Nothing in the tree consumed
it. qbit_prism_accepted_shares_total is unchanged and is the trustworthy
counter; rate(qbit_prism_accepted_shares_total[5m]) is what the gauge was
reached for. The per-lane gauge already publishes the process-local
since-start average and its lanes sum to it.

The vardiff lane gauge's help claimed it was "kept on the same elapsed
formula as qbit_prism_shares_per_second so the two stay comparable". They
never were comparable -- the lane numerator is process-local and the removed
gauge's was the ledger lifetime total. The help and the owning docstring now
say what the numerator actually is.

_ObservedRLock recorded contended acquisitions but no total, so a contended
percentage could not be derived from a live process: 30-82% contended during
a reconnect herd and 0 in ~48k during steady state are indistinguishable from
the counter alone. It now also counts granted acquisitions, published as
qbit_prism_coordinator_lock_acquisitions_total.

The class does zero shared-metrics work on uncontended acquisitions by
design, so that observing it cannot recreate the convoy it diagnoses, and a
counter under _metrics_lock would have put a second lock acquire on the fast
path. Instead the increment happens while the underlying RLock is already
held, inside a critical section the lock has already serialised. It adds no
mutex acquisition and no cross-thread ordering the lock did not already
impose.

This deliberately does not rely on the increment being atomic under the GIL:
the lock is what makes it safe, so it stays correct on a free-threaded build.
The one unsynchronised access is the read in contention_snapshot, which
assumes an attribute read yields a whole value and may be one increment
stale. Both facts are stated in the class docstring so #150's GIL-assumption
audit finds them.

Only granted acquisitions count. A timed-out wait records contention without
an acquisition, so the derived fraction is an upper bound where a caller
passes a timeout; the help text and a test both say so. Hold duration is not
instrumented -- a re-entrant lock needs per-thread depth tracking to avoid
double counting nested holds, and a clock read on every acquire and release
is the fast-path cost this class exists to avoid.

Refs #143, #150.

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.

Two documentation corrections from the review of the previous commit. No
behaviour change.

The _ObservedRLock summary line still claimed "zero shared-metrics work on
uncontended acquisitions", which the acquisition counter makes literally
false -- it runs on every acquisition, contended or not. The property that
still holds, and the one that matters, is that no shared mutex is taken on an
uncontended acquisition. The docstring now says that, and says the counter
preserves it by where it runs rather than by how often.

The vardiff lane gauge's new help said its numerator counts "shares this
process accepted". It is narrower than that. VardiffService.note_accepted
runs only where the share writer sees a newly inserted ledger row, and the
startup recovery-journal replay commits recovered shares without passing
through it at all, so an exact replay of an already-durable share and a
recovered share are both acked accepted while never being lane-counted. An
operator reconciling the lanes against an accepted-ack count would find a
shortfall the old wording said could not exist. The help and the owning
docstring now name both exclusions and say the lanes sum to this
coordinator's commit rate.

Refs #143.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@kiwidream
kiwidream merged commit 04fd0b2 into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the prism-shares-per-second-gauge-and-lock-total branch August 19, 2026 20:08
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