Skip to content

logservice: support offline WAL recovery - #25867

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
LeftHandCold:codex/logservice-wal-restore-main
Jul 22, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
LeftHandCold:codex/logservice-wal-restore-main

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jul 19, 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:

Fixes #24966.

What this PR does / why we need it:

Adds an explicit offline LogService recovery path for rebuilding a three-replica LogService cluster from artifacts generated by mo_br.

The recovery path is enabled only when logservice.BootstrapConfig.restore.wal-data-path is configured. Normal LogService startup and heartbeat behavior are unchanged when the option is absent.

Key behavior:

  • Requires a valid HAKeeper backup and WAL data file and fails closed for missing or malformed recovery input.
  • Restores NextID and NextIDByKey through replicated, max-only HAKeeper updates, including when another LogService is already the HAKeeper leader and the cluster has already entered bootstrap.
  • Keeps HAKeeper out of the running state while WAL recovery is pending.
  • Selects one recovery coordinator from replicated LogStore heartbeat state and sends replay requests to the current Log shard leader, so recovery does not depend on the restore pod being leader.
  • Validates WAL ordering, bounds, and digest, and persists replay progress for crash-safe resume without duplicating recovered records.
  • Writes the restore marker only after HAKeeper ID watermarks have been verified.

Operational constraint: all three LogService pods must run this version during recovery. Only one pod should be configured with the recovery files.

Validation:

  • go test -count=1 -timeout=15m ./pkg/hakeeper/... ./pkg/logservice ./pkg/pb/logservice ./pkg/util
  • go test -race -count=1 -timeout=20m ./pkg/hakeeper ./pkg/logservice
  • go vet ./pkg/hakeeper/... ./pkg/logservice ./pkg/pb/logservice ./pkg/util
  • go test ./cmd/mo-service ./pkg/embed -run '^$' -count=1
  • go build ./cmd/mo-service
  • make err-check

End-to-end validation on an isolated local kind cluster:

  • Seeded an old cluster with 1,001 rows and 10 databases.
  • Copied the three live LogService data directories and generated fresh recovery artifacts with mo_br.
  • Recreated all three LogService PVCs and copied only hakeeper_backup.data and wal_data.bin to log-0.
  • Started log-1 and log-2 first: log-2 became HAKeeper leader and log-1 initialized the cluster before log-0 started.
  • Started log-0: all HAKeeper replicas applied NextID=50000000 and the complete NextIDByKey; 115/115 WAL entries were replayed.
  • Verified all original rows/databases and created a new database/table with IDs 50000001 and 50000002.
  • Removed recovery configuration and restarted all three LogService pods. No WAL recovery ran; data remained intact and subsequent IDs advanced to 50010341 and 50010342.

@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 →

@mergify mergify Bot added the kind/feature label Jul 19, 2026
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Jul 19, 2026
@LeftHandCold
LeftHandCold force-pushed the codex/logservice-wal-restore-main branch from 2be15cb to 974fded Compare July 19, 2026 08:35
@LeftHandCold
LeftHandCold force-pushed the codex/logservice-wal-restore-main branch from 974fded to 302a504 Compare July 19, 2026 10:16

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

Codex automated review

Found four blocking recovery-safety bugs and two material limit issues. Focused tests were blocked locally by missing CGo headers.

P1 - Require a clean destination before initializing replay state (pkg/logservice/wal_recovery.go:800)

When no state file exists, BaseLSN and LastLSN are initialized to the destination's current latest LSN. Existing records are therefore treated as baseline, and the old WAL is appended after them and marked complete. The bootstrap path can run after HAKeeper and the Log shard are already initialized, so a restart or late recovery can silently duplicate WAL history instead of failing closed.

P1 - Reject recovery after HAKeeper has entered Running (pkg/hakeeper/rsm.go:808)

