Skip to content

Stop PRISM lease heartbeat self-fencing during accepted-block persistence (1.x.x) - #114

Merged
djh58 merged 2 commits into
1.x.xfrom
fix-prism-lease-self-fencing
Aug 12, 2026
Merged

djh58 merged 2 commits into
1.x.xfrom
fix-prism-lease-self-fencing

Conversation

@Anatolie

@Anatolie Anatolie commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Fixes the production self-fencing loop introduced by #111 (c374129), observed at block height 39416: eight coordinator deaths at ~4m20s intervals during accepted-block persistence.

Failure mechanism

persist_accepted_block() opens its CTE by updating qbit_ledger_writer_lease and holds that tuple's row lock for the entire transaction (29 MB audit bundle + 207 payouts + 207 carry-forwards took >1.7 s in production). The #111 heartbeat renewed the lease on the same tuple through the dedicated advisory-guard connection, whose statement_timeout=500 then fired (SQLSTATE 57014, while updating tuple ... in relation "qbit_ledger_writer_lease"). ledger_lease_heartbeat_loop() treats any exception as loss of the guarded session and hard-exits. Docker restarted the coordinator, the replacement adopted the lease, retried the same block, and died identically.

Fix

Per the required design correction — not a timeout bump, and no 57014 swallowing:

  1. Non-locking guarded-session heartbeat. PsqlShareLedger.verify_writer_lease_guard_session() replaces renew_writer_lease_heartbeat(). On the guard connection it proves: the session answers, pg_locks still shows this backend holding the writer advisory lock, and the committed lease row still names this exact session — all plain reads that never queue behind the row lock. Guard loss, a broken session, or a fenced-out token still raises → prompt hard exit (fail closed).
  2. Adoption silence measured from guard acquisition. The successor records when it acquires the advisory guard; _writer_lease_adoption_wait_seconds() now returns max(remaining row-silence, remaining silence-since-guard-acquisition). A predecessor that dies mid-transaction with a minutes-stale updated_at still gets one full silence interval to self-fence after losing its guard. The exact-predecessor-session CAS is unchanged.
  3. External-side-effect fence uses the same non-locking verification, so submitblock/CTV preflights no longer contend with an in-flight accepted-block transaction on the lease tuple.
  4. Lease TTL freshness is unaffected: every fenced write and each idle CTV-daemon pass still renews lease_expires_at through the fenced path; the heartbeat never carried the TTL.

Regression tests

  • Guarded verification succeeds while a simulated fenced write holds the lease tuple past the statement timeout; the old renewal SQL dies on the same simulated lock (control) — tests/test_prism_share_ledger.py.
  • Coordinator heartbeat runs at full cadence through a persist_accepted_block() outlasting both the statement timeout and the heartbeat failure budget: no hard exit, persistence completes — tests/test_prism_coordinator_shutdown.py.
  • Breaking the guard session still hard-exits promptly (heartbeat and external fence paths).
  • A successor cannot CAS-adopt until a full silence interval after acquiring the advisory guard, even with updated_at 300 s stale.
  • External fence stays non-blocking during long persistence and fails closed after guard loss.
  • Existing live-twin, stale-session adoption, shutdown, and lease-release tests updated for the new wait floor and green (test_prism_share_ledger 143, test_prism_coordinator_shutdown 46, test_prism_coordinator_vardiff 341, plus job-cache/CTV/audit/dashboard/stratum/self-check suites).

Drive-by

Three SimpleNamespace pending-share test fakes on 1.x.x lacked job_issued_at_ms/accepted_at_ms (required by the unfenced-append landing fence), which broke two shutdown tests and hung the vardiff suite in an infinite append retry on the current base. Added the two fields.

🤖 Generated with Claude Code


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


Note

High Risk
Changes writer-lease heartbeat, external fencing, and same-identity adoption timing—core coordinator safety paths that prevent twin writers and control hard-exit behavior. Incorrect fencing here can cause restart loops or unsafe lease adoption.

Overview
Fixes the production self-fencing restart loop where the lease heartbeat updated qbit_ledger_writer_lease while persist_accepted_block held that row lock, timing out the guard session and hard-exiting a healthy coordinator.

Heartbeat and external fences now use non-locking verification. verify_writer_lease_guard_session proves the advisory-guard session is live via pg_locks and a committed lease-row read, without updating or locking the lease tuple. The coordinator prefers this path (with legacy renewal only as fallback), so heartbeats and pre-RPC fences no longer contend with long fenced writes.

Same-identity adoption silence is dual-edged. Successors wait the later of remaining row silence and a full silence interval after acquiring the advisory guard, so a predecessor that dies mid-transaction with a stale updated_at still gets time to self-fence before CAS adoption.

Docs and regression tests cover the block-39416 failure mode, including verification during a held lease-row lock and adoption waits against minutes-stale lease rows.

Reviewed by Cursor Bugbot for commit 9056ca0. Bugbot is set up for automated code reviews on this repo. Configure here.

Commit c374129 (#111) renewed the writer lease on the dedicated
advisory-guard connection (statement_timeout=500ms). persist_accepted_block
opens its CTE by updating the same qbit_ledger_writer_lease tuple and holds
that row lock for the whole transaction, so any accepted block that takes
longer than the timeout killed the heartbeat with SQLSTATE 57014, the
coordinator hard-exited mid-finalization, and the Docker replacement adopted
the lease and died the same way (block 39416 looped eight times at ~4m20s).

Make the guarded-session heartbeat a non-locking liveness check: the guard
connection now proves the session answers, still holds the advisory lock in
pg_locks, and the committed lease row still names the exact session - it
never touches the tuple fenced writes lock. The external-side-effect fence
uses the same verification, so submitblock/CTV preflights no longer contend
with in-flight persistence either. Lease TTL freshness is unchanged: every
fenced write and each idle daemon pass still renews through the fenced path.

Because updated_at can now legitimately look stale during a long fenced
transaction, adoption silence is measured from two edges and the later one
wins: the lease row's updated_at age and the successor's own advisory-guard
acquisition. A successor therefore always grants its predecessor a full
silence interval to self-fence after guard loss, no matter how old the row
already is. The exact-session CAS and fail-closed handling of a broken or
fenced-out guard session are unchanged.

Also repairs pre-existing test fakes on 1.x.x whose SimpleNamespace pending
shares lacked job_issued_at_ms/accepted_at_ms, which broke two shutdown
tests and hung the vardiff suite in an infinite append retry.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9056ca0578

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread lab/prism/prism_coordinator.py Resolved
The non-locking guarded-session heartbeat stopped advancing
lease_expires_at entirely, so an idle coordinator (no fenced writes for a
lease TTL, CTV broadcaster disabled) let the singleton row expire while
alive; a different writer identity could then seize it through the expiry
CAS because its advisory-lock key differs from the incumbent's.

Fold an exact-identity TTL renewal into the verification statement using
FOR NO KEY UPDATE SKIP LOCKED: the heartbeat renews whenever the lease
tuple is uncontended and skips without queueing while a fenced
transaction (persist_accepted_block) holds the row lock, preserving the
no-self-fencing guarantee this branch introduced.

Addresses the Codex P1 review finding on PR #114.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 556e10eac0

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread lab/prism/share_ledger.py Resolved
@djh58
djh58 merged commit 6a74e9a into 1.x.x Aug 12, 2026
10 of 12 checks passed
Anatolie added a commit that referenced this pull request Aug 12, 2026
The SKIP LOCKED heartbeat renewal skips silently, and the token check is
a plain MVCC read: with the lease row expired and a different-identity
_try_acquire_writer_lease holding the tuple lock mid-CAS, verification
still saw the stale committed session token and reported the guarded
session live just before the takeover committed. The queueing renewal it
replaced caught exactly this case by re-evaluating after the claimant's
commit. Reachable after host suspend, where the local monotonic
freshness gate cannot be trusted either.

Report the committed row's expiry in the same guarded statement and
raise when the renewal was lock-blocked while the row was already
expired: that combination means an expiry claim may be in flight, so a
stale token snapshot is not proof of liveness. A healthy coordinator
never triggers it - the heartbeat keeps lease_expires_at a full TTL
ahead, so fenced writes always lock an unexpired row - and renewing an
uncontended expired row (idle recovery) stays allowed, since holding
the tuple lock proves no claim was in flight.

Addresses the second Codex P1 review finding on PR #114.

Co-Authored-By: Claude Fable 5 <[email protected]>
Anatolie added a commit that referenced this pull request Aug 12, 2026
The SKIP LOCKED heartbeat renewal skips silently, and the token check is
a plain MVCC read: with the lease row expired and a different-identity
_try_acquire_writer_lease holding the tuple lock mid-CAS, verification
still saw the stale committed session token and reported the guarded
session live just before the takeover committed. The queueing renewal it
replaced caught exactly this case by re-evaluating after the claimant's
commit. Reachable after host suspend, where the local monotonic
freshness gate cannot be trusted either.

Report the committed row's expiry in the same guarded statement and
raise when the renewal was lock-blocked while the row was already
expired: that combination means an expiry claim may be in flight, so a
stale token snapshot is not proof of liveness. A healthy coordinator
never triggers it - the heartbeat keeps lease_expires_at a full TTL
ahead, so fenced writes always lock an unexpired row - and renewing an
uncontended expired row (idle recovery) stays allowed, since holding
the tuple lock proves no claim was in flight.

Addresses the second Codex P1 review finding on PR #114.

Co-Authored-By: Claude Fable 5 <[email protected]>
Anatolie added a commit that referenced this pull request Aug 13, 2026
…laim (1.x.x) (#116)

* Fail closed when a lock-blocked lease renewal races an expiry claim

The SKIP LOCKED heartbeat renewal skips silently, and the token check is
a plain MVCC read: with the lease row expired and a different-identity
_try_acquire_writer_lease holding the tuple lock mid-CAS, verification
still saw the stale committed session token and reported the guarded
session live just before the takeover committed. The queueing renewal it
replaced caught exactly this case by re-evaluating after the claimant's
commit. Reachable after host suspend, where the local monotonic
freshness gate cannot be trusted either.

Report the committed row's expiry in the same guarded statement and
raise when the renewal was lock-blocked while the row was already
expired: that combination means an expiry claim may be in flight, so a
stale token snapshot is not proof of liveness. A healthy coordinator
never triggers it - the heartbeat keeps lease_expires_at a full TTL
ahead, so fenced writes always lock an unexpired row - and renewing an
uncontended expired row (idle recovery) stays allowed, since holding
the tuple lock proves no claim was in flight.

Addresses the second Codex P1 review finding on PR #114.

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

* Exempt the writer's own fenced write from the expired-lease fail-closed

The fail-closed branch added for the expiry-claim race treats every
lock-blocked renewal over an expired row as a possible competing claim.
But a fenced write such as persist_accepted_block holds the lease tuple
for its whole autocommit statement, during which the heartbeat cannot
renew the TTL; a statement outlasting the remaining TTL therefore left
the committed row expired with the renewal lock-blocked, and the
heartbeat hard-exited the coordinator mid-write. That rolls back a valid
write and restart-loops on every similarly slow block - the same class
of self-fencing the SKIP LOCKED renewal was introduced to fix. Raising
there is also unnecessary: the write's exclusive tuple lock means no
expiry claim can be in flight behind it, and its commit refreshes
lease_expires_at before any queued claimant re-evaluates its expiry CAS,
so the session provably survives.

Give the writer's pooled connections a per-process-unique
application_name and have the verification statement attribute the
committed row's locker through pg_stat_activity: the row's xmax is the
locker's transaction id, and a backend running that transaction under
this process's pool name is the writer's own fenced write. Only an
expired row locked by anyone else still raises. A predecessor or
replacement process never shares the name, so its in-flight writes keep
fencing this session out, and a missing attribution still defaults
closed.

Verified against live PostgreSQL 16: an own-backend uncommitted lease
lock with the committed row expired keeps verification live without
renewal; a different-identity expiry CAS holding the same lock still
raises in ~1ms without queueing; idle recovery, committed-takeover
detection, and unexpired-row lock tolerance are unchanged.

Addresses the Codex P2 review finding on PR #116.

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

* Withhold external RPCs while lease renewal defers to the writer's own write

The own-fenced-write exemption keeps the heartbeat from restart-looping
a coordinator whose write outlasts the lease TTL, but its survival
argument assumes the write commits. If it rolls back instead, the
expired row is released unchanged and a queued different-identity
claimant takes it immediately - so an external-side-effect fence that
accepted the exemption could authorize a submitblock or wallet RPC
moments before the takeover. The attribution proves who holds the lock,
not that the transaction will commit and refresh the lease.

Report the state as renewal_deferred_to_own_write in the verification
result and split the consumers: the heartbeat keeps treating it as live
(refusing to roll back the very write the lease defers to), while
_require_fresh_ledger_lease_for_external_side_effect refuses the RPC
with a new WriterLeaseRenewalDeferred error without arming the hard
exit. Both callers already retry deferred work on their own cadence -
the CTV broadcaster records the attempt as a failed row and rescans on
the next pass, and a block candidate stays in the durable outbox for
replay - so the effect runs once the commit lands a renewal, or fails
closed if the lease was truly lost.

Verified against live PostgreSQL 16: the own-backend expired-lock state
reports the deferral flag while staying live, and renewal, idle
recovery, foreign-claim fail-closed, and takeover detection are
unchanged.

Addresses the second Codex P2 review finding on PR #116.

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

* Pin the anchor-age ceiling in submit tests to stop epoch-bump flakes

test_predating_append_stays_undurable_while_landing_holds_submit_fence
intermittently failed CI with the append-invalidation epoch stuck at 0:
the row went durable but its bump never fired. The suite runs on a
synthetic millisecond timeline (declared anchors like 12000, share
stamps of 1-2) while _expose_inflight_scan_anchor prunes exposures
older than the real-wall-clock artifact ceiling, so the test's standing
anchor - exposed precisely to keep the bump deterministic, independent
of the landing's own declared-anchor lifetime - was born decades stale
and silently pruned the moment the landing exposed its declared anchor.
The assertion then degenerated into a thread race: the bump fired only
if the fenced append re-checked the predicate before the landing's
finally retired its own anchor, which a loaded runner loses.

Pin payout_artifact_max_anchor_age_seconds to infinity in
submit_coordinator so exposed anchors live exactly as long as each test
intends. This also covers the other fence tests that expose the same
synthetic anchor. Verified by reproducing the dead-anchor state
deterministically before the fix, and with the bump predicate now
holding even after the landing retires its anchor, plus 25 stress runs
of the four affected tests and the full suite green.

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

* Unwind the landed payout bar when the lease fence defers before submitblock

_mark_accepted_block_payout_landed arms its conservative barrier before
the lease fence so a transport failure's uncertain submitblock outcome
preserves the possibly-active coinbase's payout base. The new
WriterLeaseRenewalDeferred refusal exits that sequence before the RPC,
and - now that the fence no longer hard-exits the process - left the
landed=True transition armed in a live coordinator: reconciliation and
payout-state publication stayed barred until a later retry abandoned or
completed the candidate, even though qbitd provably never saw the block
and nothing needed preserving.

Catch the deferral at the submitblock fence and unmark the landed flag
this attempt armed. The pending preview survives - child work keeps
waiting instead of snapshotting pre-accept balances, matching the state
startup replay restores for a durable candidate - and the retry re-arms
landed before its own RPC. A transition landed by an earlier attempt
that did reach submitblock keeps its bar: that outcome is genuinely
uncertain (a lost RPC ack), and the pre-attempt landed snapshot the
disposition already takes distinguishes the two.

Addresses the Cursor Bugbot medium finding on PR #116.

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

* Recheck locker attribution on a fresh statement before failing closed

The expired-lease fail-closed exempts the writer's own fenced write by
attributing the lease tuple's locker through pg_stat_activity, but the
verification statement's lease-row reads share one MVCC snapshot while
pg_stat_activity reports live backend state. An own fenced write
committing between the SKIP LOCKED renewal's skip and the probe clears
its backend_xid while the snapshot still shows the old expired tuple:
renewal skipped, row expired, no attributable locker — indistinguishable
from a competing expiry claim, so the heartbeat hard-exited a healthy
coordinator whose renewal had in fact just landed with that commit.

Re-verify once on a fresh statement before raising. Its new snapshot
sees the committed refresh (the renewal lands normally), a completed
takeover (the exact-identity check fails closed with the fenced-out
error), or the same contended expiry (the lock-blocked fail-closed
stands). The recheck is bounded to one attempt, fires only for the
ambiguous expired-locked-unattributable shape, and never re-fires
on_query_start — it is the same verification's execution, not a new
queue wait. Every residual outcome remains fail-closed.

Reported by chatgpt-codex-connector on PR #116.

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

* Run the attribution recheck inside the guard's serialized query slot

The recheck re-invoked run_json, dropping and reacquiring the guard's
query lock between statements. The reacquisition could queue behind the
periodic heartbeat and other external fences, and that wait — plus the
second statement — was charged to the external fence's execution budget,
which is sized for a single statement and hard-exits on overrun. The
rescue the recheck exists to deliver could therefore be lost to lock
queueing in exactly the rare race it handles, and the docstring's claim
that the recheck is not a new queue wait was not true of the code.

Give the guard's run_json an in-slot followup hook: the callback decides
from the parsed result whether another statement runs, and any follow-up
executes inside the same lock acquisition. Each execute on the
autocommit session is still its own statement with a fresh snapshot,
which is what the recheck needs. Verification now passes its bounded
recheck as that followup, so the only cost charged to the caller's
execution budget is at most one more non-blocking statement, and
on_query_start still fires exactly once per verification. Identity
failures (lost advisory lock or session token) stay excluded from the
recheck predicate and surface through the ordinary raises.

Reported by cursor[bot] on PR #116.

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

* Defer external RPCs when an own-write renewal skip leaves a thin TTL

The renewal_deferred_to_own_write flag required the committed row to be
expired, so an own fenced write skipping renewal over a nearly-lapsed
row still authorized submitblock and wallet broadcasts. The TTL erodes
exactly while a long own write withholds renewals, so those
authorizations carry arbitrarily little runway: an RPC that outlives
the remaining TTL degenerates into the same rollback-dependent
authority the expired-case deferral rejects — the write rolls back, a
queued different-identity claimant takes the expired row, and the stale
coordinator's side effect is still in flight.

Report the deferral whenever an own-write skip finds the committed row
expired or within half the lease TTL of expiry. Skips over a row with
at least half the TTL remaining keep authorizing on the committed row's
standalone validity: every fenced commit refreshes the TTL, so steady
append traffic never erodes the margin, and deferring every own-write
skip would instead withhold submitblock behind saturated append traffic
— the submitter liveness the fast-lane submit path exists to protect.
Fail-closed behavior is unchanged: the margin implies nothing about
expiry, and the expired-and-unattributable shape still raises.

Reported by chatgpt-codex-connector on PR #116.

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

* Stop exact float equality on the coordination-blocked streak age

test_prepublication_payout_change_uses_coordination_budget asserted the
streak age equals exactly 5.0, but the age is plain float subtraction
and blocked_at is a real monotonic reading plus an offset: on a
long-uptime CI host (blocked_at + 5.0) - blocked_at rounds to
4.999999999999986 and the assertion fails, which is why the
pull_request run failed on 0adf605 while the push run of the identical
commit passed. Compare with assertAlmostEqual and a microsecond delta.

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

* Size the own-write deferral margin to the longest guarded RPC deadline

The half-TTL authority margin was a fixed heuristic: with
PRISM_BLOCK_SUBMIT_RPC_TIMEOUT_SECONDS independently configurable, an
operator could raise a guarded RPC deadline past TTL/2 and an own-write
skip authorized just above the margin could still outlive its runway —
reopening the rollback race the margin exists to close.

The ledger now takes lease_authority_margin_seconds and resolves the
margin as max(TTL/2, caller margin): the floor keeps the deferral
engaged through the eroded tail of a long own write even when
configured deadlines are short, and the caller term ties the margin to
what the fence can actually authorize. The coordinator passes twice its
longest guarded deadline — submitblock's dedicated timeout and the CTV
broadcast RPCs riding JsonRpc.call's default (now the named constant
DEFAULT_QBIT_RPC_CALL_TIMEOUT_SECONDS so changes route through the
margin) — doubled for transport-retry and scheduling slop. With default
config the resolved margin is unchanged (30s); a margin at or above the
TTL defers every own-write skip, the honest consequence of a guarded
effect that can outlast the whole lease.

Reported by chatgpt-codex-connector on PR #116.

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

* Add fixed headroom instead of doubling the authority-margin deadline

The 2x factor on the longest guarded RPC deadline cited transport-retry
slop, but no guarded effect can take twice its deadline: the fenced
mutating RPCs (submitblock, sendrawtransaction, submitpackage) are in
_QBIT_RPC_NO_TRANSPORT_RETRY_METHODS and never retry, and the read
paths that do retry share one wall-clock deadline across attempts.
Doubling only made the deferral needlessly eager as operators raise
PRISM_BLOCK_SUBMIT_RPC_TIMEOUT_SECONDS, reaching defer-every-skip while
a single RPC still fit comfortably inside the lease.

Size the margin as the longest guarded deadline plus a fixed
LEASE_AUTHORITY_MARGIN_HEADROOM_SECONDS covering what the deadline does
not: the fence-to-RPC scheduling gap and coordinator-vs-DB clock drift.
With default config the resolved margin is still the TTL/2 floor (30s).

Reported by cursor[bot] on PR #116.

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

* Budget the external fence for the verification's lawful recheck

The fence's execution budget equaled the guard's single-statement
timeout, but verify_writer_lease_guard_session may lawfully run two
statements inside one guarded slot — the verification and its
attribution recheck. Two moderately slow but in-deadline statements
(say 300ms each under database latency) blew the 500ms budget and
hard-exited a coordinator the recheck was about to prove healthy.

Export WRITER_LEASE_VERIFICATION_MAX_STATEMENTS from the ledger, derive
the recheck bound from it, and size the fence's execution budget as
that many fence timeouts. The queue-wait budget is unchanged: waiting
for the serialized slot already had its own heartbeat-failure budget.

Reported by chatgpt-codex-connector on PR #116.

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

* Enforce the RPC deadline end-to-end, not per socket operation

JsonRpc.call treated its timeout as a wall-clock bound — lease
authority margins are sized from it as the longest a fence-guarded
effect can run — but http.client applies it per socket operation. A
response body arriving one packet per interval keeps every recv inside
the socket timeout while the call runs arbitrarily long, so a guarded
submitblock or CTV broadcast could outlive the runway the margin
promised and keep running while a rolled-back own write hands the
expired lease to a queued claimant.

Arm a watchdog timer per attempt that severs the socket at the
attempt's remaining deadline; the blocked operation surfaces as
TimeoutError. For mutating calls this is the same uncertain outcome an
ordinary socket timeout already produces, reconciled by durable replay
as a new fully fenced operation, and transport-retryable reads skip
their retry once the wall clock is spent.

Reported by chatgpt-codex-connector on PR #116.

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

* Verify the lease at the submitblock RPC boundary, not before the lock

The fenced submitblock lane verified the lease and then waited on
_payout_append_landing_fence_lock before entering the RPC. A predating
append_batch holds that lock across its ledger commit and epoch bump —
under the same database saturation that erodes the lease TTL, far
longer than any scheduling headroom — so the runway the verification
proved could be consumed by the lock wait, re-opening
authorize-then-expire on exactly the path the authority margin closed.

Move the verification (and its deferral unwind of the landed payout
bar) into a closure invoked at the RPC boundary in both lanes: directly
before the unfenced submit, and inside the landing fence lock after the
epoch check passes. The verification runs on the guard session and
never touches the landing lock, so ordering is deadlock-free, and a
deferral raised under the lock releases it on propagation as before.

Reported by cursor[bot] on PR #116.

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

* Keep severing until the RPC attempt observes its deadline abort

The end-to-end deadline watchdog fired once and severed whatever socket
existed at that moment. A stalled name resolution has no socket yet, so
the one-shot sever closed an empty connection and the socket connect()
created afterwards carried the mutating RPC onward, unbounded — while
the lease authority margin relies on the timeout as a hard wall-clock
cap on fence-guarded effects.

Replace the one-shot timer with a watchdog that, once the deadline
passes, severs the connection's current socket repeatedly until the
attempt observes the abort as a transport error, so a socket created
after the stall dies within the next sweep. Covered by tests for both
the slow-dripping body and the socket-created-after-stall shapes.

Reported by chatgpt-codex-connector on PR #116.

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

* Recheck the deadline after connect so a late resolution never sends

The watchdog's periodic sweep bounds an established connection, but a
name resolution returning after the deadline resumed straight into
sendall() from conn.request()'s implicit connect — a short mutating
POST could reach qbitd between sweeps, after the lease runway the
authority margin promised had expired.

Establish the connection explicitly under the watchdog and re-check the
deadline before any request byte is sent, so the late-connect case
loses deterministically instead of racing the sweep. The stall test now
models the real shape — the stall inside connect() — and asserts the
request is never sent.

Reported by chatgpt-codex-connector on PR #116.

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

* Give the slow-body deadline test a socket the watchdog can sever

The fake connection's sock was a bare object, so the watchdog's
sock.shutdown() died with AttributeError — outside its OSError guard —
before reaching close(), and the test passed only through the response
fake's five-second backstop without ever exercising the sever. Model
the socket with a shutdown() that flags the sever, and assert both the
flag and that the call finished near the 0.3s watchdog allowance rather
than the backstop.

Reported by chatgpt-codex-connector on PR #116.

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

* Reject authority margins that reach the lease TTL at construction

A margin at or above the TTL was accepted and documented as the honest
defer-every-skip consequence of guarded effects that can outlast the
lease. That reasoning was incomplete: the deferral only gates renewal
skips, while a verification over an uncontended row renews and
authorizes unconditionally — and a landed renewal's runway is exactly
one TTL. With the guarded RPC deadline at or past the TTL, the fence
could authorize an effect that outlives even a freshly renewed lease;
an own fenced write outlasting the TTL and rolling back then hands the
row to a queued claimant while the still-authorized RPC runs. No
deferral policy closes that window — the configuration itself is
unsafe.

Fail construction when the resolved margin reaches the TTL, converting
a silent split-brain hazard (a short PRISM_LEDGER_LEASE_TTL_SECONDS or
a raised guarded-RPC deadline) into a startup error that says to raise
the lease TTL or lower the guarded RPC deadlines. Default configuration
is unaffected (margin 30s against a 60s TTL).

Reported by chatgpt-codex-connector on PR #116.

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

* Pass lease deferrals through the CTV broadcaster untouched

CtvFanoutBroadcaster._submit converted every exception into an error
BroadcastAttempt, so a WriterLeaseRenewalDeferred raised by the lease
fence — a preflight refusal fired before any RPC ran — was journaled as
a failed attempt and pushed the payout behind the persistent 300-second
retry backoff. The deferral is transient by design: the coordinator's
broadcaster loop retries on its ordinary pass interval once the
deferring write commits and a renewal lands.

Move WriterLeaseRenewalDeferred into share_ledger (with the lease
machinery; prism_coordinator re-exports it, so existing importers are
unchanged) so the broadcaster can name it without an import cycle, pass
it through _submit's generic conversion, and catch it calmly in
ctv_fanout_broadcaster_loop — one withheld-pass line instead of a
failure traceback, then the normal interval retry. The daemon journals
nothing for a deferred pass because the refusal propagates before any
attempt exists.

Reported by chatgpt-codex-connector on PR #116.

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

* Count the recheck's first round trip as heartbeat monitor progress

The heartbeat monitor's failure budget must stay under the adoption
silence, so it is sized for one statement — but the verification may
lawfully run two inside its guarded slot. Two individually in-deadline
statements aged the last success past the budget and the monitor
hard-exited a healthy coordinator midway through the attribution
recheck it was entitled to run. Raising the budget is not an option:
the monitor must kill a wedged heartbeat before its session becomes
fast-adoptable.

Let the verification report per-statement progress instead: when the
recheck decides to run its second statement, the first statement's full
round trip has completed — the same session-answers evidence a success
proves. The heartbeat loop passes a callback that stamps a progress
mark, and the monitor ages from the freshest of success and progress.
The mark is deliberately separate from the success timestamp, so
nothing that treats success as authorization freshness can observe a
verification that has not reached its verdict, and a genuinely wedged
statement — which reports no progress — still ages out unimpeded
(verified by the existing stalled-heartbeat test and a new
two-statement test whose no-progress variant hard-exits).

Reported by chatgpt-codex-connector on PR #116.

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

* Enforce the RPC deadline exactly so no byte outlives an abandoned call

The deadline watchdog allowed remaining + 0.1s before severing, and the
pre-send recheck consulted only the watchdog flag. Callers like the
submitblock hard-deadline wrapper abandon the call and raise at exactly
their configured deadline — propagating out of the payout landing fence
lock and releasing it — so a connect resuming inside the grace window
could still transmit the block with watchdog_fired unset. A
late-visible share append could then advance the payout epoch after the
fence released and before qbitd received the candidate, landing an
accepted block whose payout window omitted that share.

Sever at the attempt's exact remaining wall clock, and gate the
pre-send recheck on the deadline itself as well as the watchdog flag,
so a send can never start at or after the moment a caller may have
released ordering locks — independent of watchdog thread scheduling.

Reported by chatgpt-codex-connector on PR #116.

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

* Document what the authority margin can and cannot bound server-side

The margin's docstrings claimed every authorized effect completes
within the committed row's remaining validity, but the client-side
deadline only bounds transmission: severing the socket cannot cancel a
handler qbitd already received in full, so the node can apply a
mutating request shortly after the client gave up on it. State the
contract precisely — the headroom absorbs the node's application tail
after complete receipt (these handlers apply within milliseconds), and
a node stalled longer than the headroom after full receipt is the
documented residual of preflight fencing between independent systems,
which no client-side teardown can bound and only node-side fencing
could close.

Reported by chatgpt-codex-connector on PR #116.

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

* Disable auto_open so a severed connection cannot resurrect itself

http.client's auto_open lets request() silently re-open a connection
whose socket was cleared. When the deadline watchdog's close() landed
between the pre-send deadline check and the send, request() would
reconnect implicitly — a fresh socket the explicit connect() check
never saw, alive until the next watchdog sweep — and a short mutating
POST could reach qbitd after the submitblock caller had already
released the payout landing fence or the lease runway had expired.

Construct every connection with auto_open disabled: a cleared socket
now makes send() raise NotConnected (mapped to the timeout by the
fired-watchdog handling), and the only way a connection opens is
call()'s explicit connect under the watchdog followed by the wall-clock
deadline recheck before the first byte.

Reported by chatgpt-codex-connector on PR #116.

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

* Feed the monitor recheck progress from the external fence too

The heartbeat loop learned to report the attribution recheck's
completed first round trip as monitor progress, but the verification
has a second caller: the external side-effect fence. Its verification
holds the guard's serialized slot for the whole statement sequence, so
the periodic heartbeat queues behind it and records nothing meanwhile —
and the fence stamps success only at completion. A fence verification
lawfully running two in-deadline statements therefore aged the
heartbeat's last success past the single-statement failure budget and
the monitor hard-exited a healthy coordinator, in exactly the path that
runs before every submitblock and broadcast, under exactly the
in-flight-write conditions that trigger the recheck.

Pass the same monitor-progress callback from the fence's verification
thread, gated on signature inspection like on_query_start, so both
callers of the verification feed the monitor identically.

Reported by chatgpt-codex-connector on PR #116.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants