Skip to content

Keeper: split latest_snapshot_meta into mark and pending-apply context - #107321

Merged
antonio2368 merged 6 commits into
masterfrom
keeper-split-latest-snapshot-meta
Jun 15, 2026
Merged

antonio2368 merged 6 commits into
masterfrom
keeper-split-latest-snapshot-meta

Conversation

@antonio2368

@antonio2368 antonio2368 commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

IKeeperStateMachine::latest_snapshot_meta served two conflicting roles: the high-water mark reported to NuRaft via last_snapshot (must never regress) and the per-install validation token stamped unconditionally by save_logical_snp_obj. The unconditional stamp let a stale or duplicated install regress the reported metadata below snapshots already on disk — so zk_latest_snapshot_size and last_snapshot could move backwards, and a same-index local create could truncate a registered snapshot file in place while it was still being streamed to a peer or to S3 (an outstanding pin prevents deletion and cross-disk moves, but not an in-place WriteMode::Rewrite of the same path). A naive "stamp only if the index grows" fix is wrong: it reintroduces silent divergence when a higher-index install is saved but never applied and a new leader then re-installs a lower index.

This splits the roles. A new pending_snapshot_to_apply holds the per-install context — stamped on save, validated by apply_snapshot on (last_log_idx, last_log_term) identity, consumed on every exit — and may target any index. latest_snapshot_meta becomes monotonic, advanced only via advanceLatestSnapshotMeta. Retention now protects the file backing the mark, a displaced apply not covered by local commits fails closed instead of silently skipping, the create path adopts an already-registered same-index snapshot instead of rewriting it, and snapshot-file registration is collision-safe. Node-local change: no wire or on-disk format change, and init rebuilds the mark from disk on start.

Follow-ups left out of scope: a same-index re-receive can still rewrite the registered file in place (receive-to-temp + rename); the adopt path does not re-read file metadata; snapshots_to_keep = 0 deletes all snapshots at startup. Implemented with assistance from Claude.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fixed a bug in ClickHouse Keeper where the snapshot metadata reported via last_snapshot (and zk_latest_snapshot_size in mntr) could move backwards after a stale or duplicated snapshot install, which could also let a same-index local snapshot overwrite a registered snapshot file in place while it was still being streamed to a peer or uploaded to S3.

Version info

  • Merged into: 26.6.1.818

antonio2368 and others added 4 commits June 12, 2026 11:38
…and pending-apply context

`save_logical_snp_obj` unconditionally stamped `latest_snapshot_meta` (reported via
`last_snapshot`), so a higher-index save arriving between a lower-index save and its
apply made `last_snapshot` report an index whose apply was never delivered.

- Split into a monotonic `latest_snapshot_meta` high-water mark (advanced only through
  `advanceLatestSnapshotMeta`: init / create win / adopt / apply completion) and a
  per-install `pending_snapshot_to_apply` stamped by `save_logical_snp_obj` and
  consumed by identity in `apply_snapshot`.
- Displaced-apply coverage gate: covered by local commits -> skip success; uncovered ->
  fail closed with `LOGICAL_ERROR` (NuRaft exits, `init` recovers from the displacing
  install, which is fully saved on disk).
- Collision-safe canonical-returning `registerSnapshotFile`; retention pin via
  `setProtectedSnapshotIndex` plus a just-written pin so the mark-backing file stays
  servable (worst case `snapshots_to_keep` + 2 files).
- Identity-strict (last_log_idx, last_log_term) checks before every destructive step;
  the create-path same-index case adopts the registered file or fails closed instead
  of rewriting registered bytes in place.
- 13 new unit tests in `KeeperMemorySnapshotApplyTest`; test-only
  `KeeperContext::setLatestSnapshotDisk` for the two-disk layout.

Co-Authored-By: Claude Fable 5 <[email protected]>
LOGICAL_ERROR aborts in debug/sanitizer builds, so no test may trigger it.
The removed tests covered apply_snapshot contract violations that are
unreachable through NuRaft's single save->apply call site.

Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts:
#	src/Coordination/KeeperStateMachine.h
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [90a907a]

Summary: ❌

job_name test_name status info comment
Bugfix validation (integration tests) FAIL
test_keeper_snapshot_rotation_race/test.py::test_stable_recovery_under_write_load FAIL cidb

AI Review

Summary

This PR splits Keeper snapshot state into a monotonic latest_snapshot_meta mark and a per-install pending_snapshot_to_apply, then updates retention, same-index registration, and snapshot-apply validation around that split. I reviewed the current diff, prior discussion, and the affected Keeper snapshot paths; I did not find a new high-confidence blocker or major issue that warrants an inline comment.

Missing context / blind spots
  • ⚠️ Most current PR checks were still pending at review time; successful Fast test, build, and bugfix validation runs would close the runtime-validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 12, 2026
