Skip to content

Make writer-lease heartbeat tolerate verification tail latency - #214

Merged
kiwidream merged 2 commits into
2.x.xfrom
fix-prism-writer-lease-tail-latency
Aug 31, 2026
Merged

kiwidream merged 2 commits into
2.x.xfrom
fix-prism-writer-lease-tail-latency

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes #212.

What changed

  • Treats adoption silence, heartbeat cadence, failure budget, monitor cadence, exit margin, guard statement timeout, and scheduler slack as one validated policy.
  • Raises the default adoption silence from 1s to 2s and derives a 1.30s server-proven cap that covers the 1.25s healthy worst-case gap while preserving exit-before-adoption.
  • Splits frequent read-only exact-session ownership proof from less-frequent TTL renewal, escalating to renewal on the same beat when due.
  • Attributes guard-slot wait, guard SQL, scheduler delay, outcomes, server-proven age, monitor wake delay, and policy headroom with fixed-cardinality metrics and actionable exit details.
  • Adds deterministic production-shaped concurrency coverage for rapid work, slow SQL, contention, external fences, guard loss, wedged proof, and scheduler stalls.
  • Reserves the monitor thread's own scheduler slack in the exit envelope. The corrected worst-case bound is 1.30 + 0.05 + 0.50 + 0.10 = 1.95s, strictly before the 2.00s successor eligibility edge.

Verification

  • 349 focused lease/share-ledger/metrics tests pass independently.
  • Worker full suite: 2,952 tests; only the same 2 failures and 12 errors reproduced on the pristine base (macOS os.splice and git-fixture subprocess behavior).
  • compileall passes across lab, tests, examples, and scripts.
  • Every shell script passes bash syntax validation.
  • Commit signature verified.

Rollout gates

The issue's production-only acceptance items are intentionally not claimed by this PR run: complete a 30-minute production-shaped soak and testnet burst/chaos validation before mainnet rollout.


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

…212)

union-mainnet accumulated 69 coordinator restarts during one rapid-block
burst while PostgreSQL, qbitd, storage, CPU and memory were healthy and the
coordinator still held its writer advisory guard. The exits were genuine
protective exits: the heartbeat's server-proven envelope had elapsed. It had
elapsed because the envelope was derived from the adoption silence alone
(silence/4, silence*0.75) and so covered a heartbeat's idle interval but not
the tail of a lawful verification. Representative exits reported activity
ages of 0.54-0.78s against a 0.75s budget and server-proven ages of
0.76-0.91s against a 0.80s cap.

Four changes, none of which weakens fencing.

State the timing as one inequality. lab/prism/writer_lease_timing.py owns the
adoption silence, heartbeat interval, failure budget, monitor interval and
exit margin as a single WriterLeaseHeartbeatPolicy, derived from measurable
phase budgets: the guard session's own 0.5s statement_timeout, the 0.25s
heartbeat interval, and a 0.5s process scheduler-slack allowance. The largest
gap a healthy coordinator can leave between completed guard round trips is
their sum, 1.25s, which is both the failure budget and the floor for the
staleness cap.

The exit envelope that must sit between that cap and the adoption silence
reserves the monitor thread's own lateness, not merely its poll granularity:
exit_margin + 2 x monitor_interval + scheduler_slack = 0.70s. The monitor is a
Python thread in the same process, behind the same GIL, as the heartbeat whose
stalls this policy explicitly budgets for, so it cannot be assumed to wake on
time when the heartbeat does not. Reserving only the poll intervals leaves a
real split-brain window: at the shipped budgets a maximally late monitor
observes the stale edge and finishes its exit 2.449s after the last provable
instant, while a successor becomes adoption-eligible at 2.0s. With the
scheduler slack reserved the same worst case completes at 1.95s, one monitor
poll clear of the adoption edge, and the second monitor_interval term is what
makes that strict rather than exactly equal.

The adoption silence must therefore exceed 1.25 + 0.70 = 1.95s, and ships at
2.0s - unchanged, because it was already large enough for the corrected
envelope; the staleness cap tightens from 1.80s to 1.30s and the stability
surplus to 0.05s. Failover costs 2.0s of silence rather than 1.0s - half the
temporary downstream 4.0s pin, and derived rather than dialled in.
coordinator_config reads these values from the policy instead of re-deriving
them, the process scheduler slack is resolved through the same port pattern as
every other term so a scaled deployment or test policy validates what it
actually runs, and the policy validates itself at import.

Reject unsafe policies at startup. A combination that cannot guarantee hard
exit before replacement adoption now hard-exits with the failing term named,
before either thread is armed, instead of printing a warning and running with
no exit-before-adoption guarantee. A combination that is safe but leaves the
cap below the healthy-gap bound - which cannot produce two writers, only
avoidable restarts - still warns and starts.

Separate frequent ownership proof from TTL renewal.
prove_writer_lease_guard_session asks only the ownership question, on one
non-blocking statement with no row lock and no pg_stat_activity scan: the
same two conditions the full verification raises on, so the exact-session
guarantee is unchanged. Renewal is preserved by escalation, not by dropping
it: the proof reports the committed row's TTL, and the heartbeat runs the
full renewing verification on the first beat and on any beat whose proof
reports the row inside the own-write authority margin (>= half the TTL),
escalating within that same beat. Renewal is therefore never later than
before, and throughout a long own fenced write - when renewals are actually
being skipped - every beat runs the same fail-closed verification as before.
Adoption safety is unaffected because the successor's silence is gated by the
later of the row edge and its own guard-acquisition edge, and the guard edge
is a full silence from acquisition regardless of how stale the row looks.

Attribute the phases. Every attempt records guard-slot wait, guard SQL across
its round trips, scheduler delay, statement count, mode and outcome; the
monitor also records its own worst wake delay. Hard exits now name which bound
tripped, the last and worst attempts' phase breakdowns, the monitor's
lateness, and every term of the policy. The same data is exported with fixed
label vocabularies (28 series, closed sets for modes, outcomes, phases and
policy terms). Server-proven stamps also move to the conservative send edge of
each round trip rather than its receipt time, so scheduler delay after a
response can no longer make the session look fresher than PostgreSQL proved.

Testing extends the #128 deterministic harness rather than adding a framework:
it models the read-only proof statement, per-statement server time bounded by
the guard's statement_timeout, and the per-round-trip callback. The real
heartbeat and monitor loops run as harness actors on the virtual clock, so a
production-shaped burst - near-bound guard statements, repeated scheduler
stalls, a fenced write holding the lease tuple, and fence callers competing
for the guard slot - is deterministic and instant. It reaches a peak
server-proven age above the pre-#212 cap with no exit, while injected guard
loss, a wedged proof and a cancelled guarded statement each end this
coordinator's authority before any successor can take the guard. Two further
scenarios drive the combined worst case the envelope is sized for - authority
gone, the heartbeat thread descheduled entirely, and the monitor waking a full
monitor_interval + scheduler_slack late on a poll phase chosen so the bound
elapses immediately after a poll - and assert the exit completes, exit margin
included, before the successor's measured guard-acquisition edge plus the
silence. Both fail with the unreserved envelope at exactly the 2.449s vs 2.0s
breach above.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01GX1dKh4fGhRhqf5jyuHRWE
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-31T17:08:42.686877Z df2ab9d Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 297bda7902

ℹ️ 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/writer_lease_timing.py Resolved
@kiwidream

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: df2ab9d5d3

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant