Skip to content

Protect TOAST values needed by shadow replication - #351

Merged
serprex merged 1 commit into
mainfrom
shadow-horizon-pin
Nov 26, 2026
Merged

serprex merged 1 commit into
mainfrom
shadow-horizon-pin

Conversation

@serprex

@serprex serprex commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

PostgreSQL can vacuum TOAST values before walshadow reads them.
Hold back source cleanup while replication still needs those values.
Check once a second so cleanup can resume promptly, and improve
read-ahead so fewer writes wait for TOAST reads.


Note

High Risk
Changes replication feedback, manifest schema, and vacuum behavior cluster-wide while lagging; mis-pinned or released xmin can still lose TOAST values or bloat the source.

Overview
Adds [toast] source_horizon_pin (default on in shadow mode) so walshadow tells PostgreSQL via hot-standby feedback xmin which row versions to keep until the resolved floor advances. A new HorizonPin tracks samples from WAL running_xacts and a 1 Hz sidecar SQL sampler (pg_snapshot_xmin + insert LSN); the stream pump sends feedback when xmin changes, seeds from slot/saved manifest horizon_xmin, and clears the pin when disabled.

Resume manifests now persist horizon_xmin so restarts can re-hold the same horizon (especially with a physical slot).

Read-ahead / planning is tightened: speculative reads are dropped only for reservations below the commit LSN; chunk births in the committing transaction invalidate earlier read-aheads for those value IDs; prescan treats same-transaction (and linked subxact) TOAST births as resolving from WAL, not shadow. Shadow replay polling starts faster and backs off.

Adds shadow_toast_horizon bench plus integration tests for VACUUM during outage with/without pin, and expands architecture/docs/plans around partial reclamation fencing and future spill work.

Reviewed by Cursor Bugbot for commit 9a46ea0. Bugbot is set up for automated code reviews on this repo. Configure here.

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on a692688. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer

security-ai-gate-reviewer Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

AI review gate — auto-approved

9a46ea0d477d is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.

History (latest 5 heads, newest first)

  • 9a46ea0d477d approved — green: Cursor Bugbot
  • bfe63d7cf821 approved — green: Cursor Bugbot
  • a0747c50e312 approved — green: Cursor Bugbot
  • 7a45844cf053 approved — green: Cursor Bugbot
  • 652612467a6b approved — green: Cursor Bugbot

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on 6526124. Details in the approver's comment on this pull request.

@harshil-goel

Copy link
Copy Markdown
Contributor
  - What happens: with no slot xmin, horizon_pin_seed holds pg_snapshot_xmin of the current snapshot. The stream resumes from the manifest floor, which can be well behind that.
  - Why the seed can't be fixed later: samples between the floor and now arrive afterwards, but advance only raises the pin, so it never drops back to them.
  - Effect: transactions with xids between the floor's horizon and now have committed. Rows they killed are dead but may not be vacuumed yet, and the new pin lets VACUUM or pruning remove them immediately. Pending rows that reference those values then come back NULL.
  - Your setup: without a slot, walsender's MyProc->xmin is cleared on disconnect. So every daemon restart or crash loop opens this window.
  - Fix: persist the sent xmin in the manifest next to the floor. On boot, seed with the lower of that and the current oldest running xid, clamped to next - max(age(datfrozenxid)). The author's plan lists "save xmin in the resume manifest" but only for source crashes. It also applies to walshadow restarts with no
    slot.

  2. Samples from an old primary survive a failover within a session (session.rs:1685, :2065, source_recovery.attempt) 
  - What happens: the HorizonPin lives in the filter and outlives feed replacement (endpoint swap, redial, crossing). The old feed's sidecar samples are keyed by the old primary's insert LSN and can sit past the point where walshadow's stream stops.
  - Effect: after an async failover, LSNs past the switchpoint on the new timeline are a different history. Once the floor passes such a sample, the pin rises to an old-primary xid.
    - If that xid is ahead of the new primary's next xid, TransactionIdInRecentPast (walsender.c) silently rejects every feedback.
    - Otherwise the pin sits above xids the new primary reissues, and those transactions' deletions aren't held.
    - Either way the pin never moves back, so it doesn't recover by itself.
  - Not affected: a new session builds a new pin, so restarts are safe from this one.
  - Fix: when feed changes, discard samples above stream.next_lsn().
    
  3. A standby source pins nothing unless the standby has hot_standby_feedback = on (session.rs:1016)
  - What it means: this only matters if walshadow streams from a read replica instead of the primary. VACUUM runs on the primary, and the replica forwards walshadow's xmin upstream only if its own hot_standby_feedback is on. Otherwise XLogWalRcvSendHSFeedback (walreceiver.c) sends an invalid xmin.
  - Effect: the pin silently does nothing and nothing warns. If you stream from the primary, this doesn't apply.
  - Fix: on connect, if pg_is_in_recovery() is true and hot_standby_feedback is off, warn.

  4. Sidecar failures are silent (source_feed.rs:301) 
  - What happens: open_sql_client(..).ok() and query errors both just continue or reset the client, with no log or metric.
  - Effect: with a bad pg_hba entry for non-replication connections, or max_connections reached, the sampler redials every second forever. The pin falls back to running-xacts records every 15s, and nothing shows why.
  - Fix: warn on the first failure, and log at info when it recovers.

  5. Pin-change sends ask for a reply and push back the timed status (source_feed.rs:425)
  - What happens: a pin change calls send_status(status, true), which sends a full 'r' with a reply requested and resets last_status.
  - Effect: while the floor advances, each pin change triggers a source keepalive, and the regular timed status keeps getting deferred.
  - Fix: on a pin change, send only the 'h' frame and leave last_status alone.
 
  6. Unpinned sessions re-send the 0 release on every status (source_feed.rs:546, session.rs:1840) 
  - What happens: every deployment, including non-shadow modes, sends 'h' with 0 on each status. Each one goes through PhysicalReplicationSlotNewXmin, which takes the slot spinlock.
  - Fix: the release is only needed once per connection. Send it once, then skip it while horizon_sent == Some(0).
  
  7. born_in compares subxact xids, so read-ahead reads values born earlier in the same transaction (xact_buffer.rs:2871)
  - What happens: TOAST chunks are inserted under the current subxact's xid, so a pointer-only UPDATE in a later savepoint carries a different xid and born_in returns false.
  - Why it can't tell: prescan returns early for non-heap records (xact_buffer.rs:2969), so it never sees commit records and can't link a subxact to its parent.
  - Effect: the read waits on replay, takes a slot in the read-ahead pool and its budget, and then the planner discards it via forget(key, commit_lsn). It costs capacity, not correctness. ORMs and plpgsql exception blocks hit this often.
  - Fix: treat a birth as "own" while its xid hasn't ended, removing it on commit or abort. This works because no other transaction can see an uncommitted value.
  
  8. Replay polling starts at 1ms per read (shadow_store.rs:26)
  - What happens: each waiting read polls bridge.replay_lsn() on its own, at 1, 2, 4, 8, 16 then 20ms. 
  - Size: concurrency is capped at AHEAD_READS = 8, so the cost is at most about 5 extra bridge calls per read in its first ~30ms, and those compete with catalog reads for bridge workers. That's minor.
  - Fix: one shared replay watermark, so a waiter whose target LSN has already been reached skips polling.

  Later: export metrics for the held xmin, its age, and sampler failures.

@serprex

serprex commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Why 8 is dismissed: current code already reads first and polls replay only after the worker refuses the read.
- Small gain: a shared watermark as proposed saves at most one replay_lsn call per refused read.
- Risk: after a shadow restart rewinds replay, a stale-high watermark would burn the two-retry budget and turn a wait into an error.
- Real fix is bigger: cutting the polls properly needs a single shared poller, which is a lot of machinery for something minor.

@serprex

serprex commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

did 1-7: (edit: 1-6)

  1. added field to manifest, this is best effort
  2. serious issue, SourceFeed starts on None to reset this
  3. not too important, but simple fix. we set hot_standby_feedback for clickpipes already
  4. added log
  5. doesn't seem serious, fixed
  6. makes sense, fixed
  7. not too worried about subxact perf, but fixed since we already have necessary info handy

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on 7a45844. Details in the approver's comment on this pull request.

@serprex

serprex commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

upon closer review, 7 was costing too much. 150 lines for an optimization for subtransactions which all transactions had to pay. new code is +75/-118 relative to old code:

  • Reviewer's design: treated a value as "own" while its transaction looked unfinished. Batches are scanned in parallel, so a commit could be seen late. A reference from another transaction would then skip a read-ahead it needed.
  • New version: only compares parents that WAL itself states. A missing link falls back to the old exact-xid check, so it can only issue a read-ahead it didn't need. That is the pre-review behaviour, never worse.

Cost to transactions without savepoints:

  • One toplevel_xid != 0 check per prescanned record.
  • One opcode check per Xact record, with no lock or parsing. Assignment records only exist once a transaction passes 64 subtransactions.
  • When the birth xid and referring xid differ, two lookups in a map that stays empty.
Details 7: Reverted the version that tracked commits and aborts. It parsed every commit under a shared lock to help only savepoint workloads, and because batches are scanned in parallel, a late-seen commit could make it skip a read-ahead another transaction needed. Read-ahead is only a prefetch, so neither version could return a wrong value; this was purely a cost trade. Now a savepoint's value counts as its transaction's own only when WAL names the parent: the toplevel xid on a subtransaction's first record at wal_level=logical, or XLOG_XACT_ASSIGNMENT. Transactions without savepoints pay one integer check per record. A missing link falls back to the exact-xid check, so the worst case is the old wasted read-ahead. At wal_level=replica with fewer than 64 subtransactions nothing changes.

@serprex
serprex force-pushed the shadow-horizon-pin branch 2 times, most recently from 28ad419 to 70d61b3 Compare November 26, 2026 03:17
@serprex serprex changed the title Shadow horizon pin Protect TOAST values needed by shadow replication Nov 26, 2026

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 70d61b3. Configure here.

Comment thread src/source/source_feed.rs Resolved
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on a0747c5. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on bfe63d7. Details in the approver's comment on this pull request.

PostgreSQL can vacuum TOAST values before walshadow reads them.
Hold back source cleanup while replication still needs those values.
Check once a second so cleanup can resume promptly, and improve
read-ahead so fewer writes wait for TOAST reads.

@security-ai-gate-reviewer security-ai-gate-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.

Auto-approved by the AI review gate on 9a46ea0. Details in the approver's comment on this pull request.

@serprex
serprex merged commit ad35a88 into main Nov 26, 2026
25 checks passed
@serprex
serprex deleted the shadow-horizon-pin branch November 26, 2026 14:14
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.

2 participants