@antonio2368 antonio2368 changed the title Keeper: split latest_snapshot_meta into a monotonic high-water mark and a per-install pending-apply context Keeper: split latest_snapshot_meta into mark and pending-apply context Jun 12, 2026
@antonio2368 antonio2368 removed their assignment Jun 12, 2026
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
antonio2368 and others added 2 commits June 15, 2026 08:30
- Single-pass `removeOutdatedSnapshotsIfNeeded` retention loop.
- `validate_pending_snapshot_to_apply` reads the guarded members via `[&]` +
  `TSA_REQUIRES(snapshots_lock)` instead of taking them as parameters.
- Reword/trim comments; narrow `snp_size` scope in the create path.
- Refuse to adopt or return a snapshot file while a same-index receive is in
  progress (`snapshot_receive_ctx->log_idx`).
- Restore the `existsFile` probe in the create skip branch alongside the new
  receive-in-progress guard (the suggestion had replaced it; both are needed).
- Protect the saved-but-not-yet-applied install's index from retention until
  `apply_snapshot` consumes it, so a concurrent local create cannot advance the
  mark and prune the pending file before apply reads it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…plit

The test forces snapshot rotation expecting the leader to drop a snapshot a
recovering follower still needs, and hard-asserts both the pin-miss deferral
(`KeeperReadSnapshotDeferred`) and the later removal of the received snapshot.
Both require the snapshot the leader advertises via `last_snapshot` to be
retired mid-transfer. With the high-water mark now monotonic and its backing
file protected from retention, the advertised snapshot stays available, so the
deferral never fires and the received snapshot is not removed -- the test
asserts pre-fix behavior and cannot pass without reverting the fix. Recovery
coverage remains in `test_stable_recovery_under_write_load`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 546/625 (87.36%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@antonio2368
antonio2368 added this pull request to the merge queue Jun 15, 2026
Merged via the queue into master with commit be7fe6c Jun 15, 2026
164 of 166 checks passed
@antonio2368
antonio2368 deleted the keeper-split-latest-snapshot-meta branch June 15, 2026 13:11
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 15, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jun 25, 2026
Brings the locking branch up to current master, which now contains the merged
snapshot-metadata split (PR ClickHouse#107321). Conflicts in
src/Coordination/{KeeperSnapshotManager.{cpp,h},KeeperStateMachine.cpp} were resolved
by keeping the birth-unique-names architecture and folding in the one new upstream
commit on these files, ebe29b9 ("Address review feedback on the snapshot
metadata split"):

- Port the pending-install retention pin (protected_pending_snapshot_log_idx +
  setProtectedPendingSnapshotIndex): a saved-but-not-yet-applied install's file is
  not the mark, so a concurrent local create could advance the mark and prune it
  before apply reads it. Set in the save tail, released in the apply SCOPE_EXIT;
  added as a third pin in detachOutdatedSnapshotsIfNeeded (worst case keep + 3).
- Adopt the single-pass retention loop, keeping the deferred-unlink return-the-pins model.
- Restore the existsFile probe in the create skip branch (keeps the old
  getLatestSnapshotInfo contract feeding the S3/shutdown upload paths).
- Adopt the [&]() TSA_REQUIRES(snapshots_lock) form of validate_pending_snapshot_to_apply.

Deliberately NOT ported: the "refuse to adopt while a same-index receive is in
progress" guard. Its premise is in-place truncation of the registered file, which
cannot happen under birth-unique names (a same-index receive writes its own unique
file and adopts the existing entry on publish), so the guard would be dead code.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Brings the locking branch up to current master, which now contains the merged
snapshot-metadata split (PR ClickHouse#107321). Conflicts in
src/Coordination/{KeeperSnapshotManager.{cpp,h},KeeperStateMachine.cpp} were resolved
by keeping the birth-unique-names architecture and folding in the one new upstream
commit on these files, ebe29b9 ("Address review feedback on the snapshot
metadata split"):

- Port the pending-install retention pin (protected_pending_snapshot_log_idx +
  setProtectedPendingSnapshotIndex): a saved-but-not-yet-applied install's file is
  not the mark, so a concurrent local create could advance the mark and prune it
  before apply reads it. Set in the save tail, released in the apply SCOPE_EXIT;
  added as a third pin in detachOutdatedSnapshotsIfNeeded (worst case keep + 3).
- Adopt the single-pass retention loop, keeping the deferred-unlink return-the-pins model.
- Restore the existsFile probe in the create skip branch (keeps the old
  getLatestSnapshotInfo contract feeding the S3/shutdown upload paths).
- Adopt the [&]() TSA_REQUIRES(snapshots_lock) form of validate_pending_snapshot_to_apply.

Deliberately NOT ported: the "refuse to adopt while a same-index receive is in
progress" guard. Its premise is in-place truncation of the registered file, which
cannot happen under birth-unique names (a same-index receive writes its own unique
file and adopts the existing entry on publish), so the guard would be dead code.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants