Skip to content

fix logservice stale replica truncation - #24982

Merged
mergify[bot] merged 9 commits into
matrixorigin:3.0-devfrom
LeftHandCold:codex/logservice-clean-stale-replica-3.0-dev
Jun 17, 2026
Merged

mergify[bot] merged 9 commits into
matrixorigin:3.0-devfrom
LeftHandCold:codex/logservice-clean-stale-replica-3.0-dev

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #24966

What this PR does / why we need it:

This PR updates the MatrixOne 3.0-dev branch to use the Dragonboat snapshot import metadata fix merged in:

Main changes:

  • Update the github.com/lni/dragonboat/v4 replacement to github.com/matrixorigin/dragonboat/v4 v4.0.0-20260612094223-103d119addce.
  • Add the corresponding go.sum entries for the updated Dragonboat module.

Why this is needed:

  • The upstream fix prevents imported snapshots from synthesizing Membership.ConfigChangeId from the snapshot index.
  • HAKeeper uses Dragonboat membership ConfigChangeId as the LogService shard epoch.
  • Without this fix, an old imported membership can be reported with a large fake epoch and be treated as newer than the live membership view.
  • The upstream fix also preserves online imported snapshot membership consistently and rejects invalid target membership before restore.

Validation:

  • git diff --check
  • GOTELEMETRY=off go mod download github.com/lni/dragonboat/v4
  • GOTELEMETRY=off go list -m -json github.com/lni/dragonboat/v4
  • GOTELEMETRY=off GOCACHE=/private/tmp/mo-dragonboat-3dev-gocache go test github.com/lni/dragonboat/v4/tools github.com/lni/dragonboat/v4/internal/rsm github.com/lni/dragonboat/v4/internal/raft -run '^$' -count=0

Fixes logservice stale replica recovery with the previous MO-side stale truncation metadata cleanup plus the Dragonboat snapshot import metadata fix from #24967. This keeps truncation from processing stale local replica metadata/exported snapshots, and updates Dragonboat so imported snapshots no longer synthesize membership ConfigChangeId from snapshot index.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Multi-Angle Review Summary (3.0-dev Branch)

Comprehensive review completed across 6 dimensions: logic correctness, concurrency safety, error handling, test coverage, unhappy paths, and dependency upgrade.

✅ Overall Assessment: APPROVE

This is the 3.0-dev branch version of PR #24983 (main branch) with identical logic.

Strengths:

  • 🔒 Concurrency bug FIXED: snapshotManager now thread-safe (sync.RWMutex)
  • 🔄 Transactional cleanup: Metadata only removed if snapshot cleanup succeeds
  • 📝 Excellent test coverage: 259 new test lines (1.7:1 test:code ratio)
  • 🛡️ Conservative logic: Double-check pattern prevents false deletions
  • 🧪 Fault injection testing: TestTruncationKeepsStaleReplicaMetadataOnSnapshotCleanupFailure
  • 📦 Critical dependency upgrade: Dragonboat snapshot import metadata fix

🔴 Critical Issues FIXED

Issue #1: snapshotManager Data Race [FIXED]

Root cause: snapshotManager.snapshots map accessed by multiple goroutines without synchronization.

Concurrent paths:

  • truncationWorker → Count(), NewestIndex(), EvalImportSnapshot()
  • startReplica → Add()
  • processHAKeeperTruncation → Remove()

Impact: "concurrent map read/write" panic

Fix applied:

type snapshotManager struct {
    mu        sync.RWMutex  // ✅ ADDED
    cfg       *Config
    snapshots map[nodeID]*snapshotRecord
}

Lock strategy:

  • Read locks (RLock): Count, NewestIndex, EvalImportSnapshot
  • Write locks (Lock): Add, Remove, RemoveReplica, DropNewest, Init
  • Professional pattern: Add/addLocked to avoid nested locks

✅ Verified correct — standard RWMutex usage, complete map coverage.


Issue #2: Stale Replica Metadata Causes Fake Epoch [FIXED]

Problem: Old replica metadata + exported snapshots linger after replica superseded:

  • Stale membership reported to HAKeeper with fake large epoch
  • Disk space waste
  • Truncation processing stale metadata

Fix: New cleanupStaleReplica logic in processTruncateLog:

activeReplicas := l.startedReplicaIDs()  // T1: Get active replicas
for _, shard := range l.getShards() {
    replicas := activeReplicas[shard.ShardID]
    if _, ok := replicas[shard.ReplicaID]; !ok {  // Not active
        if len(replicas) > 0 || l.isSkippedZombie(...) {
            // Double-check before cleanup (TOCTOU protection)
            replicas = l.startedReplicaIDs()
            if _, ok := replicas[shard.ReplicaID]; ok {
                continue  // ✅ Now active, skip
            }
            l.cleanupStaleReplica(...)  // ✅ Safe
        }
    }
}

