Skip to content

3.x.x: the load report says where accepted share acknowledgements' time went, split at ORDER_LOCK, with the WAL syncs and checkpoints behind it (#829) - #835

Merged
kiwidream merged 1 commit into
3.x.xfrom
orca/829-share-ack-stall
Nov 11, 2026
Merged

kiwidream merged 1 commit into
3.x.xfrom
orca/829-share-ack-stall

Conversation

@kiwidream

@kiwidream kiwidream commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Problem

#829: on 10-30, throughput-20k-window-1fe steady_state failed with shortfall 1,022 and a client ack p99 of 5,493 ms. The server's own histogram had 11,008 acks over 1 s, yet ORDER_LOCK's longest observed wait was 0.124 s, no pool acquire reached sqlx's 2 s WARN, and the frontend logged nothing.

The time went to a queue nothing measures. Each frontend admits at most max_connections - 1 = 15 share appends (ledger/append_admission.rs), so ORDER_LOCK waits are capped at about 15 × hold, and the rest of a slow ack waits on that semaphore, ahead of the pool and of PostgreSQL. The queue fills when the ORDER_LOCK section (the one-call append plus its COMMIT) runs below 500 shares/s for some seconds. Why that section slows (the WAL flush, the frontend runtime's turnaround to COMMIT, or the call itself) is what the existing artifacts cannot say.

A repeat on e97423d (run 41719750502) showed the same signature about 6× smaller (gate passed, ack p99 961.7 ms against 1,000). So did 10-28 on 2e11f1b and #779 item 2 on v3.0.0. The evidence and the hypotheses are in #829.

Change (harness only; no server change)

Each phase in load-harness-report.json gains two blocks, additively. Nothing the trend rows, the regression rule (#551) or scripts/ read is renamed or removed.

  • share_ack_accounting splits the accepted acks' summed seconds at ORDER_LOCK.
    • Measured:
      • accepted_acks: qbit_prism_share_ack_seconds, frontend clock.
      • order_lock_wait: database_advisory_lock_wait_seconds{lock="order",result="success"}, on PostgreSQL's clock for appends.
      • order_lock_hold_append: database_order_lock_hold_seconds{holder="append"}, frontend clock.
      • append_call: pg_stat_statements for qbit_prism_append_share(...), PostgreSQL executor.
      • pool_acquire: context only.
    • Derived, each naming its formula and every input's clock, and unknown when any input is:
      • in_call_after_grant = call − wait;
      • after_call = hold − in-call: COMMIT, its WAL flush and the runtime's turnaround;
      • before_lock_and_response = acks − wait − hold: the admission queue, the submit checks, the pool checkout, BEGIN and the response write, as a labelled remainder.
    • A negative difference (the inputs' populations disagree: holds and waits include refused appends, waits the rebuild paths') reads unknown with the disagreement, never as a time.
    • pg_stat_statements is read only if the phase's reset took on the same server, by pg_postmaster_start_time().
    • The deltas reuse the restart-aware segments of server_share_ack_seconds.
    • A failed scrape, an unbracketed restart or a server that doesn't declare the family reads unknown, never 0. A declared series not yet observed is a real zero.
  • database_counters gives per-phase deltas of pg_stat_wal (syncs, sync time and its mean, full-page images, bytes) and of the checkpointer's counters (PostgreSQL 16 pg_stat_bgwriter, falling back to 17 pg_stat_checkpointer).
    • Times are reported only when track_wal_io_timing was on at both reads; otherwise they are unknown, with the reason.
    • A primary that restarted or was replaced during the phase (pg_postmaster_start_time() changed) reads unknown.
  • database.track_wal_io_timing: the harness turns it on for its managed primary and standby only (two clock reads per WAL write or sync), so a promoted standby still times WAL. The report says this, and each phase says when the server it read had it off. Against --database-url the report says the setting is whatever the external database has.
  • database.checkpoint_log: for each server log the managed cluster wrote (primary, standby, rebuilt standbys), its checkpoint and restartpoint lines (log_checkpoints is on by default), the latest 1,000 per log, read a line at a time off the runtime.
  • Gate: a gated phase that fails gets one informational row saying where its acknowledgements' time went, as 3.x.x: gate the real-node smoke on a median it can support and print where a slow tip's time went (#790) #805 does for a slow tip. There is no new gate and no budget change, and a report without the accounting prints no row.

crates/qbit-prism-load/README.md documents the new fields, their formulas and clocks.

Trend note: from this PR on, managed runs pay track_wal_io_timing's two clock reads per WAL write or sync. That is negligible next to an fsync, and database.track_wal_io_timing marks the cutover in each report.

COMMIT is deliberately not read from pg_stat_statements. PostgreSQL commits and flushes WAL in finish_xact_command, after the extension stops timing the COMMIT statement. I checked this on a private PostgreSQL 16 with commit_delay=100000 and commit_siblings=0: five BEGIN; INSERT; COMMIT took 517 ms of wall time, while pgss recorded COMMIT as 5 calls and 0.004 ms in total. The report states this next to the accounting.

Tests run (minidev-alex1, through the host gate)

  • cargo test --locked -p qbit-prism-load --test harness passes: 155 tests, 7 of them new.
    • accounted_series_are_read_by_their_labels_and_unknown_is_not_zero: picks the series by exact labels; a declared-but-unobserved series reads zero; a restart's two segments are summed; a failed scrape, an unbracketed restart, an undeclared family or counters going backwards read unknown.
    • share_ack_accounting_derives_only_from_known_inputs: derived values check out arithmetically; pgss unknown leaves the call split unknown while the remainder before the lock stays known; a negative difference reads unknown with the disagreement, and a part derived from it names that input; a frontend missing a series leaves the sums unknown, not one frontend's number.
    • wal_and_checkpoint_deltas_keep_untimed_and_reset_distinct_from_zero: timing off leaves the syncs counted and their time unknown; counters going backwards, a replaced primary or a failed read read unknown.
    • a_failed_gated_phase_prints_its_ack_accounting_without_gating_on_it.
    • the_primary_log_keeps_only_its_checkpoint_lines: checkpoint and restartpoint lines only; an unreadable log is unknown, not an empty log.
    • The existing server_histogram_scrapes… and a_counter_reset… tests still pass.
  • cargo test --locked -p qbit-prism-load --lib --test churn --test compare passes (56, 6 and 50 tests).
  • With PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin:
    • cargo test --locked -p qbit-prism-load --test load_smoke passes. It now asserts the accounting is known wherever the acks are, that WAL sync time is measured on the managed primary, and that the checkpoint log was read. It also prints each phase's accounting line, e.g. warm_up: 378 acks, 3.3 s: … after the call (COMMIT, its WAL flush, the runtime's turnaround) 1.5 s (44%, derived). WAL: 585 syncs, mean 2.735 ms. There the flush (585 × 2.7 ms ≈ 1.6 s) accounts for the after-call time.
    • harness::a_managed_cluster_that_fails_to_start_reports_the_servers_own_reason passes (the cluster's start options changed).
  • cargo fmt --all -- --check and cargo clippy --locked -p qbit-prism-load --all-targets -- -D warnings are clean apart from the three known vendored sqlx-core warnings.
  • python3 scripts/check_prism_pool_acquires.py is ok. The server is untouched, so there are no new acquire sites or settings; check_prism_settings.py and generate_prism_alerts.py don't apply.
  • No new gated test; the gated list is unchanged.

What CI must cover

  • The full workspace tests, including load_smoke and the other gated harness tests on real PostgreSQL 16.
  • The run-load set on this PR's merge result: every nightly preset with the new blocks. throughput-20k-window-1fe is the one to read for PRISM load nightly: a scheduled run failed #829.

Refs #829

🤖 Generated with Claude Code


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

…me went, split at ORDER_LOCK, with the WAL syncs and checkpoints behind it (#829)

Each phase of load-harness-report.json gains share_ack_accounting: the
accepted acks' summed seconds, the ORDER_LOCK wait, the append's hold and
the one-call append's pg_stat_statements time, measured from histograms
the server already exports, and three parts derived by named formulas
(in the call, after the call, before the lock and the response), unknown
when any input is or when their populations disagree. database_counters
adds pg_stat_wal and checkpoint deltas, with WAL times only when
track_wal_io_timing was on; the harness turns it on for its managed
primary and standby. The report carries every managed server log's
checkpoint lines, and a failed gated phase gets one informational gate
row. COMMIT is not read from pg_stat_statements: PostgreSQL flushes after
the extension stops timing the statement. No server change.

Refs #829

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream kiwidream added the run-load Run the PRISM load nightly preset set on this PR's merge result (#549) label Nov 3, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 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-11-03T22:54:18.195093Z 6f0ec5a PR opened
ℹ️ 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.

@qbit-reviewer qbit-reviewer 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.

Approved: a complete review with no bugs found.

1 finding posted inline.

Worth a look

2. [low] server_replaced compares only pg_postmaster_start_time, which may miss a crash-restart that wipes the stats

crates/qbit-prism-load/src/measure.rs:1649

EP-OBSERVABILITY. In the WAL disk-full fault, the postmaster can survive and reinitialise in place (fault/disk.rs:394-415; the repo's own test log at disk.rs:612-615 shows 'all server processes terminated; reinitializing'). server_replaced (measure.rs:1649-1662) compares only the two pg_postmaster_start_time() strings. If they match, run.rs:1971-1984 reports append_call as known. Crash recovery clears pg_stat_statements and the cumulative stats. append_call would then count only post-crash calls. The small checkpoint counters can also pass the went-backwards guard, giving wrong deltas that are reported as known. Unproven: whether PostgreSQL 16/17 keeps PgStartTime unchanged across a crash reinitialisation, which depends on PostgreSQL's postmaster.c, not this repo. A human should check that. If it does stay unchanged, also compare pg_stat_wal.stats_reset (or a similar reset timestamp) at both reads.

let counters_after = measure::database_counters(&side).await;
// Its totals are the phase's only if the phase's reset took, on the
// server that is still the primary.
let append_call = if !statements_reset {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1. [low · nit] append_call (live pg_stat_statements) and the snapshot-served histograms cover different windows

crates/qbit-prism-load/src/run.rs:1971

EP-OBSERVABILITY. The pg_stat_statements reset (run.rs:1795) runs before the before-scrapes, and the read (run.rs:1983) runs after the after-scrapes and counters_after. Meanwhile, the server's /metrics serves ShareAck, OrderLockHold and LockWait from the health publisher's last snapshot (qbit-prism-server api/metrics_snapshot.rs:45-48). That snapshot refreshes every 2 s by default. Only is_live families such as PoolAcquire are rendered at scrape time (metrics/registry.rs:191-215). So append_call counts the phase's tail, the snapshot's age plus in-flight appends, but the wait and hold deltas miss it. The result is that in_call_after_grant = call - wait is biased up and after_call = hold - in_call is biased down. In a stalled phase, after_call can read 'inputs disagree'. Neither ACCOUNTING_DEFINITION (measure.rs:1800-1804) nor the README mentions this window mismatch. The skew is bounded and a negative difference already reads unknown, so this is minor; documenting it (or waiting for a fresh snapshot) would fix it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in #850, as its first commit (2d23558): the accounting's definition and the load-harness README now say that the share-ack, ORDER_LOCK hold and lock-wait histograms are served from the frontend's metrics snapshot while pg_stat_statements is reset and read live, so the call's figures can cover up to a snapshot's age more of a phase's tail, skewing in_call_after_grant up and after_call down by that much.

@kiwidream
kiwidream merged commit 00001ae into 3.x.x Nov 11, 2026
68 of 70 checks passed
kiwidream added a commit that referenced this pull request Nov 11, 2026
… their median tip, with the slowest tip at twice the budget (#842)

Three PR load runs failed a tip-notify gate on 11-03, one preset each, on
one tip each: 4,546 ms among tips whose nearest-rank median was 1,039 ms
(tip-delivery, #833), 4,860 ms among 1,005 ms (mainnet-shape-130, #835) and
3,826 ms among 569 ms (rental churn's churn tips, #834). The gated "p99 over
6 or 8 tips" is the slowest tip, so one tip stalled on a contended runner
failed the run. #790 hit the same on the real-node smoke, and #805 split its
gate.

The same split applies here. tip-delivery-2000-miners-400k-2fe-retarget and
its 500-address variant gate the median of their 8 tips at 2500 ms and the
slowest at 5000 ms; mainnet-shape-130-addresses and mainnet-shape-650-addresses
the median of their 6 at 3000 ms and the slowest at 6000 ms;
rental-churn-bursts-and-storms its 8 churn tips at 3000 and 6000 ms through a
new optional key, churn_tip_last_notify_median_budget_ms, validated like
#805's (finite and positive; absent or null is not gated). A preset whose
median budget is above its p99 budget is refused, for either pair. Its 2 warm-up tips
keep their 3000 ms p99 and no median: the nearest-rank median of 2 is the
faster one. The churn rows now go through the same check as the run's own
tip rows, and the report's preset block serialises every gate key.

The trade-off: a nearest-rank median of n tips is the ceil(n/2)-th fastest,
so a regression confined to fewer than half the tips (3 of 6, 4 of 8) that
lands between 1x and 2x the budget now passes. One that slows most tips
still fails the median, and a stall past twice the budget or an unserved
tip still fails the slowest-tip row. The dispatch override still sets only
the slowest-tip budget. A changed preset starts a new S6 baseline
(preset_sha256 is in the series key), so these five series are judged again
after min_baseline kept nightlies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
…he load report reads them, and a warning fires when appends queue for a slot (#829, #844)

Follows #835, which is merged. 3.1.2 doesn't wait for this PR. It also carries #844's alert on the append-slot queue, as its own commit after the stages it reads.

## Problem

#835's accounting attributed its own run-load occurrence of #829 (run 41734520778, `throughput-400k-window-1fe-async` steady_state, shortfall 2,784):
- 98.5% of 61,082 accepted-ack seconds sat **before ORDER_LOCK**, in a remainder nothing measures: the append-admission queue, the submit checks, the pool checkout and BEGIN, and the response write.
- ORDER_LOCK was saturated for roughly 50 s with holds of 2 ms or more, against 0.96 ms at saturation. WAL syncs (mean 0.184 ms) cover at most about a third of that.
- The rest of the extra hold is either **in the call** (full-page images after a checkpoint starts) or **in the frontend**, between the call's reply and COMMIT. The harness's pg_stat_statements split can't separate the two.

## Change

### Server: `qbit_prism_share_append_stage_seconds{stage,outcome}`

The histogram uses the ORDER_LOCK hold ladder (1 ms to 10 s) and records four stages:

| stage | from → to | outcomes | clock | where |
|---|---|---|---|---|
| `submit_checks` | `submit_share` entry → the append's `start` (readiness, fee, tip, the payout-revision read and its checkout, the fences) | `passed` | frontend monotonic | `coordinator/miner_submit.rs` |
| `admission` | the wait for one of the `max_connections - 1` append permits | `admitted`, `closed` (pool closed first), `cancelled` (dropped while queued: a drop guard records the time actually waited, EP-ERRORS) | frontend monotonic | `ledger/append_admission.rs` |
| `locked_call` | the one-call append's own `lock_held_us`, from its grant to its reply | `replied` | PostgreSQL `clock_timestamp()` | `ledger/window.rs` `append_called` |
| `commit` | the COMMIT round trip, either append path | `committed`, `failed` | frontend monotonic | `ledger/window.rs` `commit_gated` |

**No behaviour change on the share path:**
- **Outside ORDER_LOCK.** Each stage is recorded after it ends, never while ORDER_LOCK is held:
  - `commit` is recorded once COMMIT's reply or failure is in and the hold has ended. `commit_gated` now takes the hold's guard and drops it as COMMIT returns, so the recorded hold still ends where it did and neither stage's recording falls inside it;
  - `locked_call` once the transaction and its hold have ended, by COMMIT or the gate's ROLLBACK;
  - `admission` before the append's checkout.
- **Nothing new in the locked section** except the COMMIT round trip's two clock reads: no lock, await or allocation. Results, errors and their order are unchanged. `commit_gated` became a `&self` method to reach the registry.
- **Not recorded.** A refusal, a reply the ledger then rejects, a closed commit gate (no COMMIT sent), and a submission refused or abandoned during its checks all record nothing. EP-OBSERVABILITY: nothing is recorded as zero.
- **Fixed cardinality.** `AppendStage::outcomes` lists the pairs. The family declares its seven series at start as reserved keys with no samples, so recording allocates nothing (pinned in `metrics_allocation`) and a series appears on its first observation.
- **Docs.** The metric docs are `docs/prism-metric-metadata.json`, the regenerated `docs/prism-native-metrics.md` and a reading note in `docs/prism-metrics-histogram-consumers.md`. The two `Admission::acquire` sites keep their `non-database` classification in `scripts/prism_pool_acquires.json` under their new call text.

### Harness: the stages in `share_ack_accounting`

`ACCOUNTED_SERIES` adds the four series.

- **Measured** parts, each with its clock: `submit_checks`, `admission`, `locked_call` and `commit`.
- **Derived** parts, each naming its formula:
  - `hold_unattributed` = `order_lock_hold_append` − `locked_call` − `commit`, the hold the stages leave over. For a one-call append it is only microseconds, because nothing awaits between `granted()` and the COMMIT clock. What it carries is:
    - the hold of appends that record no `locked_call`: a block-bearing share's less its COMMIT, and the whole of one refused in its call;
    - failed COMMITs and closed gates' ROLLBACKs, because only committed COMMITs are subtracted.

    Its meaning says so, and the counts beside each figure show how many.
  - `before_lock_unattributed` = `before_lock_and_response` − `submit_checks` − `admission`: the Stratum handling, the append task's start, the block-only work, the append's pool checkout and BEGIN, the call's trip to its lock, its reply's trip back and the runtime's wake to it, and the response write.
- **Where the runtime's lag lands.** The hold the frontend records starts at the grant the call reports, counted back from when the frontend processes the reply. So the reply's trip back and the runtime's wake to it are in `before_lock_and_response`, although PostgreSQL holds the lock through them. The runtime's wake to COMMIT's reply is inside `commit`. `after_call` and the gate row no longer name a "runtime turnaround".
- **Unknown, never 0, against an older server.** A server without the family doesn't declare it, so every stage and every part derived from one reads unknown, with the reason. The split at ORDER_LOCK is unchanged. As before, a declared series that hasn't been observed is a real zero.
- **Gate row.** When the report has the stages, the informational row on a failed gated phase splits the remainder before the lock into submit checks, the admission queue and the rest. It then adds a sentence giving the append's hold and its split into the call's reported hold, COMMIT and the rest. A report without the stages prints the line as before.

The first commit is the doc fix for qbit-reviewer's nit on #835: the accounting's histograms come from the frontend's metrics snapshot while pg_stat_statements is read live.

### #844: `PrismShareAppendAdmissionWaitHigh`

A warning (no page label) on the `admission` stage. It fires when a frontend's admission-wait p99 over five minutes is above **1 s**, from at least **100** admissions in that window, and that holds for **10 minutes**. `scripts/generate_prism_alerts.py` builds the expression, dwell and texts from named constants, in a function of its own.

- **Threshold.** One second is the ORDER_LOCK hold ladder's boundary, `PrismShareAckP99High`'s bound and the load gate's.
  - At production's ~50 shares/s (about 25/s per frontend of the pair) an append holds its slot for milliseconds. A wait needs 15 appends in flight on one frontend, which takes an ORDER_LOCK hold of at least 0.6 s.
  - The load lanes' clean steady states acknowledge at a p99 of 3–8 ms. #829's occurrences queued for seconds: ack p99 5.5 s on 10-30 and 6.6 s in #835's run, while the 0.96 s repeat stays under.
- **Duration.** Ten minutes is twice the window. One landing's queue leaves the window five minutes after it forms, so a landing never warns on its own. At 25/s, a settlement would have to hold ORDER_LOCK for more than about 4.6 s even to lift the five-minute p99 over a second; 2.x.x's 4–5 s block minutes would. A queue that persists does warn.
  - Repeated landings are different. They warn when, in every five minutes for ten minutes, their holds' time beyond about 1.6 s adds up to more than about 3 s; for example, a hold over 2.2 s every minute.
  - With arrivals spread evenly, a hold under 0.6 s never fills the fifteen slots, and #602's R2 budget for settlement holds is 250 ms.
- **Outcomes.** All are combined. An append dropped at the share-commit deadline while it queued is counted as `cancelled` with the time it waited, so a hard stall still warns.
- **Absent series.** A frontend without the stage histogram (older than this PR) has no admission series and stays quiet. No-data and evaluation errors are OK, because the snapshot and no-data rules own missing measurements. A stale or unpublished snapshot suppresses the rule, since the family is served from the cached body.
- **Runbook.** A new subsection of `docs/prism-ledger-ops.md`, "Shares queued for an append slot (#844)". It reads, in order:
  1. arrivals;
  2. every ORDER_LOCK holder on every frontend;
  3. the append's `locked_call` and `commit`;
  4. the time no stage covers: the call's reply on its way back, the runtime's wake to it, an abandoned append's later ROLLBACK, and the connection's return to the pool with sqlx's release ping. `PrismRuntimeLagHigh` fires only above 2 s, while 0.6 s of lag fills the slots;
  5. WAL syncs and checkpoints;
  6. pool saturation.

  The load report's `share_ack_accounting`, `database_counters` and checkpoint log lines are the offline equivalent.
- **Deployment.** The review-only `docs/prism-alert-rules-qbit-tools.patch` is regenerated from the pinned qbit-tools templates (a007a142; sha256 matches `tests/fixtures/prism-deployed-alerts.json`). The rule reaches the pair at qbit-tools' next native-rule re-vendor.
- **Overlap.** #843's listener-down rule edits the same generated files. Whichever PR merges second merges 3.x.x in and regenerates.

### What it decides for #829
- `admission` + `submit_checks` against the old remainder say where the queue is.
- In the stall window:
  - `locked_call` rising with the full-page images means the call's work after a checkpoint starts. The next step would then be checkpoint spacing or `wal_compression` on the runner, or a production measurement.
  - `locked_call` and `commit` flat while ORDER_LOCK's waits imply longer holds means time inside the lock that no stage covers: the call's reply on its way back and the frontend runtime's wake to it. That time shows in `before_lock_unattributed`, and `runtime_poll_lag_seconds` names the runtime.
  - `commit` above pg_stat_wal's sync time means the COMMIT's round trip, the runtime's wake to its reply, or a COMMIT-path wait other than the fsync.

## Tests run (minidev-alex1, through the host gate)

- `cargo test --locked -p qbit-prism-server --lib -- ledger::append_admission metrics:: api::metrics_snapshot` passes: 83 tests. They include the new `the_admission_wait_is_recorded_however_it_ends`, which runs on a paused clock with a lazy pool and no PostgreSQL:
  - with 15 permits held, a 16th append waits 2 s and records `admitted` 2 s;
  - one aborted after 1 s records `cancelled` 1 s;
  - one queued when the pool closes records `closed` 0.5 s.
- `cargo test --locked -p qbit-prism-server --test observability --test metrics_allocation` passes (17 and 4 tests). The census pins the seven series (105 families, 1,114 populated series), and every stage outcome records allocation-free.
- PostgreSQL-gated, on a private PostgreSQL 16 with `PRISM_TEST_REQUIRE_INTEGRATION=1`; the gated list is unchanged:
  - `--test append_admission` passes (32 tests). `an_append_call_reports_its_lock_and_a_cancelled_one_rolls_back_whole` now asserts:
    - an append and a refusal are both admitted, but only the append records `locked_call` and `commit`;
    - the two cancelled calls are admitted and record neither;
    - the append's ORDER_LOCK hold covers its `locked_call` and `commit`.
  - `--test b602_order_lock_hold` passes (22 tests). `a_landing_records_each_order_lock_hold_under_its_holder` now asserts that the block-solving share submitted through `Coordinator::submit` records `submit_checks`, `admission` and `commit` once each, and no `locked_call` (it takes the statement path).
- `cargo test --locked -p qbit-prism-load --test harness` passes: 156 tests.
  - New: `the_server_append_stages_split_the_remainder_and_the_time_after_the_call`. The stages are read by their exact labels (`admission{outcome="cancelled"}` is ignored), and the derived parts check out arithmetically. An older server leaves the stages and `hold_unattributed` unknown (`locked_call is unknown: …`) while `before_lock_and_response` and `after_call` stay known. A declared, unobserved family is zero.
  - The gate-row test now also covers a report with the stages, the joins between the sentences included.
- With `PRISM_TEST_PG_BIN_DIR=/usr/lib/postgresql/16/bin`, `cargo test --locked -p qbit-prism-load --test load_smoke` passes against the real server. It now asserts that every stage is known and counted where shares were accepted. The two independent measures agree:
  - `warm_up`: `locked_call` 0.3 s against pg_stat_statements' derived in-call 0.3 s, and COMMIT 0.5 s against 598 WAL syncs × 0.762 ms (0.46 s); `hold_unattributed` is 0.0 s;
  - `churn`: `locked_call` 0.3 s against 0.3 s, and COMMIT 0.6 s against 1,119 syncs × 0.635 ms (0.71 s).
- `cargo fmt --all -- --check` and `cargo clippy --locked -p qbit-prism-server -p qbit-prism-load --all-targets -- -D warnings` are clean apart from the three known vendored sqlx-core warnings.
- `python3 scripts/check_prism_pool_acquires.py`, `python3 scripts/generate_prism_metrics.py --check`, `check_prism_settings.py`, `check_gate_env_reads.py` and `check_vendored_sqlx_core.py` all pass.
- After merging 3.x.x (which brought only docs and rulesets), `cargo test --locked -p qbit-prism-server --test observability` passes again: 17 tests. They include `native_rules_reference_only_inventory_families_for_their_role` with the new rule.
- #844's alert checks:
  - `python3 scripts/generate_prism_alerts.py --check` and `python3 scripts/check_prism_alert_uids.py` pass (46 UIDs).
  - `python3 scripts/test_prism_alert_deployment.py --snapshot <the two pinned templates>` passes: 10 Jinja gate combinations, 78 original / 80 proposed rules. The test now pins the new rule as a non-paging warning with a 10 m dwell and OK no-data.
  - `python3 scripts/test_prism_alert_promql.py --promtool <prometheus 3.14.0 promtool>` passes: 46 expressions, 214 scenarios, 438 expression and 333 alert assertions. As a negative control, the fourteen new scenarios rerun alone against the same expression with a 3 m dwell (`PrismShareAckP99High`'s) fail exactly the two pending cases, the persistent queue at 14m50s and the landing at 10 m.
  - Fourteen new scenarios cover:
    - a persistent queue firing at 20 m and still pending at 14m50s;
    - a ten-second landing that lifts the p99 but stays pending at 10 m and is gone by 20 m;
    - landings once a minute: two-second settlement holds stay quiet and three-second ones warn;
    - fast admissions;
    - a hard stall's `cancelled` waits;
    - a trickle below 100 admissions;
    - slow `locked_call` and `commit` alone;
    - stale and unpublished snapshots;
    - an absent family;
    - two frontends judged apart.

## What CI must cover

- The full workspace tests, including the release-mode `metrics_allocation` run and every gated server suite on real PostgreSQL 16.
- The `run-load` set on this PR's merge result. Every preset's `share_ack_accounting` then carries the stages; `throughput-20k-window-1fe` and `throughput-400k-window-1fe-async` are the ones to read for #829.

### Pre-push review (Opus, `/code-review xhigh`, three rounds)

None of the rounds found a correctness issue on the share path. The text findings are fixed in the last three commits. The most important was that hold − `locked_call` − `commit` cannot show runtime lag, so the part is now `hold_unattributed` and the runbook reads the lag where it lands.

Four points were left, deliberately:
- **`locked_call` is recorded beside the hold, not in the `OrderHold` guard.** Moving it would change `connect.rs` for exits that are rare: an error after the reply, or a drop during COMMIT at runtime shutdown. `hold_unattributed` documents that it carries such holds.
- **The rule is snapshot-gated, like `PrismShareAckP99High` and the advisory-lock rule.** A publisher stalled behind the database is owned by `PrismMetricsSnapshotStale`. Making the family live is a separate change.
- **The stage/outcome pairing is only `debug_assert`ed.** No caller passes an unlisted pair.
- **`AdmissionWait` keeps `tokio::time::Instant`,** which its paused-clock test needs.

Refs #829
Refs #844

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
2d23558 3.x.x: say that the share-ack accounting's histograms come from the frontend's metrics snapshot while pg_stat_statements is read live (#829)
42f25c0 3.x.x: the server times each share's submit checks, its wait for an append permit, its call's own ORDER_LOCK hold and its COMMIT, and the load report reads them (#829)
add8688 Merge remote-tracking branch 'origin/3.x.x' into orca/829-share-append-stages
347b318 3.x.x: warn when share appends queue for an append slot for ten minutes (#844)
845ec13 3.x.x: the append stages' texts say where the call's reply went and when a slot frees, and two landing cadences pin the slot-queue warning (#829, #844)
1e17a49 3.x.x: the hold the append stages leave over is hold_unattributed, not a runtime turnaround, and the runbook reads runtime lag where it lands (#829, #844)
e69b63d 3.x.x: the append-slot runbook reads arrivals, every holder and the time no stage covers, and the texts agree on the hold's remainder (#829, #844)
9ea60c2 Merge remote-tracking branch 'origin/3.x.x' into orca/829-share-append-stages

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 13, 2026
…the tip-delivery, mainnet-shape and churn presets gate their median tip (#842)

## The problem

On 2026-11-03 three PR runs of the `run-load` set each failed a tip-to-last-notify gate, each on a different preset. No nightly failed one on the same code. The triage for #842 found the runner, not the code. The findings are drafted as a comment on #842.

- **The trend tracks VM speed, not commits.**
  - No server or harness source changed between the 10-23 and 10-27 nightlies, or across 11-03, 11-04 and 11-11.
  - Each frontend's initial full refresh of the same seeded 416,260-row window took 6.5–17.9 s across the 39 preset runs examined. This is the frontend's `snapshot_ms` on its `trigger="initial"` refresh line.
  - Tip-delivery's median tip follows it over 13 runs at r = 0.87 (the gate's nearest-rank median), or r = 0.90 with the midpoint median.
  - Fast VMs give the same latency before 10-27 (572–624 ms) and after it (526–571 ms).
- **Each failure was one stalled tip on its own VM.** Medians are nearest rank, as the gate computes them.

| PR | Preset | Slowest tip / median tip | Where the time went |
|---|---|---|---|
| #833 | `tip-delivery-2000-miners-400k-2fe-retarget` | 4,546 / 1,039 ms | 1st tip: refresh 1.5 s plus 2.9 s of fan-out, on both frontends at once |
| #835 | `mainnet-shape-130-addresses` | 4,860 / 1,005 ms | 3rd tip: refresh 4.1–4.6 s. A PostgreSQL check query took 1.1–1.8 s on both frontends, with no checkpoint running |
| #834 | `rental-churn-bursts-and-storms` | 3,826 / 569 ms | 6th churn tip, after the 2,000-rental burst: refresh 2.1 s plus 1.7 s of fan-out |

- **The share-ack path degraded on the same VMs.** In each failing run, the phase holding the slow tip had a share-ack p99 of 71, 207 and 380 ms. The other 36 preset runs had 2–38 ms.
- **Nothing measured the VM itself.** No steal time, pressure stall or sampler gap was recorded, so a VM-level stall could only be inferred.
- **One stall fails the whole run.** The gated "p99 over 6 or 8 tips" is the slowest tip, nearest rank. #790 had the same problem on the real-node smoke, and #805 split that gate.

## The change, in two commits and a follow-up

### 1. Measure the host

The harness now reads `/proc/stat` and `/proc/pressure/{cpu,io,memory}` every `--process-sample-interval-ms` (new `contention` module).

- **Where the figures go:** a `host_contention` block per phase, and per tip in `time_to_usable_work` and each churn section.
  - A tip's window runs from the node's tip stamp to its slowest session's first usable job.
  - When some session never got the tip, the window runs to the next tip instead, covering the time those sessions were starved.
- **What each figure divides:**
  - `steal` and `iowait` are shares of the CPU time the kernel accounted.
  - The PSI figures (some and full) are shares of the harness's monotonic time from before one read of a file to after the next.
    That is the most the two totals can cover, so time the sampler loses around a read lowers a share and never raises it past what the kernel counted.
  - Each gives its share over the window and its worst interval.
- **Unknown stays unknown:** a host without PSI or without a steal field reports that figure as null with a reason, never 0.
  - CPU `full` is not read, because the kernel reports it as zero at the system level.
  - The run-level block records the steal counter at start. A counter still at 0 cannot tell an idle hypervisor from one that doesn't report steal, so the gate's lines carry that caveat when it reads 0.
  - The sampler takes one last read as the run stops, so the final interval and a late tip have a read after them.
- **Lock sampler:** it adds its longest gap between polls, with PostgreSQL's `clock_timestamp()` of the poll that ended it. A gap counts if its interval overlaps the phase, so a stall that began before the phase is still the phase's.
- **Gate:** a failed tip row, main or churn, gets one informational row. It shows the host over the slowest tip, over its phase, and that phase's longest sampler gap. `gate::tip_timeline` prints each tip's line.

All of it is additive to the report. An older report gates as before and simply gets no host row. A report without churn or a soak keeps its shape (the tips are reached with `pointer_mut`, not indexing). The top-level key is added to the load smoke's golden key list.

### 2. Gate the median tip and give the slowest tip room for a stall

This applies #805's split to the nightly presets with tip budgets.

| Preset | Median tip | Slowest tip (was) |
|---|---|---|
| `tip-delivery-2000-miners-400k-2fe-retarget` (and `-500-addresses`) | 2,500 ms | 5,000 ms (2,500) |
| `mainnet-shape-130-addresses`, `mainnet-shape-650-addresses` | 3,000 ms | 6,000 ms (3,000) |
| `rental-churn-bursts-and-storms` churn rows (8 tips) | 3,000 ms | 6,000 ms (3,000) |

- **New key for churn tips:** `churn_tip_last_notify_median_budget_ms`, optional and validated like #805's key (finite and positive; absent or null means not gated). A preset whose median budget is above its p99 budget is refused, for either pair.
- **Rental churn's warm-up row is not split.** Its 2 warm-up tips keep their 3,000 ms p99 and no median, because the nearest-rank median of 2 is the faster one.
- **One check for both:** the churn rows now go through the same check as the run's own tip rows.
- **The report records every gate:** its `preset.gates` block now serialises `preset::Gates` whole, so the median keys and `new_session_first_job_p99_budget_ms` are in it.
- **Docs:** the README gate table, the workflow's dispatch description and the scenario criteria say the same thing.

**The trade-off, plainly:**
- **Now passes:** a regression confined to at most half the tips that lands between 1× and 2× the budget. A nearest-rank median of n tips is the ceil(n/2)-th fastest, so that is up to 3 of 6 or 4 of 8. Examples: only the first tip after a frontend start, or only churn's burst tip.
- **Still fails:**
  - The median, when a regression slows more than half the tips.
  - The median, when the run delivered fewer tips than it planned (see the follow-up below).
  - The slowest-tip row, on a stall past twice the budget or a tip some session never got.
- **Run against 11-03's three failures:** their medians (1,039 / 1,005 / 569 ms) and slowest tips (4,546 / 4,860 / 3,826 ms) all pass.
- **The trend restarts for these presets:** a changed preset starts a new S6 baseline (`preset_sha256` is in the series key). These five series are judged again after `min_baseline` (5) kept nightlies.
- **The dispatch override is unchanged:** the `tip_last_notify_p99_budget_ms` input still sets only the slowest-tip budget. The medians and churn budgets stay the preset's own, and the input's description now says so.

The commits are ordered so the first can land without the second if the gate change is not wanted.

### 3. Follow-up: a split gate passes only a run that delivered every planned tip

An independent verify found two gaps in commit 2.
- **F1, a run with too few tips passed.** Nothing checked the tips delivered against the plan; `external_tips_unminted` was reported but never gated. The nearest-rank median of 2 tips is the faster one, so tip-delivery passed a run that delivered 2 of its 8 tips with one at 4,900 ms. The old single 2,500 ms budget failed it.
- **F2, wording.** Exactly half the tips slow (4 of 8 at 4,900 ms) passes the median. This body said "fewer than half". The rule stays (it is #805's nearest rank) and the wording now says "at most half passes, more than half fails", as the README's table already did.

**The rule:** where a median budget is gated, the median row is measured only over every tip the run planned.
- **Main rows:** each phase now reports `external_tips_planned` beside `external_tips_unminted`. The gate sums them, and when the report holds fewer tips the row reads, for example, "unmeasured: 7 of 8 planned tips delivered, 1 held unminted behind a landing" and fails.
- **Churn rows:** the same check, against the section's `plan.tips_at_seconds`, which reports have carried since #521.
- **A report that does not record its plan** has an unmeasured median, which fails.
- **Unchanged:** the p99 rows, and every preset without a median.

**Why this rule:** it is the narrowest one that is exact.
- `external_tips_unminted == 0` alone misses a real node's mint that failed or never reached the watcher, since `observed_mints` drops those without counting them.
- A per-preset minimum tip count would add a key to keep in step with `--external-tips`.
- The planned count catches every way a tip goes missing, adds no preset key, and applies only where a median can hide a missing tip.

**The A/B summary:** it re-gates each base run on the candidate's preset.
- A base harness older than this follow-up records no plan, so every base run would have failed a median-gated preset, and a candidate regression would have read "as does a base run".
- When no phase records the plan, `compare` now fills it from the pinned `--external-tips`, which it already holds every counted run's tip list to.
- **After landing:** add `external_tips_planned` to `legacy-flags.json`'s `report_fields`, with the landed squash commit as `introduced`, so a newer build that drops the key is caught rather than filled. The commit is not known until squash-sign, so it can't be done in this PR.

**Not changed, by choice:**
- p99-only presets don't check the plan.
- The bridge script's tip p50 is reported over delivered tips only, and gates nothing.

## Tests run

All on this branch, through the host's build gate:
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --locked -p qbit-prism-load --all-targets -- -D warnings`: clean, apart from the three known vendored sqlx-core warnings.
- `cargo test -p qbit-prism-load --test contention`: 15 passed.
  - Parsers against real and truncated lines, plus this host's own `/proc/stat`.
  - Unknown versus a real zero for a host without PSI or a steal field, and a counter that went backwards.
  - Window math, and the tip annotation, including an unserved tip whose window runs to its replacement.
  - The lock sampler's gap, including one that straddles a window's start.
  - The sampler's final read, and the steal caveat.
  - A sampler preempted around a pressure read (the share stays at or below what the kernel counted), and the stamps on both sides of a read.
  - The gate rows: shown only on a failed tip row, absent for an old report, and pointing at an unserved tip.
- `cargo test -p qbit-prism-load --test realism`: 24 passed. #805's preset test is now `presets_gate_the_tip_median_only_where_they_split_it_from_a_stall_budget`, which covers both median keys, their refusals (including a median above its p99) and null. It is not cited in the deleted-test map, which covers 2.x.x files only.
- `cargo test -p qbit-prism-load --test churn`: 7 passed. The new churn median test uses #834's eight churn tips.
- `cargo test -p qbit-prism-load --lib --test harness --test compare --test legacy_flags --test soak_plan --test faults -- --test-threads=4`: 56, 155, 50, 3, 5 and 1 passed. Without `PRISM_TEST_PG_BIN_DIR`, the PostgreSQL-gated tests in `harness` pass without running.
- `python3 scripts/check_e2e_scenarios.py` and `python3 scripts/check_prism_pool_acquires.py`: pass.
- The first commit alone also passes clippy and the contention, realism and churn tests, so it can land without the second.
- All of the above was rerun after merging `origin/3.x.x` (#833 and #834).

No load preset was run locally.

**For the follow-up (commits after d96b217):**
- `cargo test --locked --offline -p qbit-prism-load --lib --test realism --test churn --test contention --test compare --test harness -- --test-threads=4`: 56, 26, 7, 13, 51 and 155 passed. The new tests:
  - `realism`: `a_tip_median_is_measured_only_over_every_tip_the_run_planned` (a 2-of-8 run with one tip at 4,900 ms fails, a tip held unminted fails, a report without the plan fails, a short run with an unserved tip names both reasons) and `a_tip_median_passes_a_slowdown_on_half_the_tips_and_fails_one_on_more`.
  - `churn`: 2 of 8 churn tips delivered fails the median, and a section without its plan fails it.
  - `compare`: `a_base_report_predating_the_tip_plan_is_held_to_the_pinned_tips`.
  - `harness`: the ordered-tips runs record `tips_planned` 3, including the run with one tip held unminted.
- `cargo fmt --all -- --check`: clean. `cargo clippy --locked -p qbit-prism-load --all-targets -- -D warnings`: clean, apart from the three known sqlx-core warnings.

## Landing note: merging with #845

#845 (`orca/817-alerts-check-and-report-gates`) lands first. Merged with this branch, `cargo test -p qbit-prism-load --lib` fails to compile: E0063, a missing `churn_tip_last_notify_median_budget_ms` in #845's two `Gates` literals in `preset_report_tests` (run.rs, near L5876 and L5904).
- **Don't use `None` in both literals.** With `None`, #845's `every_gate_set` still passes when the new key is dropped from the report.
- **`every_gate_set` needs `Some(non-default)`** for the new churn median key, as its own doc says ("each value differs from its default"). `the_side_report_carries_every_gate_key` then catches a dropped key.
- **The golden key file should also cover `preset.gates`.** `tests/golden/fake_side_report_keys.json` pins only the `top_level`, `node`, `topology`, `versions` and `window` keys, so it would not catch a regression in the gates block either.

## What CI must cover

- **`load_smoke`** (PostgreSQL-gated) is the only end-to-end proof of the wiring in `run.rs`. Its golden key set now includes `host_contention`. It now asserts, against a real run, that:
  - every phase has host intervals, with steal and iowait measured on Linux;
  - each PSI figure is measured or unknown with a reason;
  - the lock sampler's gap is present;
  - every driven tip, main and churn, carries a `host_contention` block naming its phase.
- **`cargo test --workspace --all-targets`** picks up the new `tests/contention.rs`.
- **Not touched:** server code, settings and metrics. The workflow edit is the dispatch input's description only, which `main` picks up at its next sync of the nightly workflow.

Refs #842

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
6aac948 3.x.x: the load report says what the host was doing over each phase and each tip's delivery (#842)
b428e5f 3.x.x: the nightly tip-delivery, mainnet-shape and churn presets gate their median tip, with the slowest tip at twice the budget (#842)
d96b217 Merge remote-tracking branch 'origin/3.x.x' into orca/842-load-notify-latency
b53688c 3.x.x: a split tip gate passes only a run that delivered every planned tip (#842)
6859982 3.x.x: the A/B summary holds an older base report's tip median to the pinned tips (#842)
189e1a2 3.x.x: the A/B tip-plan fill-in leaves a report without a phase list as it is (#842)
3dcce7e 3.x.x: a PSI share divides by the time from before its first read to after its second (#842)

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

run-load Run the PRISM load nightly preset set on this PR's merge result (#549)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant