Skip to content

3.x.x: cut the share append's ORDER_LOCK hold from nine client round trips to four (#711) - #719

Merged
RobertClarke merged 3 commits into
3.x.xfrom
RobertClarke/711-append-round-trips
Oct 6, 2026
Merged

RobertClarke merged 3 commits into
3.x.xfrom
RobertClarke/711-append-round-trips

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Refs #711.

A share append held ORDER_LOCK, the cluster-wide advisory lock every share serializes on, across nine client round trips. On the pair's frontend, which reaches PostgreSQL through the docker bridge, haproxy and verify-full TLS, each round trip is expensive. The hold, mostly client wait, set the ceiling that missed the D1 peak gate (window p99 1,116 ms against 1,000 ms through the real frontends). This PR cuts the in-lock round trips from nine to four without a migration.

The statements under the lock

Before, a new share sent nine round trips after its pg_advisory_xact_lock, ending with COMMIT:

  1. writable: the write guard's read of the cluster row.
  2. The payout-revision fence, SELECT payout_revision … FOR SHARE.
  3. The probe's bounds and the header lookup (credited share_id, retained rejected sequence, conversion_bound, floor, ceiling).
  4. The bounded share_id probe between floor and ceiling.
  5. The fallback probe: the legacy range for a new header.
  6. The ledger clock UPDATE.
  7. The INSERT into the share ledger.
  8. The INSERT into the header mappings.
  9. COMMIT.

After, it sends four, ending with COMMIT:

  1. One read. The write guard's columns, the cluster row's payout_revision, and the bounds/header statement, unchanged as a MATERIALIZED CTE on the outer side of a LEFT JOIN, all in one SELECT. A fenced append reads it FOR SHARE OF c; an unfenced one takes no lock, as before. check_writable runs on the row first, so a halted cluster or a live legacy writer is still refused before the revision is compared.
  2. One probe. For a new header, the bounded probe is a MATERIALIZED CTE (recent), and the fallback the first read chose is a UNION ALL branch: the retained rejected sequence, or the legacy range. It is gated by NOT EXISTS (SELECT 1 FROM recent), a one-time filter, so the fallback runs only when the bounded probe found nothing, exactly as before. Both branches keep their bounds as parameters. A credited header (a duplicate) runs the bounded probe alone. Its full-parent fallback stays a statement of its own, run only on a bounded miss: nothing bounds that fallback, so executor startup would otherwise open every retained leaf on every duplicate.
  3. One write. The clock UPDATE, the ledger INSERT and the header-mapping INSERT run as data-modifying CTEs in one statement. The clock is the same GREATEST, and accepted_at is the same to_timestamp of it. The "job from the future" check moved into the INSERT's WHERE: such a share inserts nothing and gets a NULL share_seq back, and the caller refuses it with the same error. The transaction's rollback then undoes the clock bump, as it did when the check ran between two statements.
  4. COMMIT.

A duplicate found in the recent leaves now takes two statements and COMMIT, down from four (writable, fence, bounds, probe) and COMMIT. The statement texts are built once (LazyLock), not formatted per share inside the lock.

Why the lock stays its own statement

The lock statement is not merged into the first read. Under READ COMMITTED, a statement's snapshot is taken when the statement starts. Reads in the same statement as pg_advisory_xact_lock would use a snapshot from before the lock was granted, and would miss the share the previous holder just committed. The first read is the first statement after the lock, so it sees every commit made under the lock before it.

BEGIN; SET LOCAL plan_cache_mode = force_generic_plan is unchanged. So are #482's cancel handling, the prepared-candidate and #657 capture paths and their order, the commit gate before COMMIT, the OrderHold metrics, and the 23514 missing-partition retry. The settlement's deferred-share credit still calls append_in inside its own transaction; there the bounds statement runs on its own, followed by the new probe and write. The capture path's recorded probe still calls qbit_prism_share_probe_floor() in its WHERE clause. Binding the bounds the first read now returns would help that rare path, but it is a change to the capture path, which this PR leaves alone.

What the merged statements could change, and why they don't

  • Triggers and foreign keys. No trigger fires on an INSERT into qbit_share_ledger or qbit_prism_share_hashes. The share ledger's statement trigger covers UPDATE, DELETE and TRUNCATE only. The cluster row's only trigger is BEFORE UPDATE OF fatal_error, which the clock UPDATE never sets. qbit_prism_share_hashes has had no foreign key since migration 016 dropped it. The data-modifying CTEs therefore write the same rows with nothing observing a shared snapshot.
  • The fence. FOR SHARE OF c still waits out a writer holding the cluster row, then rechecks against the row that writer committed, so the revision compared is the latest. The bounds CTE is materialized, so the recheck involves the cluster row alone. The other columns keep the statement's snapshot, taken before that wait. The separate bounds statement used to take a fresh one after the fence. So the read also returns probe_current: the returned cluster row's xmin compared with the snapshot's own read of the row, an InitPlan the recheck does not re-run. When a writer committed to the row while the read waited and left the revision alone, the append reads the bounds and header again in a statement of its own before probing. A revision change is refused or captured as before, without the re-read. A test drives this path with a writer that also maps the share's header.
  • A halted cluster. If a writer sets fatal_error while the fenced read waits, the append is now refused with "cluster halted: …". Before, the fence's fatal_error IS NULL filter returned no row, and the append failed with sqlx's RowNotFound. Either way the append is refused.

Pruning, proved on the new statement

the_append_probe_is_pruned_to_the_leaves_between_the_floor_and_the_sequence now reads the probe's EXPLAIN (FORMAT JSON) and splits the plan at the CTE recent subplan. Under the forced generic plan, the bounded probe still has its partitions removed at executor startup: 4 of 4 above the sequence with the sequence in p0, and at least all but p1..p3 once it has moved to p3. A new header's legacy fallback is pruned the same way, down to the release partition p0 alone, by both the custom and the generic plan. The inlined floor and ceiling are still checked against migration 016's functions, now read by column name through the append's own prepared first statement.

Tests

  • append_admission:
    • a_share_append_holds_order_lock_for_three_statements_and_its_commit uses the wire-level ExecutionProxy to pin exactly three statements and COMMIT under ORDER_LOCK for a new share, fenced and unfenced, and two for a duplicate. Round trips can't creep back unnoticed.
    • a_share_from_a_future_job_is_refused_and_its_write_rolls_back checks that the refused share leaves the ledger clock, the sequence and the mappings exactly as they were. There was no test of this refusal before.
    • a_halted_cluster_or_a_live_legacy_writer_refuses_the_append_before_its_fence covers both, fenced and unfenced, with a stale expected revision so that a fence-first order would answer differently.
    • a_fenced_append_waits_out_a_revision_writer_and_compares_what_it_commits holds an uncommitted revision UPDATE on the cluster row while the append's first statement waits on it. A committed writer gets the append refused as "payout revision changed"; a rolled-back one lets the share land.
    • a_fenced_append_rereads_its_probe_after_waiting_on_a_cluster_row_writer uses a writer that touches the cluster row and also maps the share's header to another share. The append waits on it, rereads its probe, and refuses the header as already credited. With a stale probe it would have collided with the mapping on insert.
  • share_partitions_postgres: the pruning test is rewritten as above. The duplicate, rejected-ID, legacy-range, archived-header and missing-partition tests pass unchanged.
  • The existing revision, commit-gate, uncertain-commit and partition-retry tests in append_admission, and the 3.x.x: a block found on the current tip is dropped when the payout revision moves between its submit check and its append's revision fence (#478 capture gap) #657 capture tests (commit_reconcile_tests, miner_tests::fence_capture, readiness_rpc), pass unchanged.

Local runs

cargo fmt --check and cargo clippy -p qbit-prism-server --all-targets -- -D warnings are clean.

The full gated suite ran on 204e01e, which is the current head's runtime: 82c80bb only adds the five new tests to test/prism-gated-tests.txt. It ran as the PostgreSQL shards run it: every qbit-prism-server target except live_regtest, 4 test threads, PRISM_TEST_REQUIRE_INTEGRATION=1, against a private PostgreSQL 16.10 cluster with fsync, full_page_writes and synchronous_commit on.

  • Main run, 86 binaries (the lib and 85 test binaries): 1,936 passed, 5 failed, 28 ignored. The lib passed 674/674.
  • The 5 failures are all in b619_gap_work_after_promotion, and they are environmental. Each one is pg_basebackup failed: … Disk quota exceeded. The test hard-codes tempdir_in("/tmp") for its standby, and this host's /tmp is a quota'd tmpfs that every session shares. CI's shards ran b619 green on 204e01e.
  • The ignored selections the shard runner adds: stratum_admission_postgres, the ten-thousand-connection test, passed 1/1, and observability_database passed 3/3. I stopped the run before the release-mode compact_runtime_scale selection, the issued_job_dependency ignored selection and qbit-prism-load, to keep the host quiet for the measurement below. CI's shards ran all three green on 204e01e, and shard 0 ran live_regtest green.
  • Flakes: none in the full run. An earlier targeted run with 4 threads on a busy host hit canceling statement due to lock timeout in share_partitions_postgres::landing_attributes_the_solver_on_the_block_row_and_readers_survive_a_detach. That is the database-wide migration-lock timeout seen when several schemas migrate at once. The test passed serially and in the full run.

Measurement

This is a local before/after of throughput_floor's share_append_throughput_floor: 20,000 seeded shares, then 3,000 appends per level at 1 and 4 appenders, in debug builds as CI runs it. The base binary is origin/3.x.x (dd8f765) and the patch is 204e01e. Base and patch ran back to back in fresh databases, in two rounds. Each round ran once directly against the private PostgreSQL 16 cluster, and once through one extra TCP hop: a userspace forwarder on loopback, a rough stand-in for the pair's docker bridge, haproxy and TLS.

Shares per second:

Path Round Base, 1 / 4 appenders Patch, 1 / 4 appenders Change
direct 1 423 / 454 550 / 604 +30% / +33%
direct 2 332 / 386 454 / 455 +37% / +18%
one extra hop 1 203 / 267 325 / 404 +60% / +51%
one extra hop 2 161 / 181 282 / 273 +75% / +51%

No level was contaminated by a foreign ORDER_LOCK holder. Other sessions share the host, so absolute rates drift between rounds: round 2 is slower for both binaries. Within each pair, the patch is faster in every row. The gain also grows with the cost of a round trip, as expected from cutting nine in-lock round trips to four. This is a debug build on loopback, not the pair. The deciding figure is N2's D1 peak re-measure of 204e01e through the real frontends.

Product code: src/ledger/window.rs, plus check_writable and WRITABLE_COLUMNS made pub(super) in src/ledger/connect.rs and imported in src/ledger.rs. This is a runtime change, so it is rc.3 material. Don't merge without the coordinator's go.

🤖 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.