✅ Conservative logic — double-check pattern prevents false deletions.


🧪 Test Coverage Analysis

3 new test cases (259 lines):

Test Unhappy Path
TestTruncationSkipsStaleReplicaMetadata No active replicas → skip cleanup; Skipped zombie → cleanup
TestTruncationRealignsSnapshotIndexAfterStaleReplicaCleanup After stale cleanup, realign index to active replica's newest snapshot
TestTruncationKeepsStaleReplicaMetadataOnSnapshotCleanupFailure FS failure → metadata preserved (transactional) ⭐

Fault injection test:

// Inject FS failure
failingSnapshotCfg.FS = vfs.Wrap(originalSnapshotCfg.FS, vfs.OnIndex(0, vfs.OpWrite))
s.store.snapshotMgr.cfg = &failingSnapshotCfg

assert.NoError(t, s.store.processTruncateLog(ctx))
assert.Equal(t, int64(staleReplica), s.store.getReplicaID(shardID))  // ✅ Still there
assert.Equal(t, 1, s.store.snapshotMgr.Count(shardID, staleReplica))  // ✅ Preserved

// Fix FS, retry
s.store.snapshotMgr.cfg = originalSnapshotCfg
assert.NoError(t, s.store.processTruncateLog(ctx))
assert.Equal(t, int64(-1), s.store.getReplicaID(shardID))  // ✅ Now removed

✅ Outstanding — fault injection verifies transactional cleanup.


🔍 Unhappy Path Deep Dive

Edge case #1: FS failure during snapshot cleanup → TESTED ✅

  • Metadata preserved, cleanup retried next iteration
  • Test: TestTruncationKeepsStaleReplicaMetadataOnSnapshotCleanupFailure

Edge case #2: Replica becomes active during cleanup → HANDLED ✅

  • Double-check pattern catches this: replicas = l.startedReplicaIDs() re-snapshot
  • If now active, skip cleanup

Edge case #3: Multiple stale replicas for same shard → HANDLED ✅

  • processed map deduplicates: only process each shardID once

Edge case #4: Snapshot index realignment → TESTED ✅

  • After stale cleanup, index reset to newest active replica snapshot
  • Test: TestTruncationRealignsSnapshotIndexAfterStaleReplicaCleanup

Edge case #5: Concurrent snapshotManager access → FIXED ✅

  • All methods protected by RWMutex

📦 Dragonboat Dependency Upgrade

Upgrade: v4.0.0-20251214113216-2ddf81ef2a85 → v4.0.0-20260612094223-103d119addce

Upstream fix: matrixorigin/dragonboat@103d119addce

Issue fixed: Imported snapshots no longer synthesize Membership.ConfigChangeId from snapshot index

Impact: Prevents old imported membership from being treated as newer (fake epoch bug)

✅ Critical fix — required for correct HAKeeper operation.


📊 Code Quality

  • Transactional cleanup: Snapshot cleanup failure → metadata preserved
  • Conservative logic: Double-check prevents false deletions
  • Fault injection: FS failure tested
  • Complete lock coverage: All snapshotManager methods protected
  • No breaking changes: Backward compatible

🎯 Verdict

APPROVE — This is the 3.0-dev backport of #24983 with identical logic.

Why APPROVED:

  1. Concurrency bug fixed (snapshotManager RWMutex)
  2. Comprehensive test coverage (259 lines, 1.7:1 ratio)
  3. Fault injection verifies transactional cleanup
  4. Conservative double-check logic prevents false deletions
  5. Critical Dragonboat dependency upgrade
  6. All unhappy paths tested

Comparison to #24983:

  • Target branch: 3.0-dev (vs main)
  • Code logic: Identical
  • Test coverage: Identical
  • Dragonboat version: Same

No blocking issues — ready to merge.


Reviewed dimensions: logic, concurrency, errors, tests, unhappy paths, dependency
Test coverage: 259 lines | Test:Code ratio: 1.7:1 | Fault injection: 1 test

@mergify

mergify Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-06-17 11:15 UTC · Rule: release-3.0
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-06-17 11:15 UTC · at ca321c9d7b947504acaef36c1e5f1e2d87490685 · squash

This pull request spent 15 seconds in the queue, including 2 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • github-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI (3.0) / Coverage
    • check-neutral = Matrixone Utils CI (3.0) / Coverage
    • check-skipped = Matrixone Utils CI (3.0) / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI (3.0) / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI (3.0) / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI (3.0) / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI (3.0) / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI (3.0) / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI (3.0) / Compatibility Test With Target on Linux/x64(LAUNCH)

@volgariver6

Copy link
Copy Markdown
Contributor

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants