Skip to content

Extend the deterministic concurrency harness to block candidate landing - #148

Merged
kiwidream merged 4 commits into
2.x.xfrom
extend-concurrency-harness-to-landing
Aug 19, 2026
Merged

kiwidream merged 4 commits into
2.x.xfrom
extend-concurrency-harness-to-landing

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Extends the deterministic concurrency harness to block candidate landing,
the state machine #128 ranks first by incident history. Continues #139, which
landed the harness core plus the writer-lease lifecycle.

Landing is the one PRISM owner where two threads of the same process reach
the same durable rows, and a found block is real money. The acceptance
criterion set in #128's status comment is #133's two-distinct-hash
interleaving; this PR drives it end to end. #125's escalated-budget-versus-
watchdog interleaving is covered alongside it. Both defects are already fixed
on 2.x.x (03e733e, 49f04c3), so the scenarios pass — the evidence is
that the interleavings can be expressed at all, which nothing could do
before, and both fixes now have regression cover beyond what their own PRs
added.

What the model learned

The rows landing turns on. qbit_pool_blocks and
qbit_block_candidate_outbox, the qbit_confirm_pool_block publication-
ordinal allocator, and the durable floor read.

The allocator is modelled on the shipped PL/pgSQL rather than on an
approximation of it, and the difference is load-bearing. The ordinal comes
from a sequence, not from MAX + 1: an exact replay of an already-
confirmed row matches zero rows and burns nothing, a terminally disposed row
reports the superseded disposition (-1) rather than a plain miss, and an
aborted confirmation burns its value and leaves a gap that the separate
MAX-based floor tolerates. That separation between "which ordinal did I get"
and "how high is the floor now" is exactly what lets a later ordinal publish
first and strand an earlier one behind the floor — the state #133 turns on. A
model that collapsed them could not have hosted the defect.

Landing writes are staged per transaction for the same reason lease writes
already were: a deadline-scoped statement sends COMMIT as a separate client
message, and the interesting window is inside it.

Classification stays anchored on production SQL. Every landing signature
is lifted verbatim from lab/prism/share_ledger.py, as the lease signatures
already are, so a change to that SQL breaks classification loudly rather than
quietly changing what the fake models. Where a modelled statement is a large
CTE — persist_accepted_block writes pool-block, bundle, payout-entry and
carry-forward rows in one statement — the model reproduces the effects a
landing reads back and says so in place, naming the fragment set as the point
of extension.

Three new primitives

Scheduler-aware locks, conditions, semaphores and events. The lease
scenarios never needed these: they interleave two processes around one row,
so no two actors ever contended a lock inside one coordinator. The landing
tails share the payout-balance serializer, the publication order guard, the
ledger's writer lock and read slots, and the accepted-share-stats
single-flight. A real mutex would block an actor outside the baton and the
controller would report a stall on a wait that is in fact legitimate; these
park the waiter at a named checkpoint instead, which makes a contended
process-local lock an interleaving point rather than a harness limit.

Semantics are preserved exactly — a mutex stays a mutex, FIFO grants, a
re-entrant lock stays re-entrant, timed waits measure the virtual clock — and
only the blocking mechanism changes. Notably, a non-reentrant lock re-acquired
by its owner raises rather than succeeding, because a real mutex would
deadlock there and hiding that would hide a production deadlock.

Phase breakpoints. For the lease lifecycle, every state transition is a
statement, so statement boundaries were enough. Landing is not like that: the
confirm→publish window is bounded on one side by a durable confirmation and on
the other by a lock the publish step has not taken yet, and no statement runs
at the instant that matters
. The landing already names those boundaries for
its own watchdog, so a scenario stops a tail at progress:evidence-write — the
top of the publish step, in the code's own words — instead of counting
statements and hoping the count survives a refactor.

HarnessBase. #128 names four owners and this is the second, so the
boundary is worth drawing properly. The clock, the scheduler, the PostgreSQL
model, the stepping vocabulary and the output capture are the same for landing
as for the lease lifecycle and will be the same again for tip refresh and share
submission; only what a harness builds differs. run_scenario and
assert_deterministic are now generic over HarnessBase rather than typed to
LeaseHarness, so the two remaining owners plug in without the determinism
check being re-derived per state machine. stdout and stderr are captured
separately, because which stream a diagnostic arrives on is itself an
assertion a scenario may want to make.

What is real and what is modelled

Real: BlockCandidateService, BlockFinalizationService,
AuditArtifactStore over a genuine audit root, PsqlShareLedger emitting its
shipped SQL, and the coordinator's own landing arithmetic — budgets, watchdog
ceiling, epoch fences, publication-ordinal handling.

The audit root is a real directory on purpose: what #133 loses is a file that
is never written, and no in-memory double can fail to write it.

Two model boundaries are stated rather than implied, both for the same reason —
a baton scheduler cannot schedule a thread the code under test spawns with no
factory seam, and a thread running unscheduled would take its statements
outside the schedule the harness exists to control:

  • The bounded outbox worker. Landing-class ledger steps already run inline
    on the block-work thread in production and arrive unchanged. The outbox
    marks run on a spawned worker so a misbehaving driver cannot wedge the
    submitter. The harness runs the operation inline, keeping the operation, its
    budget scope, its error propagation and its per-class latency metric, and
    dropping only the liveness wrapper. Cost: this harness cannot express a
    stuck outbox driver, so the restart escalations stay example-covered in the
    block-candidate suite.
  • The external-side-effect lease fence. Both gates it guards are kept,
    including the fresh-lease proof that authorizes a superseded-envelope
    restore, and so is the real verification statement behind them. Out of reach:
    the fence's timeout arm.

Adding either would need a thread-factory seam in production, which belongs to
whichever issue wants that interleaving rather than being smuggled in here.

Scenarios

tests/test_prism_landing_interleavings.py — #133. Block A confirms on the
synchronous client-thread tail and stops at the top of its publish step; block
B, its child, lands entirely on the accounting actor inside that window,
confirms the next ordinal and publishes; A then publishes at sequence 1 against
a floor of 2. The assertion is that A's live envelope — its only published
evidence pointer — is on disk. Before 03e733e that file was silently absent.

The suite also pins the claim the whole scenario rests on (the per-hash
disposition lease does not serialise distinct hashes — if it did, the case
would be unreachable and the other tests would prove nothing), that the
superseded write is reported rather than silent, and that withholding restore
authority degrades to the pre-fix behaviour rather than failing a found-block
landing.

tests/test_prism_landing_budget_watchdog.py — #125. The admission wait
heartbeats in slices without lengthening, and no single landing step's
admission-plus-statement budget can outrun the watchdog tolerance.

tests/test_prism_landing_harness_model.py — the model's own contract:
allocator semantics against the shipped PL/pgSQL, transaction-scoped
visibility, classification and the deposed-writer fence, and the new
synchronisation primitives.

The hypothesis decision: not adopted

#128 deferred this to the landing PR, and the reasoning it recorded was that
the lease defects were schedule-interleavings where in-house enumeration beat
RuleBasedStateMachine, while the combinatorial landing space is where that
calculus might flip. Having built the landing model, it does not flip. Three
reasons, in order of weight:

The defects here are still schedule-shaped, not data-shaped. #133 is not
"some sequence of operations violates an invariant"; it is "two specific tails
must be at two specific points at the same time". hypothesis generates
inputs; the input space that matters here is the space of interleavings, and
RuleBasedStateMachine cannot address it — under this harness only the
controlling test can say who runs next, so a generated rule sequence would
still be executing one schedule per run and shrinking over the wrong axis.

The oracle is the expensive part, and generation does not supply it. The
interesting assertion in #133 is "a file exists that no error would have told
you about". Property-based testing pays off when a cheap invariant covers a
wide input space; here the invariant is narrow and specific and the cost is
almost entirely in reaching the state, not in checking it.

A new dependency needs to earn its place. hypothesis is not currently a
dependency of this repository. Adding one to the test path of a pool that
settles real money is a supply-chain and CI-reproducibility decision, and
non-determinism is the specific hazard this harness exists to remove — a
flaky concurrency test is worse than none.

Where it would pay: share submission and dedupe, #128's fourth owner.
That one is genuinely data-shaped — acceptance ordering, duplicate
classification, window boundaries over generated share streams — and its state
machine is the simplest. If hypothesis enters this repository, that is the
PR where the case should be made, on its own evidence.

Determinism

Every scenario is proved order-stable with assert_deterministic: 25 runs, and
both the full checkpoint trace and the outcome digest must match. The trace is
the stronger half — two runs can agree on the answer while disagreeing about
the schedule that produced it, and that is exactly the flakiness this harness
exists to rule out.

Verification

Block candidate, block finalization, share ledger, audit artifacts, harness and
lease suites: 535 tests, all passing.

Full CI-equivalent run in Docker (python -m compileall over
docker lab tests examples scripts, then unittest discover): compileall
clean; the discovered-suite failure set is byte-identical to origin/2.x.x
in the same container (42 pre-existing failures that need a live PostgreSQL
service). This branch adds 5 tests and no new failures.

Deferred

Still owed to #128, unchanged in priority: tip refresh and job delivery,
and share submission and dedupe. Both plug into HarnessBase without
touching the determinism check.

#126 — the global append epoch over-abandoning a never-offered candidate — is
the immediate follow-up. Its interleaving is already reproducible against this
harness, and the fix plus its regression scenario ship in a stacked PR.

Refs #128, #133, #125.


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

Issue #128 ranks block candidate landing first by incident history, and
the harness landed by #139 covered only the writer-lease lifecycle. This
teaches it the landing state machine, which is the one owner where two
threads of the same process reach the same durable rows.

The PostgreSQL model gains the rows landing turns on: qbit_pool_blocks,
qbit_block_candidate_outbox, the qbit_confirm_pool_block publication
ordinal allocator and the durable floor read. The allocator is modelled
on the shipped PL/pgSQL rather than on an approximation of it: the
ordinal comes from a sequence, so an exact replay of an already-confirmed
row burns nothing, a terminally disposed row reports the superseded
disposition, and an aborted confirmation leaves a gap the MAX-based floor
tolerates. That distinction is the whole of the two-tail defect -- a
later ordinal can publish first and leave an earlier one behind the
floor. Landing writes are staged per transaction for the same reason
lease writes already were: a deadline-scoped statement sends COMMIT as a
separate message, and the interesting window is inside it.

Statement classification is anchored on fragments lifted verbatim from
the production SQL, as the lease signatures already are, so a change to
that SQL breaks classification loudly instead of quietly changing what
the fake models. Where a modelled statement is a large CTE, the model
reproduces the effects a landing reads back and says so.

Three new pieces support the topology. Scheduler-aware locks, conditions,
semaphores and events make a contended process-local lock an interleaving
point rather than a wedged baton -- the lease scenarios never needed
them, because they interleave two processes around one row, while the two
landing tails share the payout-balance serializer, the publication order
guard and the ledger's admission gates. Phase breakpoints let a scenario
stop a tail at a boundary the landing already names for its own watchdog,
because landing's interesting windows are the gaps between statements and
no statement runs at the instant that matters. And HarnessBase now holds
what every state machine's harness owns, so run_scenario and
assert_deterministic are generic over it rather than typed to one
harness; the two owners still owed to #128 plug in without touching the
determinism check again.

The acceptance criterion is #133's two-distinct-hash interleaving, driven
end to end: block A confirms on the synchronous client-thread tail, block
B lands on the accounting actor inside A's confirm-to-publish window and
publishes the next ordinal, and A then publishes behind the raised floor.
It is already fixed here, so the scenario passes; the evidence is that
the interleaving can be expressed at all, which nothing could do before.
The suite also pins the load-bearing claim underneath it -- the per-hash
disposition lease does not serialise distinct hashes -- and the fresh
lease proof that gates the superseded-envelope restore.

Every scenario is proved order-stable over 25 runs of the full checkpoint
trace.

Refs #128, #133.
@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 and others added 2 commits August 19, 2026 12:44
Issue #125: a landing-class ledger step is two waits, not one. The caller
queues for the ledger writer lock -- local, unbounded by any statement
deadline -- and only then runs the statement it queued for, under its own
full budget. Both are spent on the block-work thread the watchdog monitors,
and before 49f04c3 both were heartbeat-silent, so an escalated landing at
the reviewed 120s cap could hold the heartbeat still for ~240s against a
120s tolerance. The watchdog hard-exited mid-landing and the in-memory
escalation counter died with the process, so the restart came back at the
30s base to repeat the cycle.

Add landing-harness scenarios for both halves of the fix:

- a real accounting tail queued behind a held writer lock stamps
  wait-ledger-admission:landing every slice instead of going quiet, and an
  A/B against the same gate at the same budget with no progress hook shows
  slicing changes nothing about when the wait ends;
- the escalation ladder is climbed by genuinely timed-out landings and
  every rung's admission-plus-statement pair fits the watchdog tolerance,
  across a clamped cap, a clamped base and a configuration needing no
  clamp at all, with the clamp reported exactly once;
- both composed: a landing that queues for all but one slice of its
  escalated budget still lands, inside the tolerance, with no silence
  longer than one slice.

Every scenario is proved order-stable with assert_deterministic.

Co-Authored-By: Claude Opus 5 <[email protected]>
The lease half of the deterministic harness is defended by
tests/test_prism_concurrency_harness.py; the landing half added in
cefdbfa was not. A fake that answers an unrecognised statement
plausibly drifts away from production silently, and every scenario
built on it inherits the drift, so a landing scenario that failed
could not distinguish "the code under test is wrong" from "the model
is wrong".

tests/test_prism_landing_harness_model.py pins the model's own
contract in four parts:

- The publication-ordinal allocator against qbit_confirm_pool_block:
  a fresh confirmation takes the next sequence value, an exact replay
  returns 1 without burning one (proved by the next block's ordinal),
  every terminal disposition reports -1 rather than 0, a height
  mismatch and a missing row both report 0, and the durable floor —
  a MAX over the table — stays put across the gap an aborted
  confirmation leaves behind.

- Transaction scope: a deadline-scoped landing write is invisible to
  another session until COMMIT and visible to its own before it, and
  a rolled-back landing leaves no row while keeping its ordinal burned.

- Classification: every LandingOp is driven through the shipped
  PsqlShareLedger method that emits it, a landing table mention that
  matches no signature raises naming _LANDING_SIGNATURES, the deferred
  markers still name their follow-up state machine, and a deposed
  writer fails the lease CTE in the two shapes the SQL dictates — the
  outbox statements report it, the PL/pgSQL functions raise.

- The synchronisation primitives: mutual exclusion and FIFO grants,
  non-blocking and virtual-clock-timed acquires, the non-reentrant
  re-acquire that a real mutex would deadlock on, RLock depth, the
  condition's release/re-acquire and restored depth, semaphore
  exhaustion and over-release, and the event's parked and timed waits.

One landing scenario is proved order-stable with assert_deterministic
against LandingHarness. Nothing sleeps in wall-clock time.

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

This comment has been minimized.

The retention test captured time.monotonic() and asserted that a silent
reconnect cycle at exactly +TTL still resumes, relying on the store's
strictly-greater expiry comparison. That boundary arithmetic is not
exact for an arbitrary float base: (start + 900.0) - start rounds above
900.0 for roughly one in five thousand captured clock values, which
flips the boundary cycle to expired and fails the test. CI hit this on
the push run for the map commit while the pull_request run of the same
commit passed.

Every record and lookup in the test runs under frozen_clock, so the
base never needs to be a real monotonic reading. Pin it to an
exactly-representable constant, making the boundary arithmetic exact.

Refs #145.
@kiwidream
kiwidream merged commit 413f51e into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the extend-concurrency-harness-to-landing branch August 19, 2026 19:01
kiwidream added a commit that referenced this pull request Aug 19, 2026
The harness PR (#148) was squash-merged, so 2.x.x carries
tests/prism_landing_harness.py under a commit unrelated to this branch's
history. The merge base therefore predates the file on both sides and git
reports an add/add conflict for it.

Resolved in favour of this branch: 2.x.x's copy is byte-identical to this
branch's pre-change version of the file, and this branch's copy is that
same file plus the additive accepted_at_ms kwarg the straddling-row tests
need. Nothing from 2.x.x is dropped.

Everything else auto-merged; the regions are disjoint. Verified both sides
survived: this branch's anchor-set comment and the per-anchor fences in
block_finalization.py, and 2.x.x's idempotent-confirm-replay handling from
#146.
kiwidream added a commit that referenced this pull request Sep 11, 2026