Skip to content

3.x.x: write each legacy audit before SETTLEMENT_LOCK and bound import-audits (#765) - #770

Merged
RobertClarke merged 9 commits into
3.x.xfrom
RobertClarke/prism-765-import-lock
Oct 10, 2026
Merged

RobertClarke merged 9 commits into
3.x.xfrom
RobertClarke/prism-765-import-lock

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Fixes #765 for import-audits: a legacy audit's write no longer happens under SETTLEMENT_LOCK, and every phase of a row is bounded.

What happened on the pair

rc.6's importer (Ledger::import_legacy_audits, ledger/migration.rs L3975–3990 at 81c592c3) takes SETTLEMENT_LOCK, checks writable(), and only then builds the UPDATE's binds and sends it. #765's 09:52Z evidence shows the importer's session idle in transaction on ClientRead for the whole ≥ 90 s hold, then incomplete message from client at the SIGKILL. The server was waiting for the rest of the statement: the lock lasted exactly as long as the client took to send it, and nothing bounded that.

Measured

One synthetic legacy row: 112.2 MB canonical body, plus a 37.5 MB witness-leaves array bound beside it (149.7 MB of parameters). Release build; TLS (sslmode=verify-full) through an HAProxy TCP hop with the pair's settings. A second session takes SETTLEMENT_LOCK every 20 ms. Phases are timed by the client; the send/execution split comes from sampling the session's pg_stat_activity state every 10 ms.

Phase rc.6 order this PR
wait for SETTLEMENT_LOCK 1 ms 0.9 ms
encode the nine binds 103 ms, under the lock before the transaction, inside prepare (1.09 s with load, verify and canonicalize)
send the UPDATE (session idle in transaction, ClientRead) ≈ 0.15 s, under the lock before the lock, inside write (2.73 s)
server runs the UPDATE (TOAST, WAL) ≈ 2.9 s, under the lock before the lock, inside write
guard read + COMMIT 28 ms the whole hold
SETTLEMENT_LOCK held 3.145 s 13.2 ms
longest wait of the other session 3.130 s 0.003 s
send throttled to 16 MiB/s: lock held 14.948 s (≈ 12 s of it the send) 15.7 ms
send throttled to 16 MiB/s: longest wait 14.935 s 0.017 s

The new test a_large_legacy_audit_is_sent_without_holding_settlement_lock fails on rc.6's order (a 19.4 s wait against its 3 s bound) and passes with this change.

Where the 27× went: rc.6's hold is send + server execution + commit. Here that is about 3.1 s, the rehearsal's ≤ 3.4 s. On the pair the session sat in ClientRead for ≥ 68 s, and its message was still incomplete at the SIGKILL. So the send alone took ≥ 68 s against ≈ 0.15 s here; size and server work account for seconds, not minutes.

Locally, over TLS, a 112 MB bind is sent in 0.22–0.48 s with no stall in 70 runs: direct, through HAProxy, through a relay feeding the server 64 KiB at a time, and with the client pinned to two CPUs shared with busy loops. The one client-side mechanism I know of in this stack that leaves exactly that server state, with no end, is sqlx 0.8.6's rustls stream losing the wakeup of a large write. That is transact-rs/sqlx#4248, fixed upstream by #4251 after 0.8.6. It is a race I could not trigger locally, so it is a likely cause, not a proven one.

The fix does not depend on it: whatever slows or stops the send now happens before SETTLEMENT_LOCK, and it is bounded. #765's lead, the leaves arrays ($5/$6) encoded under the lock, measured 103 ms for all nine binds together. That is not the cause, and the encoding now happens off the runtime and before any transaction opens.

The change (importer path only)

Per row, in import_legacy_audits_with / write_legacy_audit (ledger/migration.rs):

  1. Load, verify and canonicalize the body, and encode all nine UPDATE parameters, on one spawn_blocking thread, before any transaction opens (ImportedAudit::encode). The leaves arrays are bound as JSON text with ::jsonb, which stores the same jsonb.
  2. On a connection of its own (detached from the pool, so abandoning the row closes the socket). The connection sets client_connection_check_interval to 1 s, best effort (PostgreSQL ≥ 14 on Linux), so the server rolls an abandoned row back within about a second even mid-UPDATE. Then: BEGIN, transaction-local timeouts for the write, and a writable() pre-check, so a halted cluster or a live legacy writer is refused before anything is sent. Then send and run the UPDATE, holding only that row's lock.
  3. Transaction-local timeouts for the locked phase, then poll pg_try_advisory_xact_lock(SETTLEMENT_LOCK) every 25 ms until granted or the lock timeout passes, then writable() again and COMMIT. A poll that misses the lock also walks the SETTLEMENT_LOCK holder's blockers: pg_blocking_pids, which counts its parallel workers, then their blockers in turn. If this transaction is among them, the row is rolled back at once so the holder goes first, including when the holder is queued behind another session that waits on the row. Other waiters, such as a second importer, just wait.

Under the lock only the guard read and the commit remain. The write is also re-polled every 100 ms, which un-sticks the sqlx lost wakeup above if it occurs.

Why the write may run outside SETTLEMENT_LOCK

The commit point does not move. The importer has taken SETTLEMENT_LOCK and writable() since #244. That is the generic writer pattern, and it serializes the import's commit with every other holder and fences it against a halt. Both still hold: the UPDATE is invisible until COMMIT, and COMMIT runs under the lock after writable() (connect.rs:821) has re-read the cluster row with a fresh snapshot. fatal-state set (fatal_state.rs:136), signing-transition (signing_transition.rs:70) and policy-transition (policy_transition.rs:31) take the lock, so each still commits wholly before or wholly after a row. What moves outside the lock is only work no other transaction can see.

What touches these rows (canonical_audit_bytes IS NULL AND share_snapshot_sha256 IS NULL, the importer's own filter at migration.rs:3925):

  • Settlement does not touch them. None of the other SETTLEMENT_LOCK holders (blocks.rs:293/425/513/736, fanout.rs:244/260, window.rs:514/1175, jobs.rs:40/99, jobs/cleanup.rs:61, candidates.rs:1818) reads or writes qbit_pool_audit_bundles. The only references in the server are listed below.
  • Readers (audit.rs:44/157/369, candidates.rs:1053/2078, blocks.rs:131/147, the API's read_models.rs and queries/*.sql) are plain MVCC reads. A row lock never blocks them, and they see the row unchanged until the commit.
  • Writers:
    • land_candidate's idempotent found_block_bits fill (blocks.rs:165, under SETTLEMENT_LOCK from blocks.rs:140) runs only when a block whose audit row already exists lands again.
    • record_landed_audit_bits (candidates.rs:1073, no advisory lock) fills the same column.
    • The archive seal (archive.rs:1443) selects only rows joined to a share snapshot (archive.rs:1418), never these.
    • Landing's INSERT (blocks.rs:236) runs only when no row exists (blocks.rs:147).
  • No deadlock, and no long wait. The importer never waits on SETTLEMENT_LOCK: it polls it and never queues. So it never has a wait-for edge towards a lock holder, and no cycle can form. A holder that does need the row being imported (only the blocks.rs:165 case) waits only until the importer's next poll, ≤ 25 ms after the importer's UPDATE has finished, which then sees it waiting and rolls the row back. In the two tests below, the holder waited about one poll interval (25–31 ms), directly or queued behind another waiter. While that UPDATE is still executing (seconds for a 112 MB row) the holder waits for it, which is less than under rc.6, where it waited for SETTLEMENT_LOCK across the importer's whole send and execution.
  • Failover and fencing. A demoted primary refuses the write or the commit, and a fence that cuts connections rolls the row back; both as before. The migration's own SETTLEMENT_LOCK (migration.rs:2944) applies only before migration 3, so never on a migrated database.

Mixed versions

rc.6 frontends and this importer share SETTLEMENT_LOCK. It is the same advisory key (0x505249534d000003) in the same transaction scope. rc.6 frontends block on it with pg_advisory_xact_lock (connect.rs:735) and the importer polls it with pg_try_advisory_xact_lock, so they exclude each other as two rc.6 processes do. The importer writes the same columns, values and WHERE guard as rc.6's. No schema or migration change: since v3.0.0-rc.6 the base has only #760, which changes the qbitd RPC client, and import-audits does not use it. The startup gates (schema version, capabilities, migration source) are rc.6's.

Bounds, signals and output

Setting (new) Default Pair Bounds
PRISM_IMPORT_AUDITS_WRITE_TIMEOUT_MS (1000–600000) 60000 60000 the write: idle_in_transaction_session_timeout (the server ends a session that stops sending mid-statement), statement_timeout and lock_timeout (row lock)
PRISM_IMPORT_AUDITS_LOCK_TIMEOUT_MS (100–600000) 5000 2000 the SETTLEMENT_LOCK wait; once held, idle_in_transaction_session_timeout and statement_timeout, so a stalled client or statement loses its session, and the lock, within this long

Both are in native-settings.txt, so this binary accepts them. Pass them only to the one-off (compose run --env), never through the lane env file. An rc.6 frontend in production mode refuses to start on a PRISM_* name it does not know (config/environment.rs). No CLI flag changes.

A row that exceeds a bound is rolled back, and the command exits 1. For a busy lock it prints this (pinned by the_import_audits_command_names_the_row_when_settlement_lock_stays_busy):

stdout: Audit completeness: {"missing_stored_bodies":1,"missing_canonical_bytes":1}
stderr: Error: importing legacy audit <64-hex block hash>

        Caused by:
            SETTLEMENT_LOCK stayed busy for 2000 ms; the row is rolled back and nothing was stored

Rows imported before the failure keep their stderr lines and stay imported. A plain re-run is the right retry: the failed row was rolled back, imported rows are skipped (canonical_audit_bytes IS NOT NULL), and the re-run starts at the failed row, verifying it again from its file.

For a capped retry loop:

  • Transient, safe to re-run after a short pause:
    • SETTLEMENT_LOCK stayed busy;
    • the session holding SETTLEMENT_LOCK is waiting for a lock this row's write holds;
    • terminating connection due to idle-in-transaction timeout, a stalled send or a stall under the lock;
    • canceling statement due to statement timeout or lock timeout;
    • a dropped connection.
  • Not transient, a re-run fails the same way: a verification error naming the row, such as a digest mismatch, a missing body or sidecar, or a key mismatch.
  • Do not retry automatically: import-audits stopped on request. That is the operator's own stop.

SIGTERM or SIGINT stops the command, and it exits 1 with import-audits stopped on request after importing N audit bodies; ... (a stop that lands after the last row is in ends as a finished import instead):

  • before the next row;
  • by dropping the connection of a row that has not been granted the lock;
  • or, once the lock is held, after finishing the commit, which is bounded as above.

A second signal exits at once, also with 1.

As a container's PID 1, the command ignored a SIGTERM it had no handler for. That is why docker stop could only kill it.

There is no Docker on the build host, so I checked this the way the kernel applies it to a container's init. sudo unshare --pid --fork plus setpriv back to the user makes the command PID 1 of a new PID namespace, and SIGTERM is sent from the parent namespace, as docker stop does:

  • Control: sleep as PID 1 was still running 2 s after SIGTERM.
  • import-audits as PID 1, parked polling SETTLEMENT_LOCK after writing its row: exited 15 ms after SIGTERM with exit code 1 and the "stopped on request" line. No session was left in a transaction, and the row was not stored.

Please repeat it once on the one-off: docker compose run it, docker stop it mid-row, and expect exit 1 within about a second.

Each row prints one line on stderr; stdout keeps the completeness JSON and Imported N audit bodies:

import-audits: block_hash=<64 hex> imported parameter_bytes=block_hash:64,schema_version:26,network_difficulty:5,coinbase_value_sats:8,audit_commitment_leaves_hex:68,witness_merkle_leaves_hex:37520001,body_uri:127,audit_bundle_sha256:64,canonical_audit_bytes:107316570 total_parameter_bytes=144836933 prepare_ms=24235 write_ms=25193 lock_wait_ms=2.2 lock_held_ms=146.0 total_ms=49581

(That line is from the debug-build test through the 16 MiB/s relay; prepare and write are far shorter in a release build on the pair.)

Tests

tests/import_audits_settlement_lock.rs (gated, listed in test/prism-gated-tests.txt) puts the importer behind a TCP relay that throttles, or stalls, what one connection sends. The relay keeps reading while stalled, so a close still reaches the server, as on a direct connection. Times below are from a debug build over TLS:

Test Scenario Result
a_large_legacy_audit_is_sent_without_holding_settlement_lock 107 MB canonical body + 37.5 MB witness leaves, throttled waiter's longest wait 0.134 s (bound 3 s); the write took 25 s; lock held 146 ms
a_write_that_stalls_mid_send_is_rolled_back_within_the_write_timeout the pair's state ended by terminating connection due to idle-in-transaction timeout 2.9 s in (write timeout 2 s); the lock was never taken; re-run imports
a_client_that_stalls_holding_settlement_lock_loses_it_within_the_lock_timeout stalled before COMMIT session and lock gone 1.07 s in (lock timeout 1 s); re-run imports
a_busy_settlement_lock_fails_the_row_within_the_lock_timeout lock held elsewhere fails in 1.08 s; holder untouched
a_stop_during_a_write_rolls_the_row_back_at_once stop mid-send stops within 2 s; no open transaction left
a_stop_while_the_server_runs_the_write_rolls_it_back_within_a_second stop while the server runs the UPDATE (a test trigger sleeps 30 s) the server's transaction ended 1.01 s after the stop
a_stop_between_rows_ends_the_import_before_the_next_row stop after a row exactly one row imported
the_import_audits_command_stops_on_sigterm real binary: a clean run, then a row stalled mid-write the clean run prints the stderr line; after kill -TERM it exits 1 in 17 ms; no open transaction
the_import_audits_command_names_the_row_when_settlement_lock_stays_busy real binary, lock held elsewhere exits 1 with the output above; a re-run after release imports the row
a_settlement_lock_holder_waiting_for_the_row_goes_first a lock holder UPDATEs the row the importer has written the holder got through in 31 ms; the importer rolled back about 90 ms in, inside a 30 s bound; the re-run imports and the holder's write stays
a_stop_after_the_last_row_ends_as_a_finished_import stop after the final row Ok(1), not a stop
a_stop_before_the_lock_is_granted_rolls_the_row_back stop while the first lock poll is held at the relay (Codex) ImportStopped within 2 s; the held poll is then released and the row is still not stored
a_settlement_lock_holder_queued_behind_another_waiter_still_goes_first the holder waits for a session that waits for the importer the holder got through in 26 ms; the importer rolled back

Existing importer tests pass locally:

  • ledger_deadline_atomicity 7/7 (per-item failure atomicity);
  • audit_body_normalization 19/19 (legacy import pool-acquire counts);
  • config_cli 30/30;
  • all 20 import and legacy tests in ledger_postgres.

Run note for the live pair

  • Can a one-off import-audits built from this head, or from rc.6 plus only these commits, run beside the rc.6 serving stack? Yes.
    • No schema change. The startup gates are rc.6's.
    • Same lock key and semantics.
    • Same row writes as rc.6's importer.
    • Nothing the frontends run changes.
    • The only rule: the two env vars go to the one-off only.
  • Timeouts: PRISM_IMPORT_AUDITS_LOCK_TIMEOUT_MS=2000 and PRISM_IMPORT_AUDITS_WRITE_TIMEOUT_MS=60000.
    • 2 s keeps any hold below the frontends' own 5 s lock waits.
    • 60 s bounds a send that stops, while only the row is locked.
  • Expected hold for a 112 MB row: the guard read plus COMMIT, about 13–16 ms here in a release build, against 3.1 s for rc.6's order on the same path. On the pair, allow up to a few hundred ms. With asynchronous replication, COMMIT flushes only the local WAL the WAL writer has not already flushed during the write. If the 3.x.x: Cutover qualification — migration rehearsal, failover drill, soak, go/no-go #291 sync flip is in effect, add the standby's acknowledgement of that tail. The hold is capped hard at the lock timeout.
  • Operator change: the two env vars above. docker stop now works; it stops between rows or rolls back the row in progress, and it no longer needs the SIGKILL guard from 3.x.x: import-audits holds SETTLEMENT_LOCK while writing a large canonical audit body (≥90 s for ~112 MB), stalling template refresh and settlement #765's operational note. On a failed row, exit 1 means re-run (see the retry rules above).

Other open PRs

None of #761, #763, #764 or the 3.1 stack changes the importer. #766, #767, #768 and #769 touch other code in the same files: ledger.rs re-exports, migration.rs, tools.rs, native-settings.txt, scripts/prism_pool_acquires.json and test/prism-gated-tests.txt. Expect at most adjacent-line conflicts when the 3.1 stream rebases.

Follow-up (not in this PR)

The same sqlx 0.8.6 lost wakeup can stall any large statement the serving frontends send over TLS. Most have client-side deadlines, but the fix belongs upstream: backport transact-rs/sqlx#4251 (a [patch] of sqlx-core), or move to a release that has it. That change ships with the serving binary, so it needs its own PR and L3.

🤖 Generated with Claude Code

RobertClarke and others added 7 commits October 10, 2026 12:54
…t-audits (#765)

On the live pair, import-audits held SETTLEMENT_LOCK for at least 90 s on a
legacy audit with a ~112 MB canonical body. PostgreSQL showed the session
idle in transaction on ClientRead for the whole hold, then "incomplete
message from client" at the SIGKILL: rc.6 takes the lock first and only
then binds and sends the UPDATE, so the hold lasted as long as the client
took to send it, and nothing bounded that.

Each row now has its UPDATE parameters encoded on the blocking thread that
verifies the body, before any transaction opens. The UPDATE is then sent
and run on a connection of its own, holding only the row's lock. Only after
that does the importer poll for SETTLEMENT_LOCK with
pg_try_advisory_xact_lock (never queued, so it cannot close a deadlock
cycle with a holder waiting for that row), check the write guard under it,
and commit. Every other SETTLEMENT_LOCK holder still sees a row committed
before it took the lock or not at all, and the lock now covers one guard
read and the commit.

Transaction-local timeouts bound each phase. PRISM_IMPORT_AUDITS_WRITE_TIMEOUT_MS
(60 s) is the idle_in_transaction_session_timeout, statement_timeout and
lock_timeout of the write; PRISM_IMPORT_AUDITS_LOCK_TIMEOUT_MS (5 s) bounds
the wait for the lock and is the idle and statement timeout while it is
held, so a stalled client or statement loses its session, and the lock,
within that long. A row that exceeds a bound is rolled back and the command
fails naming it; a re-run resumes from it. The write is also re-polled
every 100 ms: sqlx 0.8.6's rustls stream can lose the wakeup of a large
write (transact-rs/sqlx#4248, fixed after 0.8.6), which leaves exactly
that server-side state.

SIGTERM or SIGINT now stops the command: before the next row, or by
dropping the connection of a row that has not been granted the lock, which
rolls it back at once; it exits 1. In a container the command runs as
PID 1, which ignores a SIGTERM it has no handler for, so docker stop could
only kill it. Each imported row prints one line on stderr with the encoded
size of every parameter and the prepare, write, lock wait, lock hold and
total times.

No schema change, and no change to the lock helpers or anything else the
serving frontends run. The new tests put the importer behind a relay that
throttles or stalls what it sends: a 107 MB body with a 37 MB witness
leaves array beside a SETTLEMENT_LOCK waiter, stalls mid-write and while
holding the lock, a busy lock, a stop mid-write and between rows, and
SIGTERM to the real command mid-row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…OCK stays busy (#765)

An operator's retry loop keys on this: the command exits 1, stdout keeps
the remaining-work counts, stderr names the row and the busy lock, nothing
is stored, and a plain re-run imports the row once the lock frees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n import-audits' stop and bounds (#765)

Review of #770 found five gaps, fixed here:

- The importer holds the legacy row's lock while it polls for
  SETTLEMENT_LOCK, so a lock holder that needs that very row (a landing
  filling its found_block_bits) waited up to the lock timeout. The poll that
  misses the lock now also asks whether any session waits for this
  transaction, and if one does the row is rolled back at once.
- The write guard now also runs before the write, so a halted cluster or a
  live legacy writer is refused before anything is sent, as before #770; it
  still runs again under the lock.
- A second SIGTERM or SIGINT exits at once, for a stop that something
  outside the importer's bounds holds up; the first still stops gracefully.
- A stop exits directly even when the remaining-work counts cannot be
  read, instead of returning through runtime shutdown.
- PRISM_IMPORT_AUDITS_LOCK_TIMEOUT_MS has a 100 ms floor and
  PRISM_IMPORT_AUDITS_WRITE_TIMEOUT_MS a 1 s floor: each is also the
  phase's idle timeout, which must outlast the importer's own pauses.

A committed row's connection now closes within 5 s or is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y its stop paths (#765)

A stop drops the row's connection, but PostgreSQL notices a closed socket
only when it next talks to the client: a stop that arrived while the server
was still storing a large row left it running, row lock held, until the
write timeout. Each import transaction now sets
client_connection_check_interval (1 s), so the server rolls an abandoned
row back within about a second wherever the stop lands.

Also from the second review of #770:

- A stop that arrives once the last row is in ends as a finished import
  (exit 0), not as a stop.
- Rolling back for a busy lock, for a waiting session, or for an unchanged
  row ends the session cleanly instead of dropping it, which kept
  "unexpected EOF" lines out of the server log.
- The refusal for a waiting session says what it knows: another session
  waits for a lock the row's write holds (the row, or its table).
- The README says that a row already holding SETTLEMENT_LOCK finishes on a
  stop, and the second-signal exit also works off unix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dits row, and keep its stop paths bounded (#765)

From the third review of #770:

- The probe that rolls a row back for a waiting session now fires only
  when the session holding SETTLEMENT_LOCK is the one waiting on the row's
  write. A second importer or an index build waiting on the row no longer
  fails the import; they just wait, as for any writer. The refusal says so.
- client_connection_check_interval is set best-effort on the row's own
  connection, before the transaction: a server that cannot check (before
  PostgreSQL 14, or off Linux) refuses it, and that no longer fails every
  row.
- A stop is read before the next row again, so it never waits for the next
  body to load; a cheap EXISTS still ends a run whose last row is in as a
  finished import.
- The rollback on the refusal and unchanged-row paths is bounded like the
  close, and a failed rollback no longer hides the refusal message.
- One signal-counting loop serves unix and non-unix, and a stop whose
  remaining-work counts cannot be serialized says so instead of printing an
  empty line.
- The mid-execution stop test now asserts the rollback within 3 s, and a
  test pins the stop-after-the-last-row outcome.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mpt an import-audits row too, and bound the row's setup (#765)

From the fourth review of #770:

- The preemption probe walks the SETTLEMENT_LOCK holder's blockers
  transitively (pg_blocking_pids, which also counts its parallel workers),
  so a holder that waits for the imported row through another session, such
  as a second importer queued on that row, still goes first.
- The row's transaction setup (connection check, BEGIN, timeouts, write
  guard) is bounded by the write timeout and ends on a stop, as the write
  does.
- A stop is checked again after the next row is read, so a stop that lands
  during the read starts no work on the body, and the EXISTS that tells a
  finished run from a stopped one is bounded.
- After a rollback that did not finish, the connection is dropped rather
  than closed, so a refusal never waits twice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…preemption probe (#765)

From the final review of #770: checking out the row's own connection is
now bounded by the write timeout and ends on a stop, like the rest of the
row's setup. The probe that walks the SETTLEMENT_LOCK holder's blockers
recurses on process IDs alone, so it ends on its own on a wait cycle with
no depth cap. The busy-lock poll runs every 25 ms, as the session lock loop
does, since each miss reads the lock manager's state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@RobertClarke
RobertClarke marked this pull request as ready for review October 10, 2026 17:48
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 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-10T17:57:52.596859Z 099f8b2 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.

@blacksmith-sh

This comment has been minimized.

@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: 9038579215

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

RobertClarke and others added 2 commits October 10, 2026 13:51
#765)

The stop path's bounded EXISTS checks out a pooled connection, which makes
two `self.acquire()` sites in import_legacy_audits_with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex on #770: a stop that arrived after a row's UPDATE but before its first
lock poll was never read, so the poll could take SETTLEMENT_LOCK and the
row commit despite the stop. The stop is now checked before every poll and
raced against the poll in flight; only once the lock is known to be held
does the row finish. A new test holds the first poll at the relay, stops,
then lets the poll through: the row is rolled back and a re-run imports it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@RobertClarke

Copy link
Copy Markdown
Member Author

DELEGATE REPORT: #765 / #770

Head: 099f8b2f1904db84291a5b1dafe31de180ab710e.

CI: green. Run 38073705467: all 20 jobs passed, including the four PostgreSQL shards, "Prove every Rust PRISM gated test executed" and "Lint, compile, and test". The new import_audits_settlement_lock binary ran 13/13 in 62.6 s on its shard.

Codex:

  • One P2 on 9038579: a stop arriving just before the first lock poll was ignored.
  • Fixed in 099f8b2 with a regression test that fails on the old code. Replied in the thread and resolved it.
  • Codex then reviewed 099f8b2, found nothing, and reacted 👍 at 17:57:55Z after the completed row. No unresolved threads remain.

Local review: five /code-review medium rounds, all findings addressed. No round found a P1, and the final round found no P1/P2.

sqlx backport: #771.

Root cause, measured

rc.6 takes SETTLEMENT_LOCK, and only then encodes the binds and sends the UPDATE. Its hold is therefore encode + send + server execution + commit.

The row is a 112.2 MB canonical body with a 37.5 MB witness-leaves array (149.7 MB of binds). Release build, TLS (verify-full) through an HAProxy TCP hop with the pair's settings. A second session takes the lock every 20 ms.

Phase rc.6 order #770
lock wait 1 ms 0.9 ms
encode 103 ms, under the lock 0 under the lock: inside prepare, before the transaction
send (idle in transaction, ClientRead) ≈ 0.15 s, under the lock 0 under the lock: inside write (2.73 s with execution)
server execution (TOAST, WAL) ≈ 2.9 s, under the lock 0 under the lock
guard + COMMIT 28 ms the whole hold
SETTLEMENT_LOCK held 3.145 s 13.2 ms
waiter's longest wait 3.130 s 0.003 s
send throttled to 16 MiB/s: held 14.948 s (≈ 12 s of it the send) 15.7 ms
send throttled to 16 MiB/s: waiter's longest wait 14.935 s 0.017 s

On the pair, the importer sat in ClientRead for ≥ 68 s with its message still incomplete at the SIGKILL. The 27× was the send, against ≈ 0.15 s here, not size or server work.

The likely mechanism is sqlx 0.8.6's rustls lost wakeup on a large write (transact-rs/sqlx#4248, fixed upstream by #4251, not in 0.8.x). I could not reproduce it locally (70 runs over TLS, direct, through HAProxy, through a throttling relay and under CPU contention), so it is unproven. #770 does not depend on it.

Concurrency test

The waiter's longest wait beside the ≥ 100 MB import went from 19.4 s with rc.6's order (185 MB throttled; the test fails against its 3 s bound) to 0.078 s with #770 (passes). The CI version of the test (107 MB body plus 37.5 MB of leaves, debug build) measured 0.03–0.37 s.

Run note (full text in the PR body)

  • A one-off import-audits from 3.x.x: write each legacy audit before SETTLEMENT_LOCK and bound import-audits (#765) #770's squash SHA is safe beside the rc.6 serving stack: yes.
  • Timeouts: PRISM_IMPORT_AUDITS_LOCK_TIMEOUT_MS=2000 and PRISM_IMPORT_AUDITS_WRITE_TIMEOUT_MS=60000.
    • Pass them only via compose run --env.
    • Both are in native-settings.txt.
    • rc.6 frontends refuse unknown PRISM_* names in production, so keep them out of the lane env file.
  • Expected hold for a 112 MB row: 13–16 ms here; allow a few hundred ms on the pair. It is capped at the lock timeout.
  • A failed row: exit 1. stdout shows the completeness counts; stderr shows Error: importing legacy audit <hash> / Caused by: SETTLEMENT_LOCK stayed busy for 2000 ms; the row is rolled back and nothing was stored. A plain re-run is the right retry: the row was rolled back and imported rows are skipped. The PR body lists which errors are transient and which are permanent.
  • SIGTERM:
    • First signal: stop before the next row, or roll back a row not yet granted the lock. A row that holds the lock finishes its commit.
    • Second signal: exit at once.
    • Verified with the importer as PID 1 of a new PID namespace (minidev has no Docker): exit 1 after 15 ms, with no session or row left behind. A no-handler sleep as PID 1 ignored SIGTERM.
    • Please confirm once on the one-off with docker stop.
  • Upstream fix: 3.x.x: backport sqlx's TLS lost-wakeup fix (launchbadge/sqlx#4251) so a large statement cannot stall a ledger connection #771 tracks backporting sqlx#4251 for the serving binary. It is a separate PR with its own L3; not started.
  • Per-row line: on stderr, import-audits: block_hash=... imported parameter_bytes=... prepare_ms write_ms lock_wait_ms lock_held_ms total_ms. stdout keeps the completeness JSON and Imported N audit bodies.

@RobertClarke
RobertClarke merged commit 4c13491 into 3.x.x Oct 10, 2026
39 checks passed
RobertClarke added a commit that referenced this pull request Oct 16, 2026
…TLEMENT_LOCK, bound import-audits) into the 3.1 identity-sync branch

No conflicts. #770 adds no migration, so 027 and 031 stay free (3.x.x tops
out at 026). It writes legacy audit bundles under SETTLEMENT_LOCK, outside
the peer sync's paths. Locally green: dual_writer_sync, dual_writer_rebuild,
dual_writer, import_audits_settlement_lock, the full library suite, clippy,
fmt, the census, settings and metrics checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 16, 2026
Brings in 3.x.x's 4c13491 (#770: each legacy audit written before
SETTLEMENT_LOCK, bounded import-audits) through D1's branch. It merged
clean, and nothing it changes reads or writes the audit snapshots'
cut columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 19, 2026
The notes cover everything since v3.0.0-rc.6: #770's import-audits fix
(#765) and #760's idle-connection bound (#759), which would have shipped as
rc.7, and the 3.1 dual writer (#766, #768, #767, #769, #763), off by
default. They describe the new settings, migrations 027, 028 and 031 (029
and 030 reserved), the upgrade from rc.6 with the migrate run while rc.6
serves, the rollbacks, and the dual writer's known limits. The migration
guide's import-audits paragraph names this candidate in place of the
skipped rc.7.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 20, 2026
* 3.x.x: version 3.1.0-rc.1

VERSION, the workspace version and both lockfiles move to 3.1.0-rc.1.
The fuzz lockfile also picks up hyper and hyper-util, which #769 added to
the server without refreshing it. The 3.0.0 and development-line notes
point at the new candidate; its own notes follow in this pull request.

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

* 3.x.x: 3.1.0-rc.1 release notes

The notes cover everything since v3.0.0-rc.6: #770's import-audits fix
(#765) and #760's idle-connection bound (#759), which would have shipped as
rc.7, and the 3.1 dual writer (#766, #768, #767, #769, #763), off by
default. They describe the new settings, migrations 027, 028 and 031 (029
and 030 reserved), the upgrade from rc.6 with the migrate run while rc.6
serves, the rollbacks, and the dual writer's known limits. The migration
guide's import-audits paragraph names this candidate in place of the
skipped rc.7.

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

* 3.x.x: 3.1.0-rc.1 notes: #773's pre-migrate tests

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

* 3.x.x: 3.1.0-rc.1 notes: the rollback to one writer stops and syncs the peer first

Codex on #774: DOWNGRADE fences nothing, so the peer must be stopped, and its
tail pulled, before the single-writer start; declare the tail lost only for a
peer that never returns with its own database.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 22, 2026
* 3.0.x: version 3.0.0 and its release notes (#557)

3.0.0 is 3.0.0-rc.6 plus #770 (#765) and #760 (#759), the two fixes
#772 prepared as 3.0.0-rc.7, which was never tagged. The 3.0.x branch
starts at #770's merge, 4c13491, before 3.x.x took the 3.1 dual writer.

- VERSION, [workspace.package].version and the workspace-member entries
  of both Cargo.lock files move to 3.0.0.
- doc/release-notes-3.0.0.md becomes the 3.0.0 notes: #772's rc.7 notes
  as the changes since rc.6, then the D5 recovery contract it held.
- The development-line note and the migration guide name 3.0.0.

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

* 3.0.x: update rustls, rustls-webpki and webpki-roots for six RustSec advisories

cargo deny fails on rc.6's lockfile with RUSTSEC-2026-0346, -0347, -0348
and -0349 (rustls < 0.23.46), RUSTSEC-2026-0382 (rustls-webpki
< 0.103.16) and RUSTSEC-2026-0381 (webpki-roots < 1.0.10). Move each to
its first fixed patch release with cargo update --precise, in the root
and fuzz lockfiles, as #354 did for RUSTSEC-2026-0285. No other
dependency changes.

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

* 3.0.x: describe 3.0.0 as this line's production release

The development-line note's status, not-done and upgrade sections, and
the README banner, said no production release of the Rust server
existed. With the coordinator's go-ahead for 3.0.0 they now point to
3.0.0 on 3.0.x and its notes, and say 3.x.x continues as 3.1. The 3.0.0
notes list the TLS dependency update.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 28, 2026
… vendoring sqlx-core 0.8.6 (#771) (#794)

* 3.x.x: backport sqlx's TLS readiness fix so a large statement cannot stall a ledger connection (#771)

Cause. sqlx-core 0.8.6's StdSocket::poll_ready, under every rustls
connection, waited for write readiness and then for read readiness.
When a write blocks before sending anything, rustls 0.23.46's
complete_io tries a read too, so a large statement leaves both flagged.
Write readiness that arrives between the blocked write and the poll is
spent, and the task parks on read readiness while the server waits for
the rest of the statement (#765's suspected stall). Data that arrives
while the task waits to write has no waker at all. transact-rs/sqlx#4251 (merge c0ec9c0b, 2026-04-28) fixes
both: poll_ready registers both directions and returns when either is
ready. It is released in sqlx 0.9.0 only; no 0.8.x tag carries it.

Change.
- vendor/sqlx-core is sqlx-core 0.8.6 from the local registry cache,
  identical to the crates.io .crate whose SHA-256 the lockfile recorded
  (ee6798b1), plus #4251's diff to src/net/tls/util.rs and a README with
  the provenance. The diff applies as upstream wrote it; its import
  context differs only because 0.8.6 takes `future` from futures_util.
- The root Cargo.toml and the fuzz workspace's Cargo.toml patch
  sqlx-core to it. Both lockfiles change only in dropping sqlx-core's
  registry source and checksum; the root one also lists the test's two
  dev-dependencies, already in the graph.
- lab/prism/Dockerfile copies vendor/ into the build stage: without it
  the image's build context no longer resolves.
- tests/sqlx_tls_readiness.rs runs sqlx-core's rustls client against a
  rustls server over an in-memory socket whose readiness it controls,
  polling by hand. One case frees the send buffer between the blocked
  write and the readiness poll; the other has the server send while the
  client waits to write and read nothing more until the client reads.
  Against unpatched 0.8.6 both stall (parked on read with no write waker,
  and on write with no read waker); with the backport both finish, and the
  server receives the request byte for byte.

Not changed: #770's `repolled` in import-audits stays, sslmode handling
(#713) is untouched, and the vendored crate's three upstream
mismatched_lifetime_syntaxes warnings are left as shipped.

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

* 3.x.x: guard the vendored sqlx-core patch and its advisories in CI (#771)

Review follow-up to the backport.

The patch. sqlx pins its sqlx-core with `=`, so moving sqlx to another
0.8.x leaves `[patch.crates-io]` unused: Cargo only warns, the unfixed
crates.io sqlx-core returns, and nothing in the fuzz workspace would
notice. scripts/check_vendored_sqlx_core.py fails unless, for the
repository and the fuzz workspace alike:
- Cargo.toml patches sqlx-core to vendor/sqlx-core;
- Cargo.lock holds one sqlx-core, with no source or checksum, at the
  vendored version;
- the locked sqlx is that version too (sqlx X requires sqlx-core =X), and
  its sqlx-core dependency names no other copy;
- the lock file does not record the patch under [[patch.unused]].
The lint job runs it beside the other check scripts.

Advisories. cargo-deny matches RustSec advisories only against registry
crates, so it stopped checking sqlx-core. Right after `cargo deny check`,
the cargo-deny job runs the same script with --require-advisory-db.
- The script finds the database cargo-deny fetched from deny.toml's
  db-path, or from --advisory-db / RUSTSEC_ADVISORY_DB.
- It lists every sqlx-core advisory there and fails on any that is not
  withdrawn and not named, with a one-line reason, in
  vendor/sqlx-core/reviewed-advisories.toml.
- The database of 2026-10-28 holds none, so the list is empty.
The vendored README explains both checks and what to do when an
advisory appears. tests/test_check_vendored_sqlx_core.py covers:
- a registry or hand-edited sqlx-core in either lock;
- sqlx moved past the vendored version, with the patch unused;
- a second sqlx-core;
- a missing or misdirected patch;
- unreviewed, reviewed, withdrawn and malformed advisories;
- the database's location;
- the CI wiring.

The test. Its sqlx-core dev-dependency is pinned to =0.8.6, with the
_tls-rustls-ring-webpki feature that sqlx's runtime-tokio-rustls
enables. Moving sqlx or the test's backend then fails resolution or the
test instead of testing another copy. The first case no longer asserts
that a drain finds no write waker. A drain now wakes one it finds, as an
I/O driver would, and the test requires at least one drain that found
none: that is the lost-wakeup window. The module comment states the
dependency on rustls 0.23.46's complete_io, and how to re-validate the
harness on a rustls bump. Against the unpatched util.rs both cases still
stall.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@RobertClarke
RobertClarke deleted the RobertClarke/prism-765-import-lock branch November 3, 2026 20:47
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