Skip to content

Gate PRISM Postgres test containers on the real server - #134

Merged
kiwidream merged 1 commit into
mainfrom
gate-prism-postgres-readiness
Aug 17, 2026
Merged

kiwidream merged 1 commit into
mainfrom
gate-prism-postgres-readiness

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

What was failing

main CI run 32050119968, job Lint, compile, and test, step Run Postgres production-scale fixture tests:

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432"
failed: No such file or directory

Root cause

The Postgres image initialises a fresh data directory by running a temporary server that listens on the unix socket only (listen_addresses=''), then shuts it down and starts the real one.

Every PRISM test script gated on docker exec <container> pg_isready -U qbit -d qbit, which probes over that socket — so it reports "accepting connections" during initialisation. The harness then proceeded against the throwaway server and the next call raced its shutdown, hitting database "qbit" does not exist, the database system is shutting down, or the missing socket once the file was removed.

Reproduced deterministically against postgres:16-alpine: the socket probe returned success at poll 15 of a fresh container, and the next 30 psql calls produced 19-21 failures per 30 across five runs.

The window is roughly a second, which is why the scale step was the one to break: the preceding ledger step had already pulled the image, so the scale container reached the temporary-server phase inside the wait loop's first probe.

The fix

New test/prism-postgres-lib.sh exporting wait_for_prism_postgres_container, which gates on the TCP listener — absent until the real server is up, since the temporary one binds no TCP address — and confirms with a real query over the socket the tests actually use.

It replaces the identical racy loop in all six PRISM test scripts:

  • test/test-prism-postgres-scale.sh
  • test/test-prism-postgres-ledger.sh
  • test/test-prism-postgres-native-ledger.sh
  • test/test-prism-postgres-throughput.sh
  • test/test-prism-combined-regtest.sh
  • test/test-prism-stratum-regtest-live.sh

Same measurement with the new gate: 0 failures per 30, three runs.

Test-harness only; no production or lab/ code is touched.

Verification

Every step of the failing job, run locally:

Check Result
bash -n on all *.sh pass
shellcheck -x (in Docker) pass
compileall docker lab tests examples scripts pass
make test-prism-postgres-ledger PASS
make test-prism-postgres-scale PASS (the failing step)
tests.test_mainnet_compose_contract 23 tests OK
cargo test --locked --workspace --all-targets 0 failed
Compose validation, 4 profiles pass

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

The scale fixture step failed on main with:

    psql: error: connection to server on socket
    "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory

The Postgres image initialises a fresh data directory by running a
temporary server that listens on the unix socket only, then shuts it down
and starts the real one. `pg_isready` over that socket reports "accepting
connections" during initialisation, so the harness proceeded against the
throwaway server and the very next call raced its shutdown -- hitting
`database "qbit" does not exist`, `the database system is shutting down`,
or the missing socket once the file was removed.

The window is roughly a second, which is why the scale step was the one to
break: the preceding ledger step had already pulled the image, so its
container reached the temporary-server phase inside the wait loop's first
probe.

Gate on the TCP listener instead -- absent until the real server is up,
since the temporary one runs with listen_addresses='' -- and confirm with
a real query over the socket the tests actually use. The probe now lives
in test/prism-postgres-lib.sh and replaces the identical racy loop in all
six PRISM test scripts.

Measured against postgres:16-alpine, 30 psql calls issued immediately
after the gate: 19-21 failures per 30 with the old socket probe, 0 per 30
with this one.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

@kiwidream
kiwidream merged commit f28a6bf into main Aug 17, 2026
11 checks passed
kiwidream added a commit that referenced this pull request Aug 18, 2026
…rdiff) (#141)

* Land PRISM core fixups from the PRs-134-139 stability review

F1: _acquire_operation_gate's slicing path now reads the injected
self._monotonic clock at all three deadline sites, so a virtual test
clock can drive admission-wait slicing deterministically; covered by a
new virtual-clock test.

F2: load_coordinator_config rejects PRISM_WATCHDOG_TIMEOUT_SECONDS
below 1.0 at startup, keeping the derived landing-budget ceiling
(half the tolerance) meaningfully below the watchdog tolerance.

F3: the sliced-admission liveness test drops its per-gap 0.3s wall
clock bound, which false-reds on loaded CI hosts; the determinism
intent (stamp count, total elapsed, raised timeout) is unchanged and
cadence is pinned by the new virtual-clock test instead.

F4: the concurrency harness baton timeout is overridable via
PRISM_HARNESS_BATON_TIMEOUT_SECONDS (default unchanged at 20.0); it
remains a false-red failure detector and never influences ordering.

F5: startup warns on stderr when the idle-in-transaction timeout
exceeds the writer-lease acquire budget (attempts x per-attempt lock
deadline), where an orphaned backend holding the lease row lock can
no longer be reaped mid-budget and startup crash-loops instead of
self-healing.

F6: the superseded-envelope restore authority proof now runs after
the payout balance lock and the publication order guard are acquired,
so a writer deposed during the unbounded lock wait no longer restores
on stale authority; the withheld-authority diagnostic is deferred
until the locks are released. A new test deposes the writer inside
the publication guard and fails against the old check-then-act shape.

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

* Replace the racy socket-only prism-postgres healthcheck with a TCP-gated probe plus SELECT 1 confirm

The postgres image's initdb temporary server accepts unix-socket
connections and then shuts down, so a socket-only pg_isready can release
dependents against the throwaway server (the race PR #134 fixed in the
test scripts). Gate on the real TCP listener first, then confirm with a
real query.

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

* Wire the #137 lease/session-guard env knobs into the ctv broadcaster and backfill scripts

Both operator-run scripts construct PsqlShareLedger directly and got the
class defaults for lease_acquire_lock_timeout_seconds,
lease_acquire_attempts, and the four Postgres session-guard knobs, so
operator tuning of PRISM_LEDGER_LEASE_ACQUIRE_* / PRISM_POSTGRES_* never
reached them. Mirror the coordinator: read the same six env vars with the
coordinator_config helpers and defaults and pass them through. The
backfill script exposes them as CLI flags with env defaults, matching its
existing --lease-ttl-seconds pattern, with construction extracted into
ledger_from_args so the path is testable.

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

* Document that vardiff retention is process-local and can strand a stuck-high resume

The SessionDifficultyStore is in-memory: a coordinator restart, including
the watchdog's terminal exit_process(1), empties it, so the post-restart
reconnect wave is not smoothed by retention. And with the idle sweep off
(the deployed default) a rig that converged high and reconnects within
TTL on weaker hardware can resume too high with no share signal to bring
it down, bounded by the resume TTL. Honest-disclosure comments and
.env.example notes only; no behavior change.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
kiwidream added a commit that referenced this pull request Aug 19, 2026
…y seed (#124) (#155)

* Make schema applies atomic and repair a poisoned carry-forward summary seed

The psql schema-apply path ran every statement of
crates/qbit-prism/sql/001_share_ledger.sql in its own autocommit
transaction, so the carry-forward summary sync triggers could commit
before the one-time seeding block ran. An interruption in that gap, or
a live writer confirming or reversing a block in it, left the summary
holding only post-trigger deltas; the seed's NOT EXISTS guard then
treated that partial summary as seeded and skipped permanently, on that
apply and every later one, silently under-reporting every miner's
balance by their full pre-upgrade carry (#124).

- The schema script now wraps itself in one BEGIN/COMMIT transaction,
  so the apply is atomic under every client: the coordinator's psql
  backend, the native psycopg client, and a manual operator apply with
  plain autocommit psql. The old explicit BEGIN/COMMIT around only the
  audit-publication migration phase remains folded into that wrapper;
  the transaction-scoped advisory lock is now held for the whole apply.
- _run_sql additionally passes --single-transaction, so every psql
  invocation (query batches included) is one transaction. psql tolerates
  the script's own wrapper with a warning; the combination was checked
  against ON_ERROR_ROLLBACK (never set: --no-psqlrc), \connect (absent),
  and explicit transaction control in runtime SQL (absent).
- The seed guard compares the summary's active row-count total against
  the active carry history (one statement, so concurrent commits cannot
  manufacture a mismatch) and also checks summary drift, rebuilding
  from history on disagreement. A deployment already poisoned by the
  old guard is repaired by the next apply instead of locked in.
- The psycopg ImportError fallback to the psql backend is no longer
  silent; it prints a warning line.
- docs/prism-ledger-ops.md now documents the single-transaction apply
  requirement with the writer stopped.

* Add a poison-and-repair regression test for the carry-forward seed

A Docker-gated Postgres test (test/test-prism-postgres-seed-guard.sh,
wired as make test-prism-postgres-seed-guard and run in the CI
postgres-native-client job, which installs psycopg) reproduces #124's
mechanism end to end:

- The schema is applied non-atomically the way the pre-fix ops doc
  instructed (the script's own BEGIN wrapper is stripped and the head --
  tables, functions, and the carry-forward summary sync triggers, but
  not the seed -- is applied with per-statement autocommit psql).
- Pre-upgrade carry history is inserted with the summary triggers
  suppressed, then a live writer confirms a prepared block in the
  trigger/seed gap, leaving the summary holding only that post-trigger
  delta.
- The old emptiness-based seed guard (embedded verbatim) locks the
  poison in: miner-a's pre-upgrade carry is silently absent.
- A re-apply through the psql backend, and a re-poisoned re-apply
  through the native psycopg backend, both repair the summary to match
  the carry history with zero drift.
- A second scenario injects a failure inside the apply's transaction on
  both backends and asserts nothing committed, proving the atomicity
  half of the fix.

The container readiness gate follows the #134 pattern: the real TCP
listener plus a confirming query, never the racy socket-only probe.

Test harness built by a delegated remote worker; the split-marker,
wrapper-stripping, and in-transaction failure injection were adapted to
the landed self-wrapping schema script and reviewed here.

* Address review nits: setval comment accuracy, ops-doc apply semantics, drift-only guard test

- The setval comment no longer claims rollback undoes the allocator
  mutation on a pre-existing sequence (it does not); it now states the
  real residue semantics -- a failed re-apply leaves ordinal gaps only
  -- and warns future edits not to move validation after the setval.
- The ops doc's writer-stopped rationale now describes the actual
  behavior under the atomic apply (concurrent mutations block on the
  apply's table locks and fire the recreated triggers afterwards,
  inviting lock waits and deadlocks) instead of the stale
  dropped-mutations mechanism, and documents the two harmless psql
  warnings the single-transaction + self-wrapper combination emits.
- The regression test gains the guard's drift-only branch: a summary
  with matching row-count totals but corrupted balances is repaired by
  the next apply.
kiwidream added a commit that referenced this pull request Sep 10, 2026
* Gate PRISM Postgres test containers on the real server (#134)

The scale fixture step failed on main with:

    psql: error: connection to server on socket
    "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory

The Postgres image initialises a fresh data directory by running a
temporary server that listens on the unix socket only, then shuts it down
and starts the real one. `pg_isready` over that socket reports "accepting
connections" during initialisation, so the harness proceeded against the
throwaway server and the very next call raced its shutdown -- hitting
`database "qbit" does not exist`, `the database system is shutting down`,
or the missing socket once the file was removed.

The window is roughly a second, which is why the scale step was the one to
break: the preceding ledger step had already pulled the image, so its
container reached the temporary-server phase inside the wait loop's first
probe.

Gate on the TCP listener instead -- absent until the real server is up,
since the temporary one runs with listen_addresses='' -- and confirm with
a real query over the socket the tests actually use. The probe now lives
in test/prism-postgres-lib.sh and replaces the identical racy loop in all
six PRISM test scripts.

Measured against postgres:16-alpine, 30 psql calls issued immediately
after the gate: 19-21 failures per 30 with the old socket probe, 0 per 30
with this one.

* Rewrite Prism in Rust with multi-instance PostgreSQL coordination

* Smoke-test the native Prism runtime image in CI

* Preserve exact decimal CTV fee estimates before rounding

* Wait for expired-claim rollback before asserting fanout recovery

* Fence automatic fee premiums and fallback recipients across instances

* Expose due failed CTV fanouts in pending feeds

* Record template parent heights for accepted shares

* Limit public block and earnings statistics to confirmed blocks

* Filter confirmed legacy payout history before limiting rows

* Restore live Prism node and CTV readiness safeguards

* Share qbit RPC defaults between Prism writer and public service

* Persist native block compact bits from the durable header

* Pass native RPC and resource settings through Prism Compose services

* Retain CPFP reservations and fence superseded mining work

Keep funding protected until active child confirmation, reject same-parent jobs from older payout revisions, and separate general RPC deadlines from block submission. Preserve wallet proxy routes and cover recovery with real qbit regressions.

* Recover invalid unsigned CPFP funding reservations

Revalidate funding before signing and retire unusable unsigned reservations into a durable cleanup journal. Fence replacement allocation across instances, preserve signed packages, and verify exact wallet output ownership before cleanup.

* Renew candidate leases and prioritize fresh block submissions

Keep processing fenced through build waits, audit persistence and RPCs. Allow lease renewal during landing, cancel lost owners, and check expiry after row-lock waits. Prefer fresh candidates with periodic oldest-due service and skip rebuilding proven stale backlog.

* Reject transient payout validation failures without fallback

* Remove Python from Prism stale grace preflight

* Preserve retained-job admission and literal difficulty validation

---------

Co-authored-by: Alex <[email protected]>
Co-authored-by: Robert Clarke <[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
  the coordinator fragments last so they win.

- The startup lease upsert and adoption CAS run through
  _run_lease_acquisition_json: each attempt under the existing
  statement_timeout machinery (SET LOCAL statement_timeout/lock_timeout,
  or PGOPTIONS plus subprocess timeout), a diagnostic per timed-out
  attempt, and a RuntimeError naming the locked lease row after the retry
  budget. 5 attempts x 5s outlasts the 15s idle-in-transaction timeout, so
  the orphan case self-heals; only a genuinely stuck lock exits the
  process for the supervisor to restart. The outer _ensure_writer_lease
  TTL wait is unchanged - waiting out a live holder is intended failover.

Six tunables (PRISM_POSTGRES_IDLE_IN_TRANSACTION_TIMEOUT_SECONDS,
PRISM_POSTGRES_TCP_KEEPALIVES_{IDLE_SECONDS,INTERVAL_SECONDS,COUNT},
PRISM_LEDGER_LEASE_ACQUIRE_{LOCK_TIMEOUT_SECONDS,ATTEMPTS}) flow through
LedgerConfig, the coordinator wiring, .env.example, and compose.yaml, with
fail-closed validation in both load_coordinator_config and
PsqlShareLedger.__init__ for the direct-construction daemons.

Regression tests cover the guard options on all three connection paths,
conninfo option merging, the bounded startup deadline, the bounded retry
with visible failure, recovery on a later attempt, and config
defaults/validation; each was observed failing against the unmodified tree.

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

* Report lease-acquisition timeouts honestly and pin the bounds

The fatal path in _run_lease_acquisition_json diagnosed every
LedgerOperationTimeout as a lock conflict on the qbit_ledger_writer_lease
row. A connect timeout, an exhausted pool slot, a psql subprocess timeout,
and a healthy-but-overloaded server all raise the same exception, so an
unreachable Postgres was reported to the operator as a stuck transaction.
The RuntimeError was also raised without `from`, discarding the one
exception that said what actually failed.

Both the per-attempt line and the fatal error now name the lock conflict
as the most common cause without asserting it, quote the underlying
exception text, and the fatal error chains the originating timeout.

Two mutations of the acquisition bound survived the suite:

- Reverting _try_adopt_writer_lease to a bare _run_json left all eight
  tests green. Two new tests drive the real _ensure_writer_lease adoption
  branch — fast-adoption capable, a heartbeat-prefixed predecessor silent
  past both the row and guard edges — and assert the CAS runs under a
  bounded deadline and that a persistently blocked CAS stops after
  DEFAULT_LEASE_ACQUIRE_ATTEMPTS with a chained RuntimeError.
- Widening `except LedgerOperationTimeout` also left the suite green. A
  new test asserts a non-timeout failure (the RuntimeError run_json raises
  for a wrapped OperationalError, and an IdleInTransactionSessionTimeout —
  sqlstate 25P03, an InternalError rather than an OperationalError)
  propagates unchanged on the first attempt, with no retry and no
  diagnostic printed.

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

* Match the orphan-lock comments and docs to what the guards deliver

Several comments from the bounded-acquisition change claimed more than
the code provides. The PostgresSessionGuards docstring said no session
the coordinator opens can become an unreapable lock holder; tcp_keepalives_*
are silently ignored on Unix-socket connections and on platforms that do
not implement them, and session settings reach only this coordinator's own
sessions — a foreign holder is bounded solely by the acquisition deadline.
The attempt-budget comments said the ~25s budget "exceeds" the 15s
idle_in_transaction_session_timeout so the orphan is reaped mid-budget;
that timer runs on the blocking backend's clock from when its transaction
went idle, not from when the successor starts retrying, so the budget is
sized to outlast a typical reap rather than guaranteed to contain one.

Also documents the deployment caveats in the ops guide: native connections
now always set the libpq `options` parameter, so a pooler that rejects
startup options fails visibly at connect (the default compose topology
connects directly and is unaffected); the psql backend carries the guards
in PGOPTIONS, which a wrapper command that drops its environment silently
discards; and Unix-socket DSNs ignore the keepalive GUCs, leaving the
idle-in-transaction timeout as the guard that still applies.

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

* Reconcile the concurrency harness with the bounded acquisition path

The harness suites encode #123 as an unfixed defect; this branch fixes it,
so fourteen of their assertions had to be answered rather than muted.

The orphan-lock bound is now proven. OrphanedLeaseLockFailoverBoundTests
was authored against the fixed behaviour with an expectedFailure marker and
a docstring demanding its removal by the fixing commit; it passes, so the
marker is gone and the assertion is untouched. Its two siblings encoded
"the bug is present": the successor now parks under the configured
acquisition deadline instead of forever, so the wait is asserted as a
positive bound tied to the shipped tunable, and the "does not end" test now
pins how it ends -- the exact retry budget, the elapsed time that budget
implies, and a RuntimeError chaining the underlying LedgerOperationTimeout.
The orphan and the successor's park on it are kept as evidence throughout.

FakeSqlBackend needed a fidelity fix first, and it is the substantive one.
Both shipped LedgerSqlPort implementations translate a cancellation caused
by the caller's own deadline into LedgerOperationTimeout, and only when
that deadline was armed; the model did this for pool-slot exhaustion but
not for the tuple-lock wait, because before this branch no deadline ever
reached a pooled lease statement. Without the translation the model raised
a bare LockTimeout straight through the retry loop, so the suites appeared
to exercise a bounded retry that in fact ran once.

Arming the acquisition deadline also makes the acquire transaction-scoped,
which is a real widening: a coordinator that vanishes mid-acquire can now
orphan the lease lock on a path that previously could not produce one. The
model-fidelity test that used the acquire as its example of an autocommit
statement drives an unscoped renewal instead, the new shape is pinned by a
test of its own, and docs/prism-ledger-ops.md records the trade -- the new
orphan is bounded by idle_in_transaction_session_timeout, which is why that
guard is not optional. This harness models no reaper, so that test pins
only what the model supports and says where the guard itself is pinned.

Remaining changes are exact-trace updates: the acquire and adoption CAS now
commit explicitly, so each offers a precommit stop. Traces were replaced
with the observed ones rather than loosened to prefix or subset matches,
since exact order is what they exist to prove. The lost-adoption-CAS driver
needed one extra step to reach the same interleaving, the successor's
observation no longer committing itself.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Alex <[email protected]>

* Apply stability-review fixups from PRs 134-139 (PRISM core + infra/vardiff) (#141)

* Land PRISM core fixups from the PRs-134-139 stability review

F1: _acquire_operation_gate's slicing path now reads the injected
self._monotonic clock at all three deadline sites, so a virtual test
clock can drive admission-wait slicing deterministically; covered by a
new virtual-clock test.

F2: load_coordinator_config rejects PRISM_WATCHDOG_TIMEOUT_SECONDS
below 1.0 at startup, keeping the derived landing-budget ceiling
(half the tolerance) meaningfully below the watchdog tolerance.

F3: the sliced-admission liveness test drops its per-gap 0.3s wall
clock bound, which false-reds on loaded CI hosts; the determinism
intent (stamp count, total elapsed, raised timeout) is unchanged and
cadence is pinned by the new virtual-clock test instead.

F4: the concurrency harness baton timeout is overridable via
PRISM_HARNESS_BATON_TIMEOUT_SECONDS (default unchanged at 20.0); it
remains a false-red failure detector and never influences ordering.

F5: startup warns on stderr when the idle-in-transaction timeout
exceeds the writer-lease acquire budget (attempts x per-attempt lock
deadline), where an orphaned backend holding the lease row lock can
no longer be reaped mid-budget and startup crash-loops instead of
self-healing.

F6: the superseded-envelope restore authority proof now runs after
the payout balance lock and the publication order guard are acquired,
so a writer deposed during the unbounded lock wait no longer restores
on stale authority; the withheld-authority diagnostic is deferred
until the locks are released. A new test deposes the writer inside
the publication guard and fails against the old check-then-act shape.

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

* Replace the racy socket-only prism-postgres healthcheck with a TCP-gated probe plus SELECT 1 confirm

The postgres image's initdb temporary server accepts unix-socket
connections and then shuts down, so a socket-only pg_isready can release
dependents against the throwaway server (the race PR #134 fixed in the
test scripts). Gate on the real TCP listener first, then confirm with a
real query.

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

* Wire the #137 lease/sessi