RobertClarke and others added 2 commits October 6, 2026 05:03
…trips to four (#711)

A share append held ORDER_LOCK across nine client round trips: the
write guard, the payout-revision fence, the probe bounds, the bounded
share_id probe, its fallback, the clock UPDATE, the two INSERTs and
COMMIT. Every share waits behind that hold, so on a frontend that reaches
PostgreSQL through a docker bridge and TLS the round trips are the
ceiling.

Now the append reads the write guard, the fence (FOR SHARE OF the
cluster row when fenced) and the probe bounds in one statement, probes
the bounded leaves and, only when they hold nothing, the chosen fallback
in one statement (a materialized CTE gates the fallback with NOT
EXISTS), and writes the clock, the row and the header mapping in one
statement of data-modifying CTEs. A share from a future job inserts
nothing and is refused, which rolls the clock back with the transaction
as before. The lock keeps its own statement: under READ COMMITTED a
statement's snapshot predates a lock taken inside it.

The pruning test now reads the probe's JSON plan: the bounded CTE is
still pruned at executor startup, and a new header's fallback descends
the release partition alone. New tests pin three statements and COMMIT
under the lock for a new share (two for a duplicate), refuse a future
job without a trace, and refuse a halted cluster and a live legacy
writer before the fence.

Refs #711

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fenced append's probe after a cluster-row wait, and build the append's SQL once (#711)

Review findings on the merged statements:

- A credited header's fallback has no share_seq bound, so in the merged
  probe executor startup opened every retained leaf on every duplicate.
  A credited header now runs the bounded probe alone and the full-parent
  probe only on a bounded miss, as before. The rejected and legacy
  fallbacks keep their bounds and stay merged.
- The fenced first read's probe columns keep the snapshot taken before
  FOR SHARE waits out a writer on the cluster row. The read now also
  returns whether the returned row is still the snapshot's (its xmin
  against an InitPlan's read), and the append rereads the probe in its
  own statement when it is not. A test drives that path with a writer
  that also maps the share's header.
- The probe CTE is LEFT JOINed, so a missing probe row cannot hide the
  write guard's refusal.
- The statement texts are built once rather than formatted per share
  inside the lock.

A second test holds an uncommitted revision UPDATE while a fenced append
waits on it: the append compares the committed revision, or lands when
the writer rolls back.

Refs #711

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 6, 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-10-06T09:47:59.850539Z 82c80bb New commits
ℹ️ 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.

… manifest (#711)

The integration proof failed only because the five tests this PR adds executed but were not in test/prism-gated-tests.txt. No runtime change.

Refs #711

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@RobertClarke
RobertClarke merged commit d41a414 into 3.x.x Oct 6, 2026
40 checks passed
@RobertClarke
RobertClarke deleted the RobertClarke/711-append-round-trips branch October 6, 2026 11:13
RobertClarke added a commit that referenced this pull request Oct 6, 2026
…, and what each pair figure measured

From the review of #722, with the figures confirmed by the coordinator:
- #716 (open part) gives its three measured rates: 4 in about 149k
  shares in N2's rc.1 D1 sustained run on the pair, 1 in about 121k in
  the peak run on #719's build, and 1 in about 150k in rc.2's L3.
- #712 stays in the known issues. #721's parallel export shortens the
  export, but the source export is still on the critical path and both
  exports sit inside the cutover outage. #721's \gset move in the serial
  SQL is mentioned.
- #711 is improved by fix B and stays open for fix A, with the ceiling
  still flagged under 788.
- Each pair figure says what it measured:
  - rc.1's 1,479 ms is on the same shape, and an earlier under-offered
    run measured 1,116 ms;
  - the 1.473 ms hold is order_lock_hold_seconds{holder="append"} on the
    rc.1 runtime;
  - the 750/s ceiling is with the load balancer preferring the primary's
    frontend;
  - the failover drill run is described.
- The measured build is rc.3 without #718's answer mapping, and the 2.0.x
  upgrade points to the parallel export.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 6, 2026
Set VERSION and [workspace.package].version to 3.0.0-rc.3: rc.2 plus
#719 (#711 fix B: the share append holds ORDER_LOCK for 3 statements
plus COMMIT, down from 9 client round trips) and #721 (#712: the
parallel recovery-evidence export). Both Cargo.lock files move only
their workspace-member entries.

doc/release-notes-3.0.0-rc.3.md covers:
- the changes since rc.2, with N2's pair measurements on a build whose
  runtime is #719's head, each figure saying what it measured;
- upgrading, with no migration from rc.2 and the parallel export for a
  2.0.x cutover;
- the same evidence set as rc.2;
- the known issues: #716's open part with its three measured rates, #711
  still open for fix A, and #712's remaining parts.

The development-line notes name 3.0.0-rc.3, and they and the 3.0.0
notes link all three candidates' notes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 6, 2026
…ace, and the rollback hazard of the always-passed backlog setting

From the review of #725:
- The known issues add #724 to rc.3's list rather than claiming the rc.3
  notes had it.
- The pair evidence carried from rc.3 is named as rc.3's notes name it:
  the D1 peak-second gate, the 750/s ceiling and the failover drill run 1
  on #719's build. "C10" is in no record.
- Rolling a frontend back to rc.3 or earlier needs
  PRISM_STRATUM_LISTEN_BACKLOG removed first. This candidate's
  compose.yaml always passes it, and earlier builds in production mode
  refuse a set-but-unread PRISM_* setting.
- rc.1 to rc.3 did not read the setting: they refused it in production,
  and elsewhere ignored it and listened with mio's 128. A carried 2.x.x
  value overrides the 4096 default.
- #723's deployment-surface changes (compose.yaml, .env.example) are
  listed. Its CI proof is the unit test, and the pair's C5 re-run is the
  proof on the pair.
- The log line is the primary listener's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 28, 2026
…ER_LOCK is held for that call and the COMMIT (#711)

A share append held ORDER_LOCK across the lock statement, three
statements and the COMMIT, each a client round trip that every other share
of the cluster waited behind (#719).

Migration 032 (additive, no table altered, no capability):
- qbit_prism_append_share takes ORDER_LOCK and runs, each as a statement of
  its own and so each with a snapshot after the lock and any wait, what the
  frontend's statements ran: the write guard, the payout-revision fence
  (FOR SHARE when fenced), the share_id probe's inputs, the probe and its
  fallback, and for a new share the stamped row and its header mapping.
- It returns the new share_seq and accepted_at, or the existing row for
  the frontend to compare, with its own measure of the lock wait and hold.
- Refusals are raised before any write with SQLSTATEs QP001 to QP007,
  which the frontend maps back to the exact errors, and so the answers to
  miners, the statements gave (halted, legacy lease, PayoutRevisionChanged,
  the three duplicate-share refusals, a job from the future).
- qbit_prism_ledger_clock is #738's clock, now one definition: the call,
  the statement-by-statement append (a share with a block, the settlement's
  deferred-share credit, a share whose fields fail its checks) and the
  snapshot anchor all stamp with it.
- It alters no table, so #791's up-front table locks have nothing to take;
  its unit tests derive that from the file. Required from this release on.

The frontend (ledger/window.rs):
- A share without a block takes the call; the pre-commit gate and COMMIT
  stay with the frontend (commit_gated, shared with the statement path), so
  #716/#788's gate and its Contended retry are unchanged.
- A lock or statement timeout, or a cancellation, fails the call before
  COMMIT and rolls the whole transaction back; the 23514 retry still sees
  the ledger INSERT's error.
- Metrics: the ORDER_LOCK wait and the append hold are the server's
  measures (CalledOrderLock); a call that fails before reporting is a
  failed wait, and one that fails past its lock statement records neither.

Mixed versions: a 3.1.0 frontend appending with its own statements beside
one calling the function keeps share_seq order and rising stamps (its
stamps are stored in the floor the clock reads); only a backward step of
the database's own clock while both serve can break that.

Tests:
- append_admission: one call and the COMMIT under ORDER_LOCK for a new
  share, fenced or not, and a duplicate; refusals, the fence's waits, the
  probe after the fence, the 23514 retry and the uncertain COMMIT as
  before; a call cancelled waiting for the lock or past it rolls back
  whole without asking its gate, with the wait and hold recorded as above.
- ledger_clock: the 3.1.0 statements interleaved with the call.
- share_partitions_postgres: the probes' pruning is pinned by the leaves
  the append's transaction scanned, since EXPLAIN cannot reach them now.
- commit_reconcile: an append abandoned while queued on ORDER_LOCK waits
  inside its call, which, once granted, runs to its end before the
  connection's cleanup rolls it back: no row, ORDER_LOCK released, at
  most one share_seq drawn (it was none before).
- Migration: 032 in the native list, the required versions, the recovery
  evidence script, the schema rewinds to before 028 and to rc.6, and every
  hard-coded version list in the tests and the rc.6 pre-migrate scenario.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 28, 2026
…ER_LOCK is held for that call and the COMMIT (#711) (#802)

A share append held ORDER_LOCK across the lock statement, three
statements and the COMMIT, each a client round trip that every other share
of the cluster waited behind (#719).

Migration 032 (additive, no table altered, no capability):
- qbit_prism_append_share takes ORDER_LOCK and runs, each as a statement of
  its own and so each with a snapshot after the lock and any wait, what the
  frontend's statements ran: the write guard, the payout-revision fence
  (FOR SHARE when fenced), the share_id probe's inputs, the probe and its
  fallback, and for a new share the stamped row and its header mapping.
- It returns the new share_seq and accepted_at, or the existing row for
  the frontend to compare, with its own measure of the lock wait and hold.
- Refusals are raised before any write with SQLSTATEs QP001 to QP007,
  which the frontend maps back to the exact errors, and so the answers to
  miners, the statements gave (halted, legacy lease, PayoutRevisionChanged,
  the three duplicate-share refusals, a job from the future).
- qbit_prism_ledger_clock is #738's clock, now one definition: the call,
  the statement-by-statement append (a share with a block, the settlement's
  deferred-share credit, a share whose fields fail its checks) and the
  snapshot anchor all stamp with it.
- It alters no table, so #791's up-front table locks have nothing to take;
  its unit tests derive that from the file. Required from this release on.

The frontend (ledger/window.rs):
- A share without a block takes the call; the pre-commit gate and COMMIT
  stay with the frontend (commit_gated, shared with the statement path), so
  #716/#788's gate and its Contended retry are unchanged.
- A lock or statement timeout, or a cancellation, fails the call before
  COMMIT and rolls the whole transaction back; the 23514 retry still sees
  the ledger INSERT's error.
- Metrics: the ORDER_LOCK wait and the append hold are the server's
  measures (CalledOrderLock); a call that fails before reporting is a
  failed wait, and one that fails past its lock statement records neither.

Mixed versions: a 3.1.0 frontend appending with its own statements beside
one calling the function keeps share_seq order and rising stamps (its
stamps are stored in the floor the clock reads); only a backward step of
the database's own clock while both serve can break that.

Tests:
- append_admission: one call and the COMMIT under ORDER_LOCK for a new
  share, fenced or not, and a duplicate; refusals, the fence's waits, the
  probe after the fence, the 23514 retry and the uncertain COMMIT as
  before; a call cancelled waiting for the lock or past it rolls back
  whole without asking its gate, with the wait and hold recorded as above.
- ledger_clock: the 3.1.0 statements interleaved with the call.
- share_partitions_postgres: the probes' pruning is pinned by the leaves
  the append's transaction scanned, since EXPLAIN cannot reach them now.
- commit_reconcile: an append abandoned while queued on ORDER_LOCK waits
  inside its call, which, once granted, runs to its end before the
  connection's cleanup rolls it back: no row, ORDER_LOCK released, at
  most one share_seq drawn (it was none before).
- Migration: 032 in the native list, the required versions, the recovery
  evidence script, the schema rewinds to before 028 and to rc.6, and every
  hard-coded version list in the tests and the rc.6 pre-migrate scenario.

Co-authored-by: Claude Opus 5.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.

1 participant