Skip to content

Reduce MVCC scan memory during Raft recovery - #1604

Open
bootjp wants to merge 1 commit into
mainfrom
feature/raft-gc-replay
Open

bootjp wants to merge 1 commit into
mainfrom
feature/raft-gc-replay

Conversation

@bootjp

@bootjp bootjp commented Dec 3, 2026 •

Copy link
Copy Markdown
Owner

Summary

A live CPU sample during a Raft cold start showed both transaction-decision GC and Redis fence GC applying entries in Pebble forward scans. Those scans remembered every visited logical key, including tombstoned keys, while looking for as few as one visible row. Rehashing the visited-key map consumed a large share of CPU samples.

Keep only visited prefixes that could still occur at the current physical iterator position. Retain nested prefixes when binary extensions interleave with another key's MVCC versions. The same scan visits the same records and preserves tombstone, expiration, GC, and apply semantics.

Validation

  • New regression coverage exercises nested and late-arriving prefixes. Existing Pebble scan tests cover interleaved versions, tombstones, and prefix extensions.
  • On a disposable Pebble DB with 100,000 deleted transaction locks, the median of three runs for an empty drain scan improved from about 37.3 ms to 22.3 ms and from 11.9 MB to 2.5 MB allocated per scan. This benchmark isolates the sampled hot path from the rest of recovery.
  • Targeted store, GC, and Raft cold-start tests passed. Repository lint reported zero issues.

Summary by CodeRabbit

  • 改善
    • データ走査時の重複判定を効率化しました。
  • テスト
    • 走査結果の正確性を確認するテストと、空の結果を返すケースの性能を測定するベンチマークを追加しました。

Signed-off-by: bootjp <contact@bootjp.me>
@coderabbitai

coderabbitai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

前方走査で訪問済みキーを追跡する方法を、ユーザーキーのマップからプレフィックス追跡に変更しました。プレフィックス判定のテストと、空のトランザクションロック範囲走査のベンチマークを追加しました。

Changes: 前方走査の訪問キー追跡

Layer / File(s) Summary
プレフィックスによる訪問追跡
store/lsm_store.go
訪問済みキーの追跡を forwardScanPrefixes に変更しました。物理キーとユーザーキーを使って再訪を判定し、物理キーのプレフィックスでなくなった記録を除去します。
訪問追跡の検証
store/scan_replay_prefix_test.go, store/scan_replay_benchmark_test.go
短いキーの物理バージョンより拡張キーが先に現れる場合を含むテストを追加しました。また、Put と Delete の後に空のロック範囲を走査するベンチマークを追加しました。

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Possibly related issues

  • bootjp/elastickv#1590 — トランザクション決定 GC と Redis fence GC が使う前方走査に関係します。この変更は走査処理を扱いますが、安全な GC 方針やレコードの回収規則は実装していません。
Merge Risk: Minimal · up to de849

This change reduces memory use and CPU time in forward scans during Raft recovery, with no intended change to scan results. I found no concrete defect in the new visited-prefix tracking, and it comes with targeted tests and a benchmark. Merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed タイトル「Reduce MVCC scan memory during Raft recovery」は、PR の主要な変更を述べています。変更は Pebble の前方スキャン(collectScanResultsWithPhysicalLimit と collectForwardScanKV)で訪問済みキーの保持方法を変え、メモリ使用量を減らすものです。PR の目的でも、Raft コールドスタート…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

タイトル「Reduce MVCC scan memory during Raft recovery」は、PR の主要な変更を述べています。変更は Pebble の前方スキャン(collectScanResultsWithPhysicalLimit と collectForwardScanKV)で訪問済みキーの保持方法を変え、メモリ使用量を減らすものです。PR の目的でも、Raft コールドスタート時のメモリ削減が中心として説明されています。タイトルは変更の主要な点に対応しており、具体的です。

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 14413990-60af-47ee-b3a2-ffc2efe1da88
Commits

Reviewing files that changed from the base of the PR and between 93ddd83 and de8497c.

Files selected for processing: 3

  • store/lsm_store.go
  • store/scan_replay_benchmark_test.go
  • store/scan_replay_prefix_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (de8497c):

  • store/lsm_store.go

