Repository navigation
Add a deterministic concurrency harness for PRISM, proven against the writer-lease lifecycle - #139
Merged
Merged
Conversation
The concurrency defects this line keeps shipping share a shape: two owners interleave around a PostgreSQL row, and the bad schedule is too rare to reproduce by running the coordinator and hoping. Every one was found in production or in review, never by a test. The nine-slice refactor removed the structural reason for that, so this adds the missing tool: a scheduler that makes an interleaving an input rather than an accident. The harness has three parts. A baton scheduler runs real threads one at a time, stopping only at named checkpoints placed at PostgreSQL statement boundaries, so the controlling test decides who runs next and the resulting schedule is order-stable rather than merely likely. A virtual clock backs every interval the lease lifecycle measures about itself, so nothing sleeps in wall-clock time. An in-memory PostgreSQL model covers the semantics the lease lifecycle actually depends on: tuple locks held for a transaction's lifetime, FOR NO KEY UPDATE SKIP LOCKED declining to queue, per-statement READ COMMITTED snapshots, lock and statement timeouts, session-scoped advisory locks, and pg_stat_activity locker attribution against a snapshot-visible xmax. Substitution runs through ports rather than monkeypatching. LedgerSqlPort and LeaseGuardPort name the two seams PsqlShareLedger already wrote through, and the constructor now takes sql_backend_factory, lease_guard_factory and monotonic alongside the existing lease_retry_sleep. No bound method is reassigned and no clock is patched, so the code under test stays the shipped code: the real retry loop, the real CAS SQL, the real adoption arithmetic, the real fail-closed branches. FakePostgres answers statements by recognising them against fragments lifted from the production SQL, and raises on anything else. Statements belonging to the state machines deferred to follow-up PRs are recognised only well enough to name the follow-up. A fake that silently answers an unrecognised statement drifts from production without anyone noticing; this one fails instead. Issue #123 is the proving ground. Its trigger sequence now runs without a live Postgres: a coordinator vanishes in the gap between a deadline-scoped statement completing and its COMMIT, leaving an open transaction holding the lease tuple lock, and a failover twin parks on that lock inside PsqlShareLedger.__init__ with no deadline anywhere in the system that can release it. The schedule is identical across repeated runs. One test in this commit fails, deliberately. OrphanedLeaseLockFailoverBoundTests asserts the bound #123's fix must establish, and #123 is not fixed on this line: the startup lease upsert runs with no lock_timeout, so nothing bounds the successor's wait. That assertion is written against the fixed behaviour rather than against today's, because weakening it to green would delete the only executable statement of what #123 asks for. It turns green when the fix lands. Refs #128, #123 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…y fixes Completes the writer-lease lifecycle as the harness's proving ground. Three scenario modules, each driving shipped code through the harness rather than re-describing it: Renewal against a competing expiry claim. The heartbeat renews uncontended; an expired row whose skipped lock belongs to a different-identity claimant fails closed, and the control proves it is the combination that raises rather than either half; the documented attribution misfire — this coordinator's own fenced write committing between the verification statement's MVCC snapshot and its live pg_stat_activity probe — is driven at exactly that checkpoint and resolved by exactly one recheck; a claim that commits fences the session. Heartbeat during a long fenced statement. The verification crosses an in-flight fenced write without ever queueing, skipping renewal and resuming it the moment that write commits. The control runs the pre-fix locking spelling into the same lock and watches it die on the guard's statement timeout, which is what makes renewed_count == 0 mean "declined a lock that was really there" rather than "nothing was attempted". An own fenced write outlasting the TTL defers instead of self-fencing, and the same expired row locked by a foreign application_name still fails closed. Takeover and epoch fencing. The advisory guard keeps a same-identity successor out of the lease upsert entirely; adoption silence is measured from the successor's own guard acquisition even when the row is already far staler than the interval; the CAS rewrites the session token and fences the predecessor; a lost CAS re-observes after a fresh full interval instead of refusing the token permanently; and a different epoch refuses an unexpired lease while taking an expired one through the ordinary expiry CAS. Two fidelity fixes to the model, both found while reviewing the above. A cancelled lock wait now reports which bound fired. A caller deadline arrives as SET LOCAL lock_timeout, while the guard session's bound is a connection-level statement_timeout; PostgreSQL reports them with different messages, and the whole point of the SKIP LOCKED heartbeat is that the guard's bound is the fatal one, so blurring them would let a scenario assert the wrong mechanism. Vanishing a coordinator no longer fabricates an orphan on a path that cannot produce one. An explicit transaction's COMMIT is a separate client message, so a vanished client leaves it open forever; an autocommit statement has no such message and PostgreSQL finishes and commits it. #123 is explicit that the orphan shape did not exist before the deadline plumbing arrived, and a model that offered it on the autocommit path would argue for a fix to a defect that path cannot reach. Determinism: eight assert_deterministic tests at 25 repeats each, every one asserting an exact checkpoint schedule rather than merely that runs agree. Twenty consecutive full runs of the five modules produce an identical result. Refs #128 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. |
This comment has been minimized.
This comment has been minimized.
An adversarial review pass verified the model's PostgreSQL claims against a scratch PostgreSQL 16.15 cluster and found two defects that mattered. The model re-read committed state after a tuple-lock wait. PostgreSQL takes one snapshot per command in READ COMMITTED: a statement that blocks re-reads only the conflicting tuple, through EvalPlanQual, to evaluate its write predicate, while every other scan in the statement keeps the original snapshot. So a queued acquire reports the pre-wait row and a lease_age_seconds that has silently absorbed the entire wait, where the model reported a fresh row and a small age. That age is the row edge of _writer_lease_adoption_wait_seconds, so the model was hiding the very input that makes the adoption CAS's updated_at predicate load-bearing: in the model the observation was always fresh, and the CAS would have matched even with that predicate deleted. Evaluation now takes the snapshot before any lock wait, resolves write predicates against the freshly locked version, and reports results from the snapshot. Statements that evaluate to SQL NULL return None and go through production's own parse_single_json_value, rather than being smoothed over. That surfaced a real production behaviour the model had been concealing. When two coordinators race the first ever acquire, the loser's DO UPDATE matches nothing and its COALESCE fallback reads a snapshot in which no row exists yet, so the whole statement returns NULL and PsqlShareLedger.__init__ dies with "postgres query returned no JSON" — an error naming neither the lease nor the coordinator holding it. The harness's own contention self-test was constructing exactly that interleaving and turning it into a clean refusal. It now asserts the real error, and a dedicated test pins the contrast against the ordinary "lease is held by" refusal. The deliberately failing #123 test asserted a bound the fix it names would not have satisfied. It advanced the clock once and drained once, so a fix built from lock_timeout plus a bounded retry — which is what #123 proposes — would have left the successor parked on the first of several short deadlines with the test still red, and the person landing that fix looking at a red test and reaching for the weakening this test exists to refuse. It now drives the successor through every deadline it reaches. Both candidate fixes were simulated: lock_timeout alone and lock_timeout with a bounded retry each turn it green, and it stays red on this line. Four smaller model corrections. A non-matching UPDATE no longer queues on the tuple lock, because PostgreSQL evaluates the predicate against the snapshot version and never locks a row it excludes; latent today, but it would have misrepresented any fencing argument, where "the predecessor is blocked" and "the predecessor already knows it lost" are different states. Tuple-lock waiters are granted in arrival order rather than whichever the controller steps first. Pool exhaustion honours the caller's deadline instead of waiting forever. The guard session's serialization is now pinned against _NativePostgresLeaseGuard._query_lock itself, since deleting that lock left every assertion in the harness-level test green. The two new protocols had no executable contract: the repository runs no mypy, they were not runtime-checkable, and the signature test compared parameter names only. They are now @runtime_checkable, asserted against both the production classes and the fakes, and checked with full signatures across every method. LedgerSqlPort.pool_size is dropped, being surface nothing reads. Two production tidies from the same pass. The lease clock is a declared class attribute overridden per instance, rather than a getattr fallback that would silently revert to wall-clock time under a rename. _pool_application_name is injectable, removing the last uncontrolled nondeterminism inside the code under test — lease_locked_by_this_process turns on that value, so a scenario that surfaced it would have failed the determinism check for reasons nothing in the harness explained. Full suite: 2023 tests, failures limited to the five pre-existing macOS os.splice tests and the one intentional #123 assertion. Twenty consecutive runs of the five harness modules are identical. Refs #128, #123 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The repository configures no Python linter — CI runs shellcheck, bash -n and compileall — so this is a quality pass on the files this branch adds rather than a fix for a failing check. Run with ruff in Docker. Real findings, fixed: a stale noqa suppressing BLE001 on an `except BaseException` the rule does not apply to; Callable imported from typing rather than collections.abc; an unsorted __all__; re.S in place of re.DOTALL; a three-line if/return that is just its own condition; __enter__ annotated with the concrete class rather than Self, imported under TYPE_CHECKING so no runtime version floor is introduced. The guard serialization test caught a blind `except Exception: pass`, which was hiding what the test actually proves. It now catches the AttributeError the statement itself raises once past the query slot, and asserts it fired: reaching the statement is the evidence, and any other outcome means run_json did not get where the test claims. Two findings are deliberately left. Every test module in this repository carries a shebang without the executable bit, so EXE001 is the house convention and departing from it in six files would be the anomaly. The `noqa: E402` on the deferred share_ledger import is reported unused only because E402 is not enabled in this ad-hoc invocation; the import genuinely does follow a sys.path statement, so the suppression is correct and documents why. Also corrects a comment the review pass flagged as overstated: the baton timeout cannot change what a run does, but it is not free of consequence, and claiming it "cannot make a passing run flaky" overstated a real if remote failure mode. Refs #128
The assertion is unchanged. What changes is who gets told about it, and when. Left as a plain failure, it made every CI run on this branch red, which is a poor way to communicate one known-open issue: a permanently red check is indistinguishable from a broken one at a glance, and it teaches people to stop reading CI. Three separate readers took the red "Lint, compile, and test" badge for a lint failure, which is the failure mode in miniature. unittest reports an unexpected success as a suite failure, so the marker is self-removing: the day someone fixes #123 the suite goes red and hands them this file, which is exactly when learning about it is useful. Verified rather than assumed — a marked test that starts passing does set wasSuccessful False. The marker is only defensible because the assertion genuinely goes green under a real fix, which it did not before the drive-to-quiescence correction. Both candidate fixes named in #123 were simulated again against this commit: lock_timeout alone, and lock_timeout with a bounded retry, each turns it green and each leaves 2.x.x red. An expectedFailure on a test that would stay red after the fix would be strictly worse than a plain failure, and that is the state this branch was in two commits ago. Full suite: 2023 tests, one expected failure, and the five pre-existing macOS os.splice failures that pass on Linux. Ten consecutive runs of the five harness modules report OK with one expected failure every time. Refs #128, #123
This was referenced Aug 18, 2026
Closed
Closed
kiwidream
added a commit
that referenced
this pull request
Aug 19, 2026
…ng (#148) * Extend the deterministic concurrency harness to block candidate landing Issue #128 ranks block candidate landing first by incident history, and the harness landed by #139 covered only the writer-lease lifecycle. This teaches it the landing state machine, which is the one owner where two threads of the same process reach the same durable rows. The PostgreSQL model gains the rows landing turns on: qbit_pool_blocks, qbit_block_candidate_outbox, the qbit_confirm_pool_block publication ordinal allocator and the durable floor read. The allocator is modelled on the shipped PL/pgSQL rather than on an approximation of it: the ordinal comes from a sequence, so an exact replay of an already-confirmed row burns nothing, a terminally disposed row reports the superseded disposition, and an aborted confirmation leaves a gap the MAX-based floor tolerates. That distinction is the whole of the two-tail defect -- a later ordinal can publish first and leave an earlier one behind the floor. Landing writes are staged per transaction for the same reason lease writes already were: a deadline-scoped statement sends COMMIT as a separate message, and the interesting window is inside it. Statement classification is anchored on fragments lifted verbatim from the production SQL, as the lease signatures already are, so a change to that SQL breaks classification loudly instead of quietly changing what the fake models. Where a modelled statement is a large CTE, the model reproduces the effects a landing reads back and says so. Three new pieces support the topology. Scheduler-aware locks, conditions, semaphores and events make a contended process-local lock an interleaving point rather than a wedged baton -- the lease scenarios never needed them, because they interleave two processes around one row, while the two landing tails share the payout-balance serializer, the publication order guard and the ledger's admission gates. Phase breakpoints let a scenario stop a tail at a boundary the landing already names for its own watchdog, because landing's interesting windows are the gaps between statements and no statement runs at the instant that matters. And HarnessBase now holds what every state machine's harness owns, so run_scenario and assert_deterministic are generic over it rather than typed to one harness; the two owners still owed to #128 plug in without touching the determinism check again. The acceptance criterion is #133's two-distinct-hash interleaving, driven end to end: block A confirms on the synchronous client-thread tail, block B lands on the accounting actor inside A's confirm-to-publish window and publishes the next ordinal, and A then publishes behind the raised floor. It is already fixed here, so the scenario passes; the evidence is that the interleaving can be expressed at all, which nothing could do before. The suite also pins the load-bearing claim underneath it -- the per-hash disposition lease does not serialise distinct hashes -- and the fresh lease proof that gates the superseded-envelope restore. Every scenario is proved order-stable over 25 runs of the full checkpoint trace. Refs #128, #133. * Drive the #125 escalated landing budget against the watchdog Issue #125: a landing-class ledger step is two waits, not one. The caller queues for the ledger writer lock -- local, unbounded by any statement deadline -- and only then runs the statement it queued for, under its own full budget. Both are spent on the block-work thread the watchdog monitors, and before 49f04c3 both were heartbeat-silent, so an escalated landing at the reviewed 120s cap could hold the heartbeat still for ~240s against a 120s tolerance. The watchdog hard-exited mid-landing and the in-memory escalation counter died with the process, so the restart came back at the 30s base to repeat the cycle. Add landing-harness scenarios for both halves of the fix: - a real accounting tail queued behind a held writer lock stamps wait-ledger-admission:landing every slice instead of going quiet, and an A/B against the same gate at the same budget with no progress hook shows slicing changes nothing about when the wait ends; - the escalation ladder is climbed by genuinely timed-out landings and every rung's admission-plus-statement pair fits the watchdog tolerance, across a clamped cap, a clamped base and a configuration needing no clamp at all, with the clamp reported exactly once; - both composed: a landing that queues for all but one slice of its escalated budget still lands, inside the tolerance, with no silence longer than one slice. Every scenario is proved order-stable with assert_deterministic. Co-Authored-By: Claude Opus 5 <[email protected]> * Pin the landing half of the concurrency harness with self-tests The lease half of the deterministic harness is defended by tests/test_prism_concurrency_harness.py; the landing half added in cefdbfa was not. A fake that answers an unrecognised statement plausibly drifts away from production silently, and every scenario built on it inherits the drift, so a landing scenario that failed could not distinguish "the code under test is wrong" from "the model is wrong". tests/test_prism_landing_harness_model.py pins the model's own contract in four parts: - The publication-ordinal allocator against qbit_confirm_pool_block: a fresh confirmation takes the next sequence value, an exact replay returns 1 without burning one (proved by the next block's ordinal), every terminal disposition reports -1 rather than 0, a height mismatch and a missing row both report 0, and the durable floor — a MAX over the table — stays put across the gap an aborted confirmation leaves behind. - Transaction scope: a deadline-scoped landing write is invisible to another session until COMMIT and visible to its own before it, and a rolled-back landing leaves no row while keeping its ordinal burned. - Classification: every LandingOp is driven through the shipped PsqlShareLedger method that emits it, a landing table mention that matches no signature raises naming _LANDING_SIGNATURES, the deferred markers still name their follow-up state machine, and a deposed writer fails the lease CTE in the two shapes the SQL dictates — the outbox statements report it, the PL/pgSQL functions raise. - The synchronisation primitives: mutual exclusion and FIFO grants, non-blocking and virtual-clock-timed acquires, the non-reentrant re-acquire that a real mutex would deadlock on, RLock depth, the condition's release/re-acquire and restored depth, semaphore exhaustion and over-release, and the event's parked and timed waits. One landing scenario is proved order-stable with assert_deterministic against LandingHarness. Nothing sleeps in wall-clock time. Co-Authored-By: Claude Opus 5 <[email protected]> * Pin the vardiff resume TTL-boundary test to an exact clock base The retention test captured time.monotonic() and asserted that a silent reconnect cycle at exactly +TTL still resumes, relying on the store's strictly-greater expiry comparison. That boundary arithmetic is not exact for an arbitrary float base: (start + 900.0) - start rounds above 900.0 for roughly one in five thousand captured clock values, which flips the boundary cycle to expired and fails the test. CI hit this on the push run for the map commit while the pull_request run of the same commit passed. Every record and lookup in the test runs under frozen_clock, so the base never needs to be a real monotonic reading. Pin it to an exactly-representable constant, making the boundary arithmetic exact. Refs #145. --------- Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Alex <[email protected]>
kiwidream
added a commit
that referenced
this pull request
Aug 20, 2026
* Extend the deterministic concurrency harness to block candidate landing Issue #128 ranks block candidate landing first by incident history, and the harness landed by #139 covered only the writer-lease lifecycle. This teaches it the landing state machine, which is the one owner where two threads of the same process reach the same durable rows. The PostgreSQL model gains the rows landing turns on: qbit_pool_blocks, qbit_block_candidate_outbox, the qbit_confirm_pool_block publication ordinal allocator and the durable floor read. The allocator is modelled on the shipped PL/pgSQL rather than on an approximation of it: the ordinal comes from a sequence, so an exact replay of an already-confirmed row burns nothing, a terminally disposed row reports the superseded disposition, and an aborted confirmation leaves a gap the MAX-based floor tolerates. That distinction is the whole of the two-tail defect -- a later ordinal can publish first and leave an earlier one behind the floor. Landing writes are staged per transaction for the same reason lease writes already were: a deadline-scoped statement sends COMMIT as a separate message, and the interesting window is inside it. Statement classification is anchored on fragments lifted verbatim from the production SQL, as the lease signatures already are, so a change to that SQL breaks classification loudly instead of quietly changing what the fake models. Where a modelled statement is a large CTE, the model reproduces the effects a landing reads back and says so. Three new pieces support the topology. Scheduler-aware locks, conditions, semaphores and events make a contended process-local lock an interleaving point rather than a wedged baton -- the lease scenarios never needed them, because they interleave two processes around one row, while the two landing tails share the payout-balance serializer, the publication order guard and the ledger's admission gates. Phase breakpoints let a scenario stop a tail at a boundary the landing already names for its own watchdog, because landing's interesting windows are the gaps between statements and no statement runs at the instant that matters. And HarnessBase now holds what every state machine's harness owns, so run_scenario and assert_deterministic are generic over it rather than typed to one harness; the two owners still owed to #128 plug in without touching the determinism check again. The acceptance criterion is #133's two-distinct-hash interleaving, driven end to end: block A confirms on the synchronous client-thread tail, block B lands on the accounting actor inside A's confirm-to-publish window and publishes the next ordinal, and A then publishes behind the raised floor. It is already fixed here, so the scenario passes; the evidence is that the interleaving can be expressed at all, which nothing could do before. The suite also pins the load-bearing claim underneath it -- the per-hash disposition lease does not serialise distinct hashes -- and the fresh lease proof that gates the superseded-envelope restore. Every scenario is proved order-stable over 25 runs of the full checkpoint trace. Refs #128, #133. * Drive the #125 escalated landing budget against the watchdog Issue #125: a landing-class ledger step is two waits, not one. The caller queues for the ledger writer lock -- local, unbounded by any statement deadline -- and only then runs the statement it queued for, under its own full budget. Both are spent on the block-work thread the watchdog monitors, and before 49f04c3 both were heartbeat-silent, so an escalated landing at the reviewed 120s cap could hold the heartbeat still for ~240s against a 120s tolerance. The watchdog hard-exited mid-landing and the in-memory escalation counter died with the process, so the restart came back at the 30s base to repeat the cycle. Add landing-harness scenarios for both halves of the fix: - a real accounting tail queued behind a held writer lock stamps wait-ledger-admission:landing every slice instead of going quiet, and an A/B against the same gate at the same budget with no progress hook shows slicing changes nothing about when the wait ends; - the escalation ladder is climbed by genuinely timed-out landings and every rung's admission-plus-statement pair fits the watchdog tolerance, across a clamped cap, a clamped base and a configuration needing no clamp at all, with the clamp reported exactly once; - both composed: a landing that queues for all but one slice of its escalated budget still lands, inside the tolerance, with no silence longer than one slice. Every scenario is proved order-stable with assert_deterministic. Co-Authored-By: Claude Opus 5 <[email protected]> * Pin the landing half of the concurrency harness with self-tests The lease half of the deterministic harness is defended by tests/test_prism_concurrency_harness.py; the landing half added in cefdbfa was not. A fake that answers an unrecognised statement plausibly drifts away from production silently, and every scenario built on it inherits the drift, so a landing scenario that failed could not distinguish "the code under test is wrong" from "the model is wrong". tests/test_prism_landing_harness_model.py pins the model's own contract in four parts: - The publication-ordinal allocator against qbit_confirm_pool_block: a fresh confirmation takes the next sequence value, an exact replay returns 1 without burning one (proved by the next block's ordinal), every terminal disposition reports -1 rather than 0, a height mismatch and a missing row both report 0, and the durable floor — a MAX over the table — stays put across the gap an aborted confirmation leaves behind. - Transaction scope: a deadline-scoped landing write is invisible to another session until COMMIT and visible to its own before it, and a rolled-back landing leaves no row while keeping its ordinal burned. - Classification: every LandingOp is driven through the shipped PsqlShareLedger method that emits it, a landing table mention that matches no signature raises naming _LANDING_SIGNATURES, the deferred markers still name their follow-up state machine, and a deposed writer fails the lease CTE in the two shapes the SQL dictates — the outbox statements report it, the PL/pgSQL functions raise. - The synchronisation primitives: mutual exclusion and FIFO grants, non-blocking and virtual-clock-timed acquires, the non-reentrant re-acquire that a real mutex would deadlock on, RLock depth, the condition's release/re-acquire and restored depth, semaphore exhaustion and over-release, and the event's parked and timed waits. One landing scenario is proved order-stable with assert_deterministic against LandingHarness. Nothing sleeps in wall-clock time. Co-Authored-By: Claude Opus 5 <[email protected]> * Scope the PRISM append-invalidation epoch per anchor (#126) The append-invalidation epoch is one global counter, so a landing that compares its own baseline against the live value learns only that some payout window was invalidated. A share stamped later than this candidate's declared anchor -- but early enough to predate a newer exposed window -- bumped that counter without touching this candidate's window, and the pre-offer fence read the inequality and terminally abandoned the candidate as append_epoch_stale. On the fallback submit lane that happens before qbitd ever sees the block, so a valid block's reward is forfeited. Record, with each bump, the stamp of the row that caused it (max(job_issued_at_ms, accepted_at_ms) -- exactly what _pending_share_predates_anchor compares), keep the most recent 256 in a bounded map alongside the oldest epoch still retained, and let a landing ask whether any bump in (baseline, live] was caused by a row that predates its own declared anchor. Both landing fences ask that instead of comparing counters. The predicate fails closed on everything it cannot prove: an unknown declared anchor, a baseline older than the retained history, or a gap in the scanned range. The post-offer branch is untouched -- it already logs rather than abandons -- and collection_only candidates stay exempt. The relaxation rests on the existing ordering: a landing exposes its declared anchor and drains unfenced in-flight appends before its fences arm, so every append that could predate the anchor has already bumped or bumps behind the fence. tests/test_prism_landing_append_epoch.py drives all of it through the landing harness: the over-abandon (now lands, confirms, publishes), the fail-closed pairs at and inside the anchor, both fences (the bump placed between the advisory read and the fence-held one via phase:tip-height-rpc), a pruned history, and a candidate with no declared anchor. Every scenario is proved order-stable with assert_deterministic. Co-Authored-By: Claude Opus 5 <[email protected]> * Pin the vardiff resume TTL-boundary test to an exact clock base The retention test captured time.monotonic() and asserted that a silent reconnect cycle at exactly +TTL still resumes, relying on the store's strictly-greater expiry comparison. That boundary arithmetic is not exact for an arbitrary float base: (start + 900.0) - start rounds above 900.0 for roughly one in five thousand captured clock values, which flips the boundary cycle to expired and fails the test. CI hit this on the push run for the map commit while the pull_request run of the same commit passed. Every record and lookup in the test runs under frozen_clock, so the base never needs to be a real monotonic reading. Pin it to an exactly-representable constant, making the boundary arithmetic exact. Refs #145. * Close the disarm gap in the anchor-scoped append epoch (#126) The anchor-scoped predicate reads recorded bumps, so it is only as sound as the guarantee that every append predating a landable window's anchor actually bumps. That guarantee had a hole: a seeded window's anchor is exposed to the append-side predates() checks only by the armed payout-ledger artifact, and the bump that consults that anchor also disarms the artifact. The live anchor set could then go empty while jobs from earlier windows were still landable, and a replay row genuinely predating such a candidate's declared anchor committed silently -- _record_late_visible_payout_append returned None, no bump, no stamp -- so the landing's fences read only harmless history and submitted an invalidated window. Demonstrated with a deterministic interleaving: the pre-#126-fix tree failed closed on it; the anchor-scoped tree submitted. Route every write to the armed-artifact slot through _replace_payout_ledger_artifact_locked, which folds the outgoing artifact's snapshot anchor into the monotone, never-retired published-job-window watermark before the slot moves. The fold runs under _job_cache_lock -- the same lock every predates() read takes -- so no append can observe the anchor gone with the watermark not yet raised. The invariant that now actually holds, and that the fence comments now state: the anchor-set maximum never decreases while any job is landable, so every append that predates a live or seeded anchor bumps and leaves a stamp for the fences to read. The watermark's permanence is what the per-anchor predicate makes affordable: the extra bumps a retired anchor forces come only from replay-shaped rows (the pending-commit floor keeps ordinary commits above every job anchor) and are forgiven per anchor rather than over-abandoning. Reword the authoritative-fence comment in block_finalization.py: it claimed the recorded stamps were "the whole history the block's window can still see", which held for bumps but not for predating appends until the fold above made every predating append bump. Also pin the recorded stamp's max(job_issued_at_ms, accepted_at_ms) choice, which every equal-stamp scenario left indistinguishable from min() or either stamp alone: a straddling row -- issued at or before the candidate's anchor, accepted after -- does not predate the window, and recording anything but the max would abandon a valid block, resurrecting the #126 over-abandon. tests/test_prism_landing_append_epoch.py gains the disarm-gap scenario (premise: the bump disarmed the artifact; verdict: nothing submitted) and the straddling pair (lands, and abandons once both stamps predate), all proved order-stable with assert_deterministic; the landing harness's append_late_visible_share learns an additive accepted_at_ms. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Alex <[email protected]>
kiwidream
added a commit
that referenced
this pull request
Sep 11, 2026
* Shard PRISM coordinator tests by domain Re-cut of the original test sharding against current 1.x.x (36267d6): the two monolithic coordinator test files split into nine domain shard files plus two shared no-environment support modules, with the current test bodies as the source of truth. All 609 sharded test methods are conserved exactly once, and dependent test files change import paths only. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM coordinator core owners Re-cut of the original core-owner extraction against current 1.x.x (36267d6). Fifteen owner modules leave prism_coordinator.py at 15,436 lines (from 31,041): coordinator_config (immutable snapshot construction, all env reads), rpc (JsonRpc + transport retry policy), bounded_executor, ctv_runtime, progress_health, template_artifacts, bundle_compiler, job_bundle, job_delivery, tip_refresh, stratum_session, share_writer, payout_state, background_services (incl. the ledger lease heartbeat service), coordinator_shutdown. The old extraction commit served as the placement and wiring map; every moved body is the current coordinator implementation, so all upstream fixes through #120 are carried, including the landing-class deadlines, degraded accepted-parent previews, append/anchor fencing, tip-refresh epoch waves and lease fencing. Coordinator compatibility facades, private-name aliases and descriptor- routed legacy fields preserve every existing import path and test seam. share_ledger gains typed exact/conflict share replay consumed by the share writer; the Postgres ledger shell test asserts the new replay semantics. Nine owner-boundary test files are added (116 tests) and support modules gain typed-recovery fakes; no existing behavioral assertion is weakened. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM audit artifact ownership Re-cut of the original audit-artifact extraction against the rebuilt PR 74 layer. lab/prism/audit_artifacts.py owns every audit path and filesystem mutation under one identity-checked root: candidate-artifact lifecycle with compiler inode-transfer adoption, ordered publication (thread + lock-file process fencing) keyed by a durable audit publication ordinal (SQL sequence/column/backfill migration + ledger confirm/reactivate/floor, with an in-memory pool-block state machine for the compatibility ledger), legacy-evidence upgrade, and the #88 gap-recovery flow with the ledger range backfill threaded in as a per-call callback. The coordinator and PsqlShareLedger keep one-line delegating shims; verify_bundle honors the configured bundle build timeout. Bodies for pre-existing behavior come from the current tree, so all upstream fixes through #120 are preserved; the Postgres ledger shell gate gains publication-ordinal assertions plus three A1 gates (transition parity, migration, cross-process fencing), and the canonicalizer round-trip contract is pinned by new crate regression tests. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM block candidate submission Re-cut of the original B1 extraction against the rebuilt PR 75 layer. lab/prism/block_candidates.py owns the durable candidate codec and the full submit-before-accounting lane from the current tree: node-submission workers with hard RPC deadlines, same-hash disposition leases and terminal outcomes, the accounting queue/thread handoff, startup and outbox replay with quarantine, acceptance evidence and chain probes, retry merge/pacing/backoff, block-work heartbeats and the DB/RPC call workers including the landing-class deadline split with per-block escalation and the startup enumeration-owed gate. The coordinator keeps the node submission finalization side, thin delegates, and descriptor-routed compatibility state; replay adoption registers credit floors through the share-writer owner before preview registration so one bad row cannot abort the rest. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM share submission Re-cut of the original share-submission extraction against the rebuilt PR 76 layer. lab/prism/share_submission.py decomposes the submit hot path into pure parse/validate/classify functions plus ShareSubmissionService, with bodies from the current tree: the cross-connection retained-submit authority (same-tip-only guard, retained version mask, original extranonce), stale-grace block-solve drop accounting ahead of low-difficulty classification, and the durable-outbox fast paths in both block routes wired to the block-candidate owner's facades. The recent- share duplicate window becomes RecentShareIndex with oldest-insertion eviction, and the service owns share-ack histogram state behind the existing coordinator routing seam. The coordinator keeps a one-line decorated handle_submit, the rejection-constant re-exports, and descriptor-routed compatibility state. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM vardiff service and block finalization Re-cut of the original vardiff/finalization extraction against the rebuilt PR 77 layer. lab/prism/block_finalization.py owns the post-offer B3 lane from the current tree — admission with acceptance-evidence short-circuits, landing under the append-epoch fences and window-proof decision, the CTV/share-credit tail, ordered audit publication through the PR 75 store, and accepted-block accounting — packaged in the six bounded finalization phases with candidate-interarrival metrics. The block-candidate owner's ports are untouched: its targets remain the coordinator facades, which now delegate to the service, and landing round-trips through the coordinator seam so existing monkeypatches intercept. lab/prism/vardiff_service.py owns vardiff configuration, share windows, the idle retarget engine and its executor state behind twelve adopted compatibility fields, keeping the difficulty-direction clean-jobs rule. The B3 decision document is refreshed for the node-first accounting-actor architecture. Co-Authored-By: Claude Fable 5 <[email protected]> * Extract PRISM observability and audit HTTP Re-cut of the original observability extraction against the rebuilt PR 78 layer. lab/prism/observability.py owns mining-delivery and semantic- currency policy, the cached base-health snapshot with live progress overlay, the starting-state 503 and warm-up loop, and a new cached complete-metrics snapshot pipeline with bounded collector diagnostics. lab/prism/audit_http.py owns the audit listener lifecycle and route handler behind a typed port, with genuinely bounded shutdown: a stop racing startup before the serve loop commits now cancels the startup window and returns within its deadline, pinned by new socket-lifecycle regressions. The coordinator keeps delegating shims, the health-attribute compatibility properties, the renamed complete-metrics renderer, and the listener-binds-before-warm-up startup ordering with its phase stamps; the compose environment gains the metrics refresh interval alongside every existing pass-through. Co-Authored-By: Claude Fable 5 <[email protected]> * Complete PRISM coordinator ownership cleanup Re-cut of the original terminal cleanup layer against the rebuilt PR 79 stack. lab/prism/metrics.py owns the complete Prometheus payload and the extracted formatter bodies behind copied owner snapshots, proven byte-identical to the previous renderer by a frozen-reference parity test. lab/prism/reorg_reconciler.py owns reconcile flight admission, the per-tip trusted memo, lookup counters and the bounded proving prefetch executor around the current core state machine, while the coordinator keeps the exact serialized writer/payout/landed-preview adapter and compatibility descriptors. The watchdog moves into a WatchdogService with the coordination-blocked streak, classification, bounded lease release and unconditional hard exit behind the dynamic coordinator seam that the lease heartbeat service also fires. BlockFinalizationService drops its implicit attribute forwarding for an explicit typed port with mechanical coverage, the interim health compatibility properties and forty-plus compatibility re-exports are deleted with every caller repointed, and white-box tests now target the owning services. Co-Authored-By: Claude Fable 5 <[email protected]> * Document PRISM refactor review stack Re-derived documentation layer: the review-stack guide, ownership map, invariants, roadmap, A1 contract and validation evidence, updated for the rebuilt stack against current 1.x.x — the node-first finalization split, the re-measured structural audit, and validation results actually produced on this tree (Docker-backed Postgres/A1 gates, Rust workspace, container compile and image build, compose validation; live Stratum targets recorded unavailable for the missing qbitd prerequisite). The ledger operations guide keeps its current landing/replay text and gains the known-outcome replay-resumption contract; the audit publication ordinal comment in the finalization owner is refreshed for reactivation reuse. Co-Authored-By: Claude Fable 5 <[email protected]> * Add a deterministic concurrency harness for PRISM, proven against the writer-lease lifecycle (#139) * Add a deterministic concurrency harness and prove it against #123 The concurrency defects this line keeps shipping share a shape: two owners interleave around a PostgreSQL row, and the bad schedule is too rare to reproduce by running the coordinator and hoping. Every one was found in production or in review, never by a test. The nine-slice refactor removed the structural reason for that, so this adds the missing tool: a scheduler that makes an interleaving an input rather than an accident. The harness has three parts. A baton scheduler runs real threads one at a time, stopping only at named checkpoints placed at PostgreSQL statement boundaries, so the controlling test decides who runs next and the resulting schedule is order-stable rather than merely likely. A virtual clock backs every interval the lease lifecycle measures about itself, so nothing sleeps in wall-clock time. An in-memory PostgreSQL model covers the semantics the lease lifecycle actually depends on: tuple locks held for a transaction's lifetime, FOR NO KEY UPDATE SKIP LOCKED declining to queue, per-statement READ COMMITTED snapshots, lock and statement timeouts, session-scoped advisory locks, and pg_stat_activity locker attribution against a snapshot-visible xmax. Substitution runs through ports rather than monkeypatching. LedgerSqlPort and LeaseGuardPort name the two seams PsqlShareLedger already wrote through, and the constructor now takes sql_backend_factory, lease_guard_factory and monotonic alongside the existing lease_retry_sleep. No bound method is reassigned and no clock is patched, so the code under test stays the shipped code: the real retry loop, the real CAS SQL, the real adoption arithmetic, the real fail-closed branches. FakePostgres answers statements by recognising them against fragments lifted from the production SQL, and raises on anything else. Statements belonging to the state machines deferred to follow-up PRs are recognised only well enough to name the follow-up. A fake that silently answers an unrecognised statement drifts from production without anyone noticing; this one fails instead. Issue #123 is the proving ground. Its trigger sequence now runs without a live Postgres: a coordinator vanishes in the gap between a deadline-scoped statement completing and its COMMIT, leaving an open transaction holding the lease tuple lock, and a failover twin parks on that lock inside PsqlShareLedger.__init__ with no deadline anywhere in the system that can release it. The schedule is identical across repeated runs. One test in this commit fails, deliberately. OrphanedLeaseLockFailoverBoundTests asserts the bound #123's fix must establish, and #123 is not fixed on this line: the startup lease upsert runs with no lock_timeout, so nothing bounds the successor's wait. That assertion is written against the fixed behaviour rather than against today's, because weakening it to green would delete the only executable statement of what #123 asks for. It turns green when the fix lands. Refs #128, #123 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Cover the remaining writer-lease interleavings, and two model fidelity fixes Completes the writer-lease lifecycle as the harness's proving ground. Three scenario modules, each driving shipped code through the harness rather than re-describing it: Renewal against a competing expiry claim. The heartbeat renews uncontended; an expired row whose skipped lock belongs to a different-identity claimant fails closed, and the control proves it is the combination that raises rather than either half; the documented attribution misfire — this coordinator's own fenced write committing between the verification statement's MVCC snapshot and its live pg_stat_activity probe — is driven at exactly that checkpoint and resolved by exactly one recheck; a claim that commits fences the session. Heartbeat during a long fenced statement. The verification crosses an in-flight fenced write without ever queueing, skipping renewal and resuming it the moment that write commits. The control runs the pre-fix locking spelling into the same lock and watches it die on the guard's statement timeout, which is what makes renewed_count == 0 mean "declined a lock that was really there" rather than "nothing was attempted". An own fenced write outlasting the TTL defers instead of self-fencing, and the same expired row locked by a foreign application_name still fails closed. Takeover and epoch fencing. The advisory guard keeps a same-identity successor out of the lease upsert entirely; adoption silence is measured from the successor's own guard acquisition even when the row is already far staler than the interval; the CAS rewrites the session token and fences the predecessor; a lost CAS re-observes after a fresh full interval instead of refusing the token permanently; and a different epoch refuses an unexpired lease while taking an expired one through the ordinary expiry CAS. Two fidelity fixes to the model, both found while reviewing the above. A cancelled lock wait now reports which bound fired. A caller deadline arrives as SET LOCAL lock_timeout, while the guard session's bound is a connection-level statement_timeout; PostgreSQL reports them with different messages, and the whole point of the SKIP LOCKED heartbeat is that the guard's bound is the fatal one, so blurring them would let a scenario assert the wrong mechanism. Vanishing a coordinator no longer fabricates an orphan on a path that cannot produce one. An explicit transaction's COMMIT is a separate client message, so a vanished client leaves it open forever; an autocommit statement has no such message and PostgreSQL finishes and commits it. #123 is explicit that the orphan shape did not exist before the deadline plumbing arrived, and a model that offered it on the autocommit path would argue for a fix to a defect that path cannot reach. Determinism: eight assert_deterministic tests at 25 repeats each, every one asserting an exact checkpoint schedule rather than merely that runs agree. Twenty consecutive full runs of the five modules produce an identical result. Refs #128 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Correct the PostgreSQL snapshot model and the #123 bound An adversarial review pass verified the model's PostgreSQL claims against a scratch PostgreSQL 16.15 cluster and found two defects that mattered. The model re-read committed state after a tuple-lock wait. PostgreSQL takes one snapshot per command in READ COMMITTED: a statement that blocks re-reads only the conflicting tuple, through EvalPlanQual, to evaluate its write predicate, while every other scan in the statement keeps the original snapshot. So a queued acquire reports the pre-wait row and a lease_age_seconds that has silently absorbed the entire wait, where the model reported a fresh row and a small age. That age is the row edge of _writer_lease_adoption_wait_seconds, so the model was hiding the very input that makes the adoption CAS's updated_at predicate load-bearing: in the model the observation was always fresh, and the CAS would have matched even with that predicate deleted. Evaluation now takes the snapshot before any lock wait, resolves write predicates against the freshly locked version, and reports results from the snapshot. Statements that evaluate to SQL NULL return None and go through production's own parse_single_json_value, rather than being smoothed over. That surfaced a real production behaviour the model had been concealing. When two coordinators race the first ever acquire, the loser's DO UPDATE matches nothing and its COALESCE fallback reads a snapshot in which no row exists yet, so the whole statement returns NULL and PsqlShareLedger.__init__ dies with "postgres query returned no JSON" — an error naming neither the lease nor the coordinator holding it. The harness's own contention self-test was constructing exactly that interleaving and turning it into a clean refusal. It now asserts the real error, and a dedicated test pins the contrast against the ordinary "lease is held by" refusal. The deliberately failing #123 test asserted a bound the fix it names would not have satisfied. It advanced the clock once and drained once, so a fix built from lock_timeout plus a bounded retry — which is what #123 proposes — would have left the successor parked on the first of several short deadlines with the test still red, and the person landing that fix looking at a red test and reaching for the weakening this test exists to refuse. It now drives the successor through every deadline it reaches. Both candidate fixes were simulated: lock_timeout alone and lock_timeout with a bounded retry each turn it green, and it stays red on this line. Four smaller model corrections. A non-matching UPDATE no longer queues on the tuple lock, because PostgreSQL evaluates the predicate against the snapshot version and never locks a row it excludes; latent today, but it would have misrepresented any fencing argument, where "the predecessor is blocked" and "the predecessor already knows it lost" are different states. Tuple-lock waiters are granted in arrival order rather than whichever the controller steps first. Pool exhaustion honours the caller's deadline instead of waiting forever. The guard session's serialization is now pinned against _NativePostgresLeaseGuard._query_lock itself, since deleting that lock left every assertion in the harness-level test green. The two new protocols had no executable contract: the repository runs no mypy, they were not runtime-checkable, and the signature test compared parameter names only. They are now @runtime_checkable, asserted against both the production classes and the fakes, and checked with full signatures across every method. LedgerSqlPort.pool_size is dropped, being surface nothing reads. Two production tidies from the same pass. The lease clock is a declared class attribute overridden per instance, rather than a getattr fallback that would silently revert to wall-clock time under a rename. _pool_application_name is injectable, removing the last uncontrolled nondeterminism inside the code under test — lease_locked_by_this_process turns on that value, so a scenario that surfaced it would have failed the determinism check for reasons nothing in the harness explained. Full suite: 2023 tests, failures limited to the five pre-existing macOS os.splice tests and the one intentional #123 assertion. Twenty consecutive runs of the five harness modules are identical. Refs #128, #123 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Clean up the harness under a standard Python linter The repository configures no Python linter — CI runs shellcheck, bash -n and compileall — so this is a quality pass on the files this branch adds rather than a fix for a failing check. Run with ruff in Docker. Real findings, fixed: a stale noqa suppressing BLE001 on an `except BaseException` the rule does not apply to; Callable imported from typing rather than collections.abc; an unsorted __all__; re.S in place of re.DOTALL; a three-line if/return that is just its own condition; __enter__ annotated with the concrete class rather than Self, imported under TYPE_CHECKING so no runtime version floor is introduced. The guard serialization test caught a blind `except Exception: pass`, which was hiding what the test actually proves. It now catches the AttributeError the statement itself raises once past the query slot, and asserts it fired: reaching the statement is the evidence, and any other outcome means run_json did not get where the test claims. Two findings are deliberately left. Every test module in this repository carries a shebang without the executable bit, so EXE001 is the house convention and departing from it in six files would be the anomaly. The `noqa: E402` on the deferred share_ledger import is reported unused only because E402 is not enabled in this ad-hoc invocation; the import genuinely does follow a sys.path statement, so the suppression is correct and documents why. Also corrects a comment the review pass flagged as overstated: the baton timeout cannot change what a run does, but it is not free of consequence, and claiming it "cannot make a passing run flaky" overstated a real if remote failure mode. Refs #128 * Mark the #123 bound as an expected failure The assertion is unchanged. What changes is who gets told about it, and when. Left as a plain failure, it made every CI run on this branch red, which is a poor way to communicate one known-open issue: a permanently red check is indistinguishable from a broken one at a glance, and it teaches people to stop reading CI. Three separate readers took the red "Lint, compile, and test" badge for a lint failure, which is the failure mode in miniature. unittest reports an unexpected success as a suite failure, so the marker is self-removing: the day someone fixes #123 the suite goes red and hands them this file, which is exactly when learning about it is useful. Verified rather than assumed — a marked test that starts passing does set wasSuccessful False. The marker is only defensible because the assertion genuinely goes green under a real fix, which it did not before the drive-to-quiescence correction. Both candidate fixes named in #123 were simulated again against this commit: lock_timeout alone, and lock_timeout with a bounded retry, each turns it green and each leaves 2.x.x red. An expectedFailure on a test that would stay red after the fix would be strictly worse than a plain failure, and that is the state this branch was in two commits ago. Full suite: 2023 tests, one expected failure, and the five pre-existing macOS os.splice failures that pass on Linux. Ten consecutive runs of the five harness modules report OK with one expected failure every time. Refs #128, #123 --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> * Preserve the audit envelope when two found blocks land in one confirm-publish window (#136) * Preserve the audit envelope on interleaved found-block landings Two distinct found blocks can land inside one confirm->publish window. The synchronous miner-connection-thread tail confirms block A under the payout-balance lock and the publication order guard, then releases both before it publishes; the accounting-actor tail lands block B in that gap, allocates the next ordinal and publishes first. The per-hash disposition lease does not serialise two distinct hashes, so nothing prevents the interleaving. Block A then reached publish_success already superseded and returned without writing anything: its live audit envelope -- the block's only published evidence pointer -- was lost permanently and silently. The Postgres audit row, canonical bundle, body, accounting, share credit and settlement all survived; only the public evidence trail was dropped. The old code conflated two invariants behind one floor check. The evidence path is a single mutable pointer that must advance monotonically in sequence, and floor gating is correct for it. The live envelope is a per-block immutable artifact on its own height+hash path, and a superseded ordinal's envelope competes with nothing. Being behind the floor means you may not become current; it does not mean your own envelope is not yours to write. Sequence-versus-floor alone cannot authorise that write, though. A process whose writer lease has been taken over is also behind the floor, and it must stay fenced out of the shared audit root entirely: its in-memory report may be stale, and publishing a stale report as a block's public evidence is worse than leaving the envelope missing. Only the caller knows which it is. The write is therefore opt-in through a new restore_superseded_envelope keyword that defaults to false, and only _publish_finalization_evidence -- the live writer finalizing a block it confirmed itself in this landing -- passes true. A deposed writer replaying stale state never reaches that call site, so the A1 process gate's C3 fencing invariants are preserved exactly. When the write is authorised it routes through _write_superseded_live_envelope_locked, which writes the envelope only when it is absent and logs the event. The publication order guard and the process flock are held throughout, and the write is rolled back if any post-write identity assertion fails. A present envelope is returned untouched, so a same-hash stale replay keeps its existing behaviour exactly. The current evidence reference, the cached identity and retention pruning are not touched, and the publication still reports published=False. The diagnostic goes to stderr: this store is hosted inside worker processes that reserve stdout for a strict JSON protocol stream, and the A1 process gate drives this exact superseded path. Add two regression tests, both failing before the fix at the envelope-existence assertion: the distinct-hash interleaving across the synchronous and actor tails, and the convergence path where the peer is confirmed but not yet published so the earlier block is retried behind the floor. Because the write is opt-in, no existing assertion changes -- the test diff is purely additive. Fixes #133 Co-Authored-By: Claude Opus 5 <[email protected]> * Lease-gate the superseded-envelope restore and pin its wiring An adversarial review of the interleaved-landing fix for issue #133 returned four findings; this lands all four. The restore's opt-in rested on "a deposed writer never reaches the call site", which is false for a writer deposed inside its own confirm->publish gap: it confirms with a valid lease, loses it during the gap, and everything from there to the publish call is lease-unfenced. Content divergence was independently impossible -- the report and persistence digests bind to the durably confirmed ordinal -- so this was a coherence defect against the A1 process gate's C3 immobility invariant rather than a corruption path, but that invariant is cheap to keep literally true. _publish_finalization_evidence now asks the coordinator's bounded, non-blocking exact-session fence (require_fresh_lease_for_external_side_effect) for restore authority before entering the publication order guard, holding no store lock across the verification. The asymmetry is deliberate: a clean proof grants restore_superseded_envelope=True, while a lease failure (WriterLeaseRenewalDeferred, ShutdownInProgress) withholds the restore, logs the withholding with the component and exception type, and lets the publication proceed unchanged. The restore is a repair of an evidence pointer, not the publication itself; degrading to False is exactly the previously shipped behaviour, whereas failing the found-block path on a lease hiccup would be a live regression. The fence stays a no-op for ledgers without the writer lease guard, never waits on the lease row, and its internal hard-exit arming for a genuinely dead lease is left intact. The production opt-in was also untested: flipping the call site back to False passed all 254 tests. A new coordinator-level regression test drives the real two-tail topology -- handle_submit's synchronous landing paused inside its confirm->publish gap while a second distinct-hash candidate rides the submitter->accounting-actor handoff, lands, and publishes -- and asserts both blocks' live envelopes exist afterwards. It fails at the envelope-existence assertion with the call site reverted to False. A sibling test pins the degrade path: a fence that raises withholds the restore without failing either landing. The present-file early return in _write_superseded_live_envelope_locked accepted any bytes and fsynced nothing, so a truncated or corrupt envelope was silently accepted and could never be repaired. It now compares the existing envelope against the one this identity would build, ignoring created_at exactly as the main publish path does -- the comparison is extracted into a helper shared with that path -- raises the same invalid/conflicts errors, and fsyncs the parent directory on a match before returning. The superseded-write diagnostic used to print while holding both the store lock and the publication-order flock; an undrained stderr would have blocked the found-block path with locks held. The store now records the write on the returned publication (AuditPublication.superseded_envelope_written, defaulted so every existing construction site is unchanged) and _publish_finalization_evidence emits the message -- still on stderr, because worker stdout is a strict JSON-lines protocol -- after the balance lock and the order guard have been released. Verified: the three unittest suites (256 tests), the Postgres ledger gate and the four A1 gates including C3-B-wins-late-A, and ruff E4/E7/E9/F on the changed files. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]> * Persist per-session vardiff difficulty across miner reconnects (#138) * feat(prism): persist per-session vardiff difficulty across reconnects A coordinator restart or miner reconnect previously reset every session to its lane's start difficulty; at 4x per 300s retarget a large miner needed 15-25 minutes to re-climb while flooding the share path, feeding the 2026-07-16 loop: coordinator slows -> watchdog exits -> every miner reconnects -> every session resets to lane start -> share rate spikes -> coordinator slows further. Remove the amplifier by retaining each worker's last converged difficulty in a bounded, TTL'd in-process store keyed by (listener name, exact Stratum username). The value is recorded at every committed retarget and on disconnect, and adopted on the first mining.authorize of a new connection, before password parsing, so an explicit d= still outranks it and an md=-only password clamps the resumed value. Adoption is capped at min(lane max difficulty, lane start * resume factor): a stale or absurd retained entry is clamped instead of adopted, while a value below the lane start resumes as-is (vardiff targets a share rate, so a converged session is on target by definition). New tunables, documented in .env.example: - PRISM_STRATUM_VARDIFF_RESUME (default 1): master switch; 0 restores lane-start reconnect behavior exactly. - PRISM_STRATUM_VARDIFF_RESUME_TTL_SECONDS (default 900): how long a converged difficulty stays adoptable; keep short where the idle step-down sweep is disabled. - PRISM_STRATUM_VARDIFF_RESUME_MAX_ENTRIES (default 8192): LRU bound on retained state (2x the deployed connection cap). - PRISM_STRATUM_VARDIFF_RESUME_MAX_START_FACTOR (default 1024, must be >= 1): plausibility ceiling as a multiple of the lane start. Also adds convergence observability -- sessions sitting at their vardiff ceiling, per-lane accepted share counts and rates, resume outcomes by bounded label, and a retained-sessions gauge -- mirrored into the frozen metrics reference implementation. * fix(prism): age retained vardiff difficulty from real convergence SessionDifficultyStore.record re-stamped recorded_monotonic on every write, and the disconnect seam records on every disconnect with no share evidence. A session that resumed a retained difficulty, submitted nothing and disconnected therefore refreshed that value's clock, so reconnect cycles shorter than the TTL kept it adoptable indefinitely (reproduced: ttl=900 survives past 4000s on 800s cycles). That defeats the short TTL exactly where it matters: with the idle step-down sweep disabled as deployed, a session resumed above its true hashrate produces no accepted shares and cannot step itself down. record now takes an explicit share_backed flag and refreshes the timestamp only on a first record, on a value that actually moved, or on an unchanged value backed by accepted shares; otherwise the entry keeps ageing from its original convergence. The stored difficulty is always updated and LRU recency still moves on every record, so recency and TTL stay independent. ClientState gains vardiff_accepted_any, set on the first accepted share of a connection and never reset within it; the retarget commit point passes its own window's evidence (accepted_shares > 0), and the disconnect seam passes the connection's accumulated flag. An idle step-down carries no shares but lowers the value, so it refreshes on the changed-value branch as before. Also from the same review: - Disconnect retains client.share_difficulty only. The pending value is advertised with a future job, so a disconnect racing an in-flight retarget was retaining a difficulty the miner never received; a retarget whose paired send completed still records itself. - qbit_prism_vardiff_resume_total gains outcome="overridden", counted when an adopted resume is superseded by an explicit difficulty request in the same authorize, so resumed + clamped - overridden is the number that stuck. Routed through a coordinator seam like the adjacent ones. - Document shared-username retention as last-writer-wins next to PRISM_STRATUM_VARDIFF_RESUME, sharpen the per-lane rate gauge HELP to say it is a since-start average and point at rate() over the counter, and record the at-ceiling census cost at convergence_snapshot. Tests cover the reconnect-cycle repro and its share-backed counterpart, the undelivered-pending disconnect, the retarget commit-point recording, the env -> config -> coordinator -> store sizing chain, and an authorize whose username reservation fails. The frozen metrics reference mirrors both rendered-byte changes. * Cap the escalated landing budget below the watchdog tolerance (#135) * Cap the escalated landing budget below the watchdog tolerance A landing-class ledger step cost two independent budgets of heartbeat silence, and the escalated budget could exceed what the watchdog would wait for. Both halves are fixed here (issue #125). Half A -- the ledger admission wait is no longer heartbeat-silent. PsqlShareLedger._operation_gate waited for the writer lock or read semaphore in a single blocking acquire sized by _remaining_operation_timeout, which under statement_timeout is the full constant budget. That wait is local admission, not database work: no statement has been sent, so no server-side deadline bounds it and the ledger reports nothing until the gate opens. A new operation_progress thread-local scope -- shaped exactly like its operation_timeout and statement_timeout siblings -- installs a callback plus a slice; when one is installed the acquire is served in slices and the callback fires between them. Without a hook the path is unchanged: one blocking acquire and the same LedgerOperationTimeout message, so non-block-work callers pay nothing. The caller's deadline stays authoritative, the loop always attempts the acquire at least once so an expired budget still fails where it always did, the callback never runs while this thread holds the gate, and an exception from it propagates rather than being swallowed inside a lock wait. Both statement-timeout scopes in BlockCandidateService run on the watchdog-monitored block-work owner thread, so they now install that hook (duck-typed, like the statement_timeout/operation_timeout probes beside them) with _record_block_submitter_wait as the callback and the already-watchdog-clamped _block_work_wait_slice as the slice. Ledgers predating the hook keep working unchanged. Half B -- the landing cap is derived from the configured watchdog. DEFAULT_BLOCK_LANDING_DB_TIMEOUT_MAX_SECONDS (120s) and the watchdog default (120s) were independent literals, so an escalated landing budget could legally outrun the tolerance. _block_landing_db_timeout now clamps both the base and the escalation cap to watchdog_timeout_seconds * BLOCK_LANDING_DB_TIMEOUT_WATCHDOG_FRACTION (0.5), read from the configured coordinator rather than a second hardcoded number, and DEFAULT_PRISM_WATCHDOG_TIMEOUT_SECONDS replaces the literal in the env default so the two cannot drift apart. Arithmetic. Before: admission wait (up to 120s) plus a fresh server-side statement (120s) gave 240s of silence against a 120s watchdog; the watchdog hard-exited mid-landing, the in-memory escalation counts died with the process, and the restart replayed the same doomed attempt from the base budget. After: the silent span of one landing step is a single statement, and at the 120s default the ceiling is 60s with escalation running 30s -> 60s -> 60s. At the 300s production tolerance the ceiling is 150s, so the reviewed 120s cap is granted in full and deployments using that override see no behavior change. Tests. New coverage pins the escalated budget inside half the configured watchdog (and pins the 300s override leaving the 120s cap intact), the sliced admission wait stamping progress while blocked and still raising at the caller's deadline, the unhooked gate path staying a single acquire, hook validation/nesting/propagation, and both scopes installing the hook while a ledger without operation_progress still works. Two existing tests that assert budgets above half the default watchdog now set watchdog_timeout_seconds explicitly rather than weakening their assertions. Refs #125 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * Make the landing scope's one-statement heartbeat invariant true The escalated landing budget is clamped to half the watchdog tolerance on the grounds that the heartbeat-silent span of one landing step is a single server-side statement. That fraction is only sound if the claim holds, and in three places it did not. Ledger operations that hold a gate across two statements. Three _operation_gate bodies issue a second statement without releasing the lock: confirm_accepted_block and reactivate_pool_block read the publication ordinal their mutating statement's command snapshot could not see, and carry_forward_integrity_report reads its audit head under the same lock so the two reads observe one another. No admission slice runs between the statements, so a landing caller's monitor was asked to sit through two statement budgets of silence -- at the 120s default that is the whole tolerance with no margin at all. PsqlShareLedger._note_operation_progress reports the completed first round trip, following the same reasoning as verify_writer_lease_guard_session's on_statement_progress callback. That callback stays as it is: its callers pass it explicitly per call rather than through the thread-local scope, and its statements never run under _operation_gate. Unstamped stretches between the current-tip RPC and the audit build. The reorg reconciliation, the prior-balance checks and the tip-height RPC each run inline on the block-work thread and stamped nothing. All three now bracket with the file's phase-pair idiom. Bracketing the reorg walk alone would not have been enough: one pass spends a getblockhash plus up to two ledger statements per watched pool block, so its silent span grows with the reorg window. The reconcile state machine takes a record_progress port -- wired to the coordinator's block-work phase recorder, defaulted to a sink -- and stamps per row. The unfenced-append drain. Its condition wait was untimed and unstamped. It stays unbounded, because bounding it could let a landing arm its epoch fences ahead of an append that must drain first; instead it waits in watchdog-sized slices from the existing _block_work_wait_slice helper and stamps each slice that still finds the predicate true. The while loop's re-check makes the timed wait semantically transparent, and the common path never enters the loop. Every stamper here no-ops off the registered block-work owner thread, so client-thread dispositions and background reconciliation are unchanged. The fraction's comment now states what is actually bracketed and calls the result a margin rather than a global invariant: a network stall mid-statement has no client-side socket-read deadline on the native psycopg path and can outlast any budget, which is a genuinely wedged process where a watchdog exit is the right outcome. Co-Authored-By: Claude Opus 5 <[email protected]> * Fix the progress-hook race and the landing clamp's blind spots Four follow-ups from the review of the landing-budget clamp. The progress thread-local was built lazily. operation_progress did a getattr-then-assign that is not atomic, so two block-work threads entering their first-ever scope on a fresh ledger could each build a local() and have one assignment win. The loser's hook then lived on an object the ledger no longer referenced and its admission wait silently reverted to the heartbeat-silent path -- exactly the failure the hook exists to remove. PsqlShareLedger.__init__ now creates it alongside its two siblings; the scope keeps its lazy fallback for ledgers built through __new__ in focused tests. The clamp was silent. When the watchdog-derived ceiling lands below the configured base or cap the operator gets less than they asked for -- at the 120s default tolerance a 120s cap becomes 60s -- and "escalation exhausted at my cap" becomes indistinguishable from "escalation never reached my cap". _block_landing_db_timeout runs on every landing attempt, so the notice names the configured values, the granted values, the ceiling and the watchdog it came from, and prints exactly once; the flag flips under the coordinator lock so concurrent first landings cannot both print, and the line itself is emitted outside that lock. The clamp ignored watchdog_enabled. A deployment running with the watchdog off has no hard-exit hazard to stay under, so halving its cap bought nothing. The ceiling is now infinite in that case, which also keeps the clamp notice silent (an infinite ceiling never compares below a finite configured value) and cannot poison the escalation arithmetic, whose inputs stay finite. The attribute is read defensively and defaults to enabled, since clamping is the safe answer; a test pins the name on LifecycleConfig so the defensive read cannot outlive the setting. Nesting semantics did not match the siblings. operation_timeout and statement_timeout merge by minimum, so nesting only ever tightens; operation_progress replaced outright, letting an inner scope with a larger slice widen heartbeat gaps its enclosing caller had already sized against its own monitor. Slices now merge by minimum. The callback still replaces: the innermost caller is the one whose liveness the wait belongs to. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Alex <[email protected]> * Bound PRISM writer-lease acquisition and guard coordinator Postgres sessions (#137) * Bound writer-lease acquisition and guard Postgres sessions A coordinator client that vanishes without an RST (partition, SIGSTOP, VM pause) leaves its backend idle-in-transaction, still holding the qbit_ledger_writer_lease row lock taken by the landing CTE. The successor's startup lease upsert ran with no statement or lock timeout, so it blocked inside PsqlShareLedger.__init__ - before the watchdog arms - until TCP keepalive teardown, a multi-hour full-pool outage (issue #123). Settlement correctness was never at risk; the outbox row stays pending and replays. Two independent halves: - Every coordinator Postgres session (pooled native client, dedicated lease-guard session, psql subprocess backend) now carries session guards: idle_in_transaction_session_timeout reaps the orphaned transaction, and the server-side tcp_keepalives_* GUCs bound dead-socket detection to 30 + 3x10 = 60s. DSN/PGOPTIONS values the operator set are merged, with th
Summary
Adds a deterministic concurrency test harness for PRISM, and proves it against
the writer-lease lifecycle. Closes the tooling half of #128.
Between
v1.0.0andv1.1.0this line took 71 commits and the large majoritywere concurrency defects. Every one was found in production or in review,
never by a test, because reproducing an interleaving meant standing up the
whole coordinator and hoping the schedule came out wrong. The nine-slice
refactor changed that precondition; this PR supplies the tool that
precondition was for.
The scope here is deliberately narrow: the harness core plus one state
machine. Block candidate landing, tip refresh and job delivery, and share
submission and dedupe are named in #128 and are explicitly deferred to
follow-up PRs — see Deferred below.
The harness
tests/prism_concurrency_harness.py. Three pieces, each chosen against aspecific way the previous approach failed.
A baton scheduler over real threads. Exactly one actor runs at a time, and
it stops only at named checkpoints placed at PostgreSQL statement boundaries.
The controlling test decides who runs next. The alternative — starting threads
and nudging them with sleeps — is what the existing lease tests approximate
with canned response queues, and it can express a sequence of responses but
not an interleaving: there is no way to say "the successor's upsert reaches
the server while the predecessor's transaction is open but uncommitted."
Making the schedule an input rather than an accident is the whole point, and
it is what makes a run reproducible and order-stable rather than merely
likely.
A virtual clock. Every interval the lease lifecycle measures about itself
— adoption silence from advisory-guard acquisition, caller deadlines, TTL
expiry, retry sleeps — reads it. Nothing sleeps in wall-clock time, so a
scenario that spans six hours of lease timeout runs in microseconds and a
scenario that turns on a 250 ms retry does not depend on the test host's load.
An in-memory PostgreSQL model. Not a SQL interpreter — a model of the
semantics this lifecycle actually depends on: exclusive tuple locks held for a
transaction's lifetime,
FOR NO KEY UPDATE SKIP LOCKEDdeclining to queue,per-statement READ COMMITTED snapshots,
lock_timeoutandstatement_timeout,session-scoped advisory locks, and
pg_stat_activitylocker attributionagainst a snapshot-visible
xmax. Explicit transactions are modelled asBEGIN / statement / COMMIT with a checkpoint in the gap, because that gap is
the whole of #123.
Why substitution goes through ports
PsqlShareLedgerwrote through two seams that had no names:_NativePostgresClientand_NativePostgresLeaseGuard. This PR names them —LedgerSqlPortandLeaseGuardPort— and adds constructor injection(
sql_backend_factory,lease_guard_factory,monotonic) alongside thelease_retry_sleephook that already existed.No bound method is reassigned and no clock is patched. That matters here
beyond taste: the tree carries 922
type: ignore[method-assign]sites, and aharness that added more would be feeding the pattern it exists to replace.
The consequence is that the code under test is the shipped code — the real
retry loop, the real CAS SQL, the real adoption arithmetic, the real
fail-closed branches — rather than a re-description of it.
Why the fake refuses to guess
FakePostgresanswers a statement by recognising it against fragments liftedverbatim from the production SQL, and raises
UnsupportedStatementonanything else. Statements belonging to the deferred state machines are
recognised only well enough to name the follow-up in the error.
A fake that silently answers an unrecognised statement drifts away from
production without anyone noticing, and every scenario built on it inherits
the drift.
tests/test_prism_concurrency_harness.pypins this from the otherdirection: it drives each lease operation through real
PsqlShareLedgercallsand asserts the classifier still recognises what that module generates today,
so a change to the production SQL breaks classification loudly instead of
quietly changing meaning.
Scenarios covered
The writer-lease lifecycle, as #128's suggested first step:
test_prism_lease_orphaned_lock.pytest_prism_lease_renewal_vs_expiry_claim.pytest_prism_lease_heartbeat_under_fenced_write.pytest_prism_lease_takeover.pytest_prism_concurrency_harness.pySeveral of these express things no existing test could. The clearest is the
lost-CAS scenario, where the predecessor's renewal queues on the tuple lock
while the successor's adoption CAS is in flight, then lands first and makes
the CAS miss — a three-way ordering between two processes and one row lock.
Evidence of determinism
A flaky concurrency test is worse than none, so order-stability is proved
rather than assumed.
assert_deterministicbuilds a fresh harness per run andrequires an identical checkpoint trace and an identical outcome across 25
runs; every scenario module has at least one such test, and each asserts the
exact expected schedule as a literal list rather than merely asserting that
runs agree with each other.
Two things fall out of the design that are worth stating explicitly. There is
no wall-clock ordering anywhere: the one real-time value in the harness is a
baton timeout, and it cannot change the order of any run — it can only turn a
hang into a diagnosable error, at the cost of being able to fire if an actor
somehow took twenty wall-clock seconds to reach its next checkpoint. And the
determinism check found two real modelling bugs while this PR was being
written — the model was letting a second transaction steal a held tuple lock,
and was letting two concurrent inserts both succeed instead of conflicting on
the singleton index. Both would have made later scenarios quietly wrong.
Concretely: ten
assert_deterministictests, 25 repeats each, comparingfull checkpoint traces. The literal expected-trace assertion that follows each
one is the stronger half — for a schedule fully specified by explicit
step/run_untilcalls, repetition mostly proves that real threads and areal clock did not intrude, while the trace literal is what pins the
schedule. Twenty consecutive runs
of the five modules produce an identical result every time (53 tests, the same
single expected failure). The modules also pass individually and in reverse
order, so no scenario depends on state another one left behind.
What #123 currently shows
#123's fix has not landed on
2.x.x.idle_in_transaction_session_timeoutis set nowhere in the tree, server-side TCP keepalives are configured nowhere,
and the startup lease upsert still runs with no
lock_timeout(
_try_acquire_writer_lease→_run_jsonwith no armed caller deadline).The harness drives the issue's trigger sequence without a live Postgres. A
coordinator vanishes in the gap between a deadline-scoped statement completing
and its COMMIT; its transaction stays open holding the lease tuple lock; a
failover twin then parks inside
PsqlShareLedger.__init__on that lock. Theschedule is identical across 25 runs:
Three tests around that interleaving pass, and they are the evidence #128
asked for: the orphan really does hold the lock, the successor really does
park on it with
wake_atunset andscheduler.next_deadline()returningNone— nothing anywhere in the system bounds the wait — and six virtualhours later it is still not runnable. A control test releases the orphan and
shows the successor immediately reaching its decision, which is what makes the
parked state attributable to the lock rather than to a scenario that simply
never scheduled it.
One assertion in this PR does not hold on
2.x.x, deliberately.OrphanedLeaseLockFailoverBoundTests::test_successor_startup_must_not_wait_unboundedlyasserts the bound #123's fix must establish: a successor's startup finishes,
by acquiring or by raising, within a bounded time. It is written against the
fixed behaviour rather than against today's, because asserting today's
behaviour would delete the only executable statement of what #123 asks for —
and #128 is explicit that each of these issues "should instead be a failing
property test that the fix turns green."
It is marked
@unittest.expectedFailure, so CI is green. That is not aweakening: the assertion is untouched, and
unittestreports an unexpectedsuccess as a suite failure, so the day someone fixes #123 the suite goes red
and hands them this file. The marker removes itself; a permanently red check
would only have taught people to stop reading CI.
The marker is safe to apply here specifically because the assertion does go
green under a real fix. Both candidate fixes named in #123 were simulated —
lock_timeoutalone, andlock_timeoutwith a bounded retry — and eachturns it green, while
2.x.xleaves it red. AnexpectedFailureon a testthat would stay red after the fix would be strictly worse than a plain
failure.
The interleaving also sharpened one thing the issue did not say. A
different-epoch failover twin has no useful work to do behind that lock at
all: once it can read the row it refuses immediately, because
_can_wait_for_writer_leaserequires an exact identity match. Every second itspends queued is pure outage with no upside, which strengthens the case for
the issue's proposed
lock_timeoutand bounded retry over a longer wait.On adding
hypothesisNot proposed here. Recommend deferring the decision to the landing PR.
The argument for it is real: #128 asks for model-based and property-based
tests, and
hypothesis'sRuleBasedStateMachineplus shrinking is theobvious way to search a space rather than enumerate it. The argument against
it, for this PR, is that it would not have found any of these defects. The
lease bugs are not "some input violates an invariant" — they are "this
specific schedule of two owners around one row starves or deadlocks." What
needs generating is the schedule, and the harness already makes schedules
first-class: enumerating interleavings of runnable actors is a small amount of
code on top of
drain, and doing it in-house keeps shrinking meaningful,because the thing worth shrinking is a checkpoint sequence rather than a data
value.
The cost is not zero either. The repo has no
pyproject.toml, no third-partytest dependency, and CI runs a bare
python -m unittest discover; adding onemeans an install step in CI and in any image that runs the suite.
Where it would genuinely pay is block candidate landing, where the space is
combinatorial in a way the lease lifecycle is not — dispositions × retry
counts × append epochs × the two-tail topology. Concrete proposal: revisit
when that PR is written, and adopt
hypothesisif the hand-written schedulematrix there exceeds roughly thirty cases.
Deferred to follow-up PRs
Named in #128, not implemented here. In the priority order that issue sets:
terminalization. Needs the harness extended with the outbox and pool-block
rows, the publication-ordinal allocator and floor, and the two-tail landing
topology (
_submit_synchronous_block_candidateon a client thread versusthe accounting actor). PRISM: interleaved landings of two distinct found blocks silently drop the earlier block's audit envelope #133's two-distinct-hash interleaving is the
acceptance criterion, and PRISM: escalated landing budget can outrun the 120s watchdog and restart-loop found-block settlement #125 and PRISM: global append epoch can over-abandon a never-offered candidate on the fallback submit path #126 are the next two: PRISM: escalated landing budget can outrun the 120s watchdog and restart-loop found-block settlement #125 needs the
heartbeat clock and the
_operation_gateadmission wait modelled asinterleaving points, which the virtual clock already supports; PRISM: global append epoch can over-abandon a never-offered candidate on the fallback submit path #126 needs
the global append epoch as harness state.
convergence, single-flight promise resolution and eviction. Driven through
TipRefreshRuntimeandJobDeliveryRuntimerather than throughFakePostgres; the scheduler and clock carry over unchanged.classification, window boundaries. Needs
qbit_share_ledgerin the model,which is the largest single extension and the reason it is last despite
being the simplest state machine.
Two harness extensions are worth doing alongside (1) rather than speculatively
now: a scheduler-aware substitute for
PsqlShareLedger._lockso two actorscan contend on the writer lock inside one process, and a systematic
interleaving explorer over runnable actors so a scenario can assert an
invariant across every schedule instead of one chosen schedule.
Verification
python -m unittest discover -s tests -p 'test_*.py'— 2023 tests, plusone expected failure (the PRISM: orphaned lease-tuple lock can block writer failover for hours after a partition mid-landing #123 assertion above). The only other failures are
the five
os.splicespool tests intest_prism_job_builder.py, which failon macOS and pass on Linux — pre-existing and unrelated.
test_prism_share_ledger,test_prism_background_services,test_prism_share_writer,test_prism_share_writer_service,test_prism_coordinator_shutdown) —299 tests, all pass.
python -m compileall -q docker lab tests examples scripts— clean.every time.
shellcheck -xover all 23 tracked shell files — clean.GIT_CONFIG_GLOBAL=/dev/null.CI on this branch is green: 2023 tests,
expected failures=1. The five macOSos.splicefailures listed above do not occur on the Linux runners, asexpected. Every lint step —
bash -n, ShellCheck, andcompileall— passes;ShellCheck was additionally run locally in Docker across all 23 tracked shell
files.
Review round
This PR went through an adversarial review pass that verified the model's
PostgreSQL claims experimentally against a scratch PostgreSQL 16.15 cluster.
It found two blocking defects, both now fixed:
The model re-read committed state after a tuple-lock wait. PostgreSQL
takes one snapshot per command in READ COMMITTED; a statement that blocks
re-reads only the conflicting tuple (EvalPlanQual) to evaluate its write
predicate, while every other scan — including the
COALESCEarm that buildsthe whole not-acquired result — keeps the original snapshot. The model
reported a fresh row and a small
lease_age_secondswhere the real serverreports the pre-wait row and an age that has silently absorbed the entire
wait. That age is the row edge of
_writer_lease_adoption_wait_seconds, sothe model was hiding the input that makes the adoption CAS's
updated_atpredicate load-bearing.
Fixing it surfaced a real production behaviour the harness had been
concealing: when two coordinators race the first ever acquire, the loser's
DO UPDATEmatches nothing and itsCOALESCEfallback reads a snapshot inwhich no row exists yet, so the statement returns SQL
NULLandparse_single_json_valueraisespostgres query returned no JSONout ofPsqlShareLedger.__init__— an error naming nothing about leases. Filed as#140 and pinned by
test_first_acquire_race_loser_gets_an_unhelpful_error,which also asserts the contrast against the ordinary "lease is held by"
refusal. Not fixed here: it is a bootstrap-only diagnostic defect rather than a
correctness one, and this PR is the harness rather than the fixes it enables.
It is the first defect this harness found on its own.
The deliberately failing #123 test did not go green under the fix its own
docstring names. It advanced the clock once and drained once, so any fix
whose bounded wait spans more than one deadline left the successor parked and
the test red. It now drives the successor through every deadline it reaches.
Verified by simulating both candidate fixes:
lock_timeoutalone andlock_timeoutplus a bounded retry now both turn it green, and it stays redon
2.x.x.Also fixed from that pass: non-matching
UPDATEs no longer queue on the tuplelock (PostgreSQL evaluates the predicate against the snapshot first and never
locks a row it excludes — latent today, but it would misrepresent any fencing
argument); tuple-lock waiters are now granted in arrival order; pool
exhaustion honours the caller's deadline; the guard's serialization is pinned
against
_NativePostgresLeaseGuard._query_lockitself rather than against theharness's re-description of it; both protocols are
@runtime_checkablewithassertIsInstanceand full-signature checks, since the repository runs nomypy;
_pool_application_nameis injectable, removing the last uncontrollednondeterminism inside the code under test; and the clock is a declared class
attribute rather than a
getattrfallback.The review confirmed as sound: the baton protocol (no lost wakeup, no two
runnable actors), order stability across 20 runs and varying
PYTHONHASHSEED,the
snapshot:verifyattribution model,ON CONFLICT DO UPDATElocking witha false
WHERE,vanish()'s autocommit/explicit split, the production diff'sblast radius, and all three #123 claims about the tree.
Refs #128, #123, #140.