RestoreIDWatermarkUpdate sets LogServiceRecoveryPending even when the current state is HAKeeperRunning. The Running transition guard only applies while the current state is BootstrapCommandsReceived, and Running has no transition back to a gated state. With staggered startup, HAKeeper can reach Running from a quorum before the recovery pod heartbeats; the late pod then starts replay while the cluster is serving.

P1 - Invalidate the cached ID allocator after restoring watermarks (pkg/logservice/store_hakeeper_check.go:142)

This updates the replicated HAKeeper watermark but leaves l.alloc unchanged. updateIDAlloc preallocates a 10,240-ID range, and getScheduleCommand reuses any remaining range with capacity >=1024. If bootstrap scheduling allocates a low range before a late recovery pod applies a higher backup watermark, those cached low IDs are handed out after recovery and can collide with IDs referenced by restored data.

P1 - Fence user appends during WAL replay (pkg/logservice/wal_recovery.go:878)

Replay sends APPEND requests via doAppend, while the recovery status only gates HAKeeper state and ID allocation. LogService's normal append handler has no recovery-pending fence, so another valid writer can insert a user record between replay entries. The reconciliation loop explicitly rejects such records as unexpected or mismatched, leaving recovery failed and HAKeeper pending.

P2 - Bound accepted WAL entries by the actual RPC message limit (pkg/logservice/wal_recovery.go:51)

The parser accepts RawData up to defaultMaxMessageSize (100 MiB), but the recovery client uses cfg.RPC.MaxMessageSize and morpc validates RPCRequest.ProtoSize(), which includes the protobuf request plus the APPEND command header and payload. Thus an entry at the parser limit, and entries near it under the default RPC limit, are accepted from disk but rejected before transmission.

P2 - Avoid loading the full recovery artifact into memory (pkg/logservice/wal_recovery.go:339)

The code permits a 1 GiB file while retaining every RawData slice and WALEntry in memory. A valid artifact with millions of entries adds hundreds of megabytes of slice/struct/allocation overhead on top of the file contents, potentially exhausting a LogService before replay begins.

@LeftHandCold

Copy link
Copy Markdown
Collaborator Author

Codex automated review

Reviewed head a945001 against origin/main after loading all existing reviews, issue comments, and inline comments. Three blocking data-integrity paths remain. Focused tests could not compile because this worktree lacks the required cgo/libmo.dylib prerequisite.

P1 - Do not infer SafeDSN from the first surviving record (pkg/logservice/wal_recovery.go:793)

This clamp assumes firstNormalDSN-1 is already durable and raises any smaller source SafeDSN. That is invalid because asynchronous commits allow PSN order to differ from DSN order: a surviving WAL can begin with DSN 10/SafeDSN 3 while DSNs 4-9 occur at later PSNs. Rewriting the first payload to SafeDSN 9 makes TN replay treat those delayed DSNs as already safe, potentially skipping them or hitting replay logic errors. Preserve the lower source watermark or derive the lower bound from authoritative checkpoint metadata, with an end-to-end test covering an out-of-order prefix across read batches.

P1 - Gate persisted TN startup, not only bootstrap commands (pkg/logservice/store_hakeeper_check.go:510)

Replacing state.TNState with an empty state only suppresses new HAKeeper StartReplica commands. TN Start() independently reloads persisted shard metadata and calls startTNShards() before heartbeats; its normal ReplayForWrite stops at the current Log tail and cannot be rerun. A retained or restarting TN can therefore replay the newly created empty Log shard before WAL import, after which HAKeeper completes recovery and enters Running with the TN missing the recovered tail. The replicated barrier must be observed by TN startup/replay itself, and the integration test must retain TN metadata rather than using an empty heartbeat.

P1 - Fence truncation throughout WAL replay (pkg/logservice/rsm.go:250)

The recovery lease rejects ordinary appends and lease changes, but handleTruncateLsn still accepts truncation commands. The coordinator checks TruncatedLsn only once after installing the fence, so an existing TN can truncate after that check while entries are being imported. Reconciliation ignores non-user records and the completion marker only counts imported user entries, allowing recovery to report success with a raised truncation watermark that makes restored records unreadable or eligible for compaction. Reject TruncateLSNUpdate while the recovery lease is active and test a truncate interleaved with replay.

TN 持久化启动:不采纳。 离线恢复明确要求 TN 在 WAL 恢复完成前保持停止。修改 TN 通用启动流程会增加正常集群启动风险。
恢复期间 truncate:不采纳。 严格离线流程下没有 TN 或外部客户端发送 truncate,LogService truncation worker 自身不会生成该命令。

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

pkg/logservice/wal_recovery_status.go:113

This does not actually wait for every voting replica to report its recovery status. A
store may already exist in LogState.Stores from an earlier heartbeat while ConfigData
is nil or does not contain wal-recovery-status; continuing here allows election from a
partial candidate set.

For example, if store-b reports coordinator-pending first, it can elect itself while a
lexicographically smaller artifact-owning store-a has not published its recovery status
yet. Once store-a reports, it will also elect itself. The destination fence does not
serialize these coordinators when they use the same WAL digest and recovery lease
holder, so both can append the same source entry and corrupt the recovery sequence.

Please return not-ready unless every voting replica has a valid recovery status item,
and add a test where one replica has no status while another replica is coordinator-
pending.

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

Codex automated review

Found three blocking correctness issues. Focused tests could not build because required C headers are unavailable.

P1 - Existing backup-only restore is rejected without the new recovery flag (pkg/logservice/service_bootstrap.go:178)

With the existing restore.file-path configuration and restore.enabled=false, the initial request carries no recovery intent. If another initial member wins with default IDs, this unconditional watermark restore sends RestoreIDWatermarkUpdate, which HAKeeper rejects whenever LogServiceRecoveryPending is false. Bootstrap then retries and fails, regressing the pre-existing backup restore path.

P1 - Malformed skip records can panic during replay (pkg/logservice/wal_recovery.go:639)

Skip payloads are accepted whenever they are nonempty and a multiple of 16 bytes; DSN/PSN semantics are not checked. The downstream replayer panics when a skip DSN is absent from dsn2PSNMap or appears twice. A structurally valid but corrupt recovery artifact therefore crashes replay instead of failing closed.

P1 - Overlapping DSN ranges are not rejected (pkg/logservice/wal_recovery.go:546)

Cross-entry validation checks Raft indexes and arithmetic overflow but not overlap or duplicate normal DSN intervals. Two normal entries with distinct Raft indexes and the same DSN start pass validation; replay stores only one PSN per start DSN and overwrites the earlier record, allowing recovered WAL data to be silently omitted or applied incorrectly.

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

Re-reviewed the latest update. The coordinator election now correctly waits for every
voting replica to publish a valid recovery status, which addresses the partial-election
race. I also reviewed the new WAL sequence and skip DSN/PSN validation and did not find
any further blocking issues. The targeted recovery tests pass.

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

Codex automated review

Loaded all existing reviews, issue comments, and inline comments (none). Earlier blocking recovery findings are addressed; the retained-TN and truncate concerns are conditional on the explicit offline-recovery precondition. git diff --check passes. Focused Go tests could not run because the Go toolchain is unavailable.

P2 - Bound retained SkipDSN references during WAL scanning (pkg/logservice/wal_recovery.go:480)

Although recovery accepts files up to 10 GiB and streams normal payloads, every SkipDSN payload is decoded into a reference slice and retained in entry.skip until the entire file has been parsed, sorted, and validated. Valid skip-heavy artifacts can therefore retain nearly the full 10 GiB as Go allocations (plus slice overhead), causing the LogService to OOM rather than fail cleanly. Cap cumulative references/memory, or retain offsets and re-read the skip payload only after sorting.

P2 - Preserve missing custom backup behavior outside WAL recovery (pkg/logservice/service_bootstrap.go:343)

Before this change, getBackupData treated a missing restore file as no backup for every path. This branch now fails normal bootstrap for any missing custom path, even with restore.enabled=false and no WAL recovery configured; only the default hk_data path remains optional. That regresses existing backup-only/normal configurations and contradicts the stated unchanged normal startup behavior. Keep the coordinator-side missing-artifact requirement in getBackupDataForBootstrap, but preserve the prior optional behavior outside recovery.

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

Reviewed exact head c3a6a41 against current origin/main. The earlier recovery-integrity blockers are addressed, and fresh package plus race-focused tests pass, but two material gaps remain.

P1 - Preserve optional missing custom backup behavior outside WAL recovery (pkg/logservice/service_bootstrap.go:314-345)

When wal-data-path is absent and restore.enabled is false, getBackupDataForBootstrap does not take the non-coordinator exception. A missing non-default relative file now returns ErrFileNotFound here, and a missing absolute file returns os.ErrNotExist above. Before this PR, every missing restore path returned nil. An existing deployment can retain a custom restore.file-path after the one-time artifact is removed or temporarily unavailable; upgrading to this change then aborts BootstrapHAKeeper even though WAL recovery is not configured. This contradicts the PR contract that normal startup is unchanged without wal-data-path. The new TestGetBackupDataForBootstrap currently codifies the regression. Keep strict missing-artifact failure for the actual WAL recovery coordinator, but preserve the previous optional behavior outside recovery.

P2 - Bound retained SkipDSN references before semantic validation (pkg/logservice/wal_recovery.go:475-480)

The scanner permits a 10 GiB file and streams normal payloads, but each SkipDSN body is copied into a walRecoverySkipReference slice and retained on WALEntry until the entire file has been scanned and sorted. Unknown, duplicate, and wrong-PSN references are rejected only afterward by validateWALRecoveryEntries. Consequently, a structurally valid but semantically malformed skip-heavy artifact can make the process retain roughly the artifact size as Go heap and OOM before returning the promised validation error. Normal mo_br output is constrained by the number of live WAL entries, so this finding is specifically about the PR stated fail-closed behavior for malformed recovery input. Retain offsets and re-read skip bodies after sorting, validate incrementally where possible, or impose a safe cumulative reference bound.

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

Re-reviewed exact head fafe6f8 against base dae28be. No remaining blocking issue found.

I revalidated every previously raised recovery gap. The current implementation now preserves optional missing custom backups outside WAL recovery, bounds retained SkipDSN references before allocation, streams payloads, derives the actual RPC payload ceiling, binds completion to the destination RSM marker, rejects dirty destinations, persists/reconciles crash progress, fences normal appends and lease changes, preserves SafeDSN semantics, waits for complete voting membership before coordinator election, and holds HAKeeper scheduling/ID allocation behind replicated recovery preparation with allocator-generation invalidation.

Fresh validation on this exact head:

  • go build -mod=readonly ./pkg/hakeeper ./pkg/logservice
  • go vet -mod=readonly ./pkg/hakeeper ./pkg/logservice
  • full go test -count=1 -timeout=15m ./pkg/hakeeper ./pkg/logservice
  • focused go test -race -count=1 -timeout=15m -run 'WAL|Recovery|Restore|Recovered|IDAllocatorDiscards' ./pkg/hakeeper ./pkg/logservice
  • git diff --check

All passed. The full package run also covers the real TAE LogEntry writer/decoder replay test, not only synthetic byte validation.

The current Ubuntu UT rerun reports pkg/logservice PASS (387.81s). Its sole failure is a data race in pkg/vm/engine/tae/rpc/handle_debug.go triggered by pkg/tests/dml/TestDataBranchPickRetestCompositePKChunkProbe; neither path is modified by this PR.

@mergify

mergify Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-22 13:05 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-07-22 13:30 UTC · at 6e1080be215d1425eef13cfc1acfd828dd866e23

This pull request spent 25 minutes in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)

Reason

Pull request #25867 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LogService HAKeeper can regress to stale shard membership after Dragonboat imported snapshot metadata rewrite

6 participants