What to check, by subsystem:

  • kv/hlc*.go — Next() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (the TSO allocation floor; legacy modes have none and are pinned as known gaps), and the NextFenced ceiling fence (fail-closed when wall_now >= physicalCeiling or when the next value's physical half exceeds it). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/tso*.go — RaftTSOAllocator must Observe the committed allocation floor before reserving and commit the new floor before handing a window out (HLC.tla IssuanceMode = "tso").
  • kv/coordinator.go, kv/sharded_coordinator.go — RunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and which node stamps StartTS / CommitTS (HLC-3; legacy ShardedCoordinator stamping is the known gap G10). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on (OCC.tla; G0 / G1 are pinned as known gaps).
  • kv/fsm.go, kv/fsm_migration_serving.go — FSM apply of HLC lease entries (SetPhysicalCeiling), the one-phase / PREPARE / COMMIT validation OCC.tla models, verifyComposed1, and the migration serving guard Composed.tla relies on for unpinned writes.
  • store/mvcc_store.go, store/lsm_store.go — version visibility, resumable compaction, the commit-ts apply fence, and the MVCC-1 / MVCC-4 / MVCC-5 invariants.
  • adapter/ts.go — the snapshot start timestamp OCC.tla assumes (applied watermark; MaxUint64 on an empty store).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

@bootjp
bootjp marked this pull request as ready for review December 3, 2026 17:18
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T17:19:47.851227Z de8497c Draft marked ready
🔒 Security Review ✅ Completed 2026-12-03T17:23:13.643299Z de8497c Draft marked ready
ℹ️ 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.

@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

TLA+ spec divergence review (auto-triggered)

This PR touches files that the TLA+ safety spec has an anchor on (per
docs/design/2026_05_28_implemented_tla_safety_spec.md §3),
so an AI review is requested below to verify the implementation has not drifted
from the model.

Anchored files changed in this PR head (de8497c):

  • store/lsm_store.go

What to check, by subsystem:

  • kv/hlc*.go — Next() must respect the HLC-4 preconditions (i)/(ii)/(iii) from the design doc: bounded skew, logical-counter handoff on leader change (the TSO allocation floor; legacy modes have none and are pinned as known gaps), and the NextFenced ceiling fence (fail-closed when wall_now >= physicalCeiling or when the next value's physical half exceeds it). Any change to the bit layout (48/16), the CAS loop, or the ceiling getter/setter is in scope.
  • kv/tso*.go — RaftTSOAllocator must Observe the committed allocation floor before reserving and commit the new floor before handing a window out (HLC.tla IssuanceMode = "tso").
  • kv/coordinator.go, kv/sharded_coordinator.go — RunHLCLeaseRenewal, hlcRenewalInterval, hlcPhysicalWindowMs constants, and which node stamps StartTS / CommitTS (HLC-3; legacy ShardedCoordinator stamping is the known gap G10). Any change to renewal cadence, group selection, or fail-closed behaviour is in scope.
  • kv/transaction.go, kv/lock_resolver.go — OCC commit-ts assignment, lock-map encoding (key, lock_ts) -> start_ts, and the LockResolver action OCC-3 depends on (OCC.tla; G0 / G1 are pinned as known gaps).
  • kv/fsm.go, kv/fsm_migration_serving.go — FSM apply of HLC lease entries (SetPhysicalCeiling), the one-phase / PREPARE / COMMIT validation OCC.tla models, verifyComposed1, and the migration serving guard Composed.tla relies on for unpinned writes.
  • store/mvcc_store.go, store/lsm_store.go — version visibility, resumable compaction, the commit-ts apply fence, and the MVCC-1 / MVCC-4 / MVCC-5 invariants.
  • adapter/ts.go — the snapshot start timestamp OCC.tla assumes (applied watermark; MaxUint64 on an empty store).
  • distribution/** — route catalog versioning, SplitRange atomicity, and CatalogWatcher async fan-out (M4 scope).

If the change is correct but requires a spec update, edit tla/hlc/HLC.tla (or the corresponding M2..M5 module once landed) and the design doc in the same PR. The tla-check workflow runs the TLC model check on the same paths.


@claude review please verify TLA+ spec divergence per the checklist above.

@codex review please verify TLA+ spec divergence per the checklist above.

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