Skip to content

fix(move): make --force re-validate before wiping and cover definitive unresumable checkpoints - #1038

Merged
morgo merged 8 commits into
block:mainfrom
morgo:fix/move-force-recovery-semantics
Sep 5, 2026
Merged

morgo merged 8 commits into
block:mainfrom
morgo:fix/move-force-recovery-semantics

Conversation

@morgo

@morgo morgo commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Move could wipe a partial target copy under --force and only afterward discover a source-side failure that wiping cannot fix. It also refused forced recovery when deeper checkpoint validation found an expired checkpoint or unusable source positions.

Validate every post-setup check except target state before wiping, including automatic recovery from an empty move checkpoint. Allow forced recovery only for typed, definitive checkpoint failures; transient errors still abort. Checkpoint records are fully validated before the checksum watermark is assigned or change feeds are built, and the force fallback explicitly clears that watermark before starting fresh.

Post-setup checks now run in stable name order, so a target with several problems reports the same first failure on every run. The exclusion path is covered directly and shares the regular RunChecks API.

Reject source/target aliases before target operations by comparing selected schemas and server UUIDs through a shared dbconn helper. Different credentials or hostnames cannot bypass this guard. Multi-source and multi-target moves resolve each connection identity once instead of repeating queries for every pair.

Validation against MySQL 8.0.43:

  • go test ./pkg/move/check and go test ./pkg/move
  • Focused force recovery and database identity regressions.
  • golangci-lint run: clean.

morgo and others added 2 commits July 2, 2026 06:45
…e unresumable checkpoints

--force's wipe-and-restart recovery had two holes:

1. It wiped the target FIRST and re-ran the post-setup checks AFTER.
   RunChecks iterates a map, so the triggering failure may equally have
   been source-side (rename_safety's leftover _old table,
   source_schema_consistency drift, table_compatibility) — failures that
   wiping the target cannot cure. A multi-hundred-GB partial copy plus a
   valid checkpoint could be destroyed only for the rerun to fail on the
   same source-side error. Now the post-setup checks minus target_state
   (the one check wiping cures) are re-run BEFORE the wipe, and the wipe
   is refused if any still fail.

2. When the resume probe passed but resumeFromCheckpoint's deeper
   validations found the checkpoint definitively unusable — older than
   --checkpoint-max-age, positions that do not parse (e.g. a row written
   by the migration runner into the same _spirit_checkpoint table name),
   or a source missing from the positions map — the run hard-failed even
   with --force set, despite the flag's contract covering exactly
   "cannot resume from a checkpoint". These states are now tagged with
   typed sentinels (status.ErrCheckpointTooOld, new
   errCheckpointUnresumable) and fall through to the same
   validate-then-wipe path. Possibly-transient errors keep hard-failing:
   classification is strictly by errors.Is, never by string.

resumeFromCheckpoint now performs all checkpoint-record validation
before its first side effect (chunker subscriptions, runner state), so a
definitive validation failure leaves the runner clean for the fall-through
to rebuild everything via newCopy().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@morgo
morgo requested a lite review from Copilot September 5, 2026 15:17
@morgo
morgo marked this pull request as ready for review September 5, 2026 15:17

Copilot AI 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.

🟢 Approval recommended

The changes are safety-focused, localized, and accompanied by targeted integration tests covering the newly introduced failure and recovery paths.

Pull request overview

This PR hardens move --force recovery by ensuring source-side validation happens before any destructive target wipe, and by making certain checkpoint failures eligible for forced restart rather than aborting after partial validation.

Changes:

  • Gate --force target wipes behind a pre-wipe revalidation of all post-setup checks except target_state, preventing wipes when failures are source-side.
  • Treat specific checkpoint-resume failures (e.g., too-old checkpoints, malformed/missing per-source positions) as definitively unresumable so --force can restart safely.
  • Add a shared dbconn guard to reject source/target database aliases using DATABASE() + @@server_uuid, plus integration tests for new recovery and alias behavior.
File summaries
File Description
pkg/move/runner.go Reorders validation vs wipe behavior for --force, adds definitive-unresumable checkpoint handling, and enforces source/target identity checks early.
pkg/move/runner_test.go Adds regression coverage for pre-wipe validation, forced restart on definitive checkpoint failures, and source/target alias rejection.
pkg/move/check/target_state.go Exposes a stable check name constant so the runner can exclude only target_state in pre-wipe validation.
pkg/move/check/check.go Introduces RunChecksExcluding to support pre-wipe validation that intentionally omits specific checks.
pkg/dbconn/database_identity.go Adds RequireDifferentDatabase helper for robust source/target alias prevention across differing DSNs.
pkg/dbconn/database_identity_test.go Verifies alias detection works for same DB and for distinct DSNs pointing at the same DB.
docs/move.md Updates operator guidance for --force, including which checkpoint failures are eligible and the source/target alias restriction.
Review details
  • Files reviewed: 7/7 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread pkg/dbconn/database_identity.go Resolved
@aparajon

aparajon commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator

🤖 Adversarial correctness review — 45ccf7a3 (+329/-17, 7 files)

The central insight is right and stated well: "wiping only cures target-side state, so a failure in any other (source-side) check must surface before the target is destroyed." Excluding exactly one check by name — with TargetStateCheckName used both at registerCheck and at the exclusion site, so the two cannot drift — is the right mechanism, and RunChecksExcluding's comment gets the fail-safe direction exactly right: "excluding too little only blocks a wipe, excluding too much could green-light one."

Restricting forced recovery to typed sentinels rather than "any resume error" is the other good call. errors.Is on ErrCheckpointTooOld / errCheckpointUnresumable means a transient checkpoint read failure still aborts instead of being converted into permission to destroy a partial copy, which is the failure this could most easily have introduced.

⭐ The reordered watermark assignment is not cleanup — it's what makes the new force path safe, and that coupling is worth stating in the PR. Moving

	copierWatermark := rec.CopierWatermark
	r.checksumWatermark = rec.ChecksumWatermark

below the validations reads as tidying, but r.checksumWatermark is consumed on the fresh path too (runner.go:1815, r.checksumChunker.OpenAtWatermark(r.checksumWatermark)). Before this PR a failed resume always returned, so a stale value could never reach a fresh copy. This PR makes the resume failure fall through to a wipe — so without the reorder, --force recovery would have opened the checksum chunker at the abandoned attempt's high-water mark and skipped verification of everything below it on a newly-copied target. Silent, and exactly the kind of thing a checksum exists to catch. Two independent-looking hunks; one is load-bearing for the other.

I verified the property that makes it hold, since it isn't local: ErrCheckpointTooOld is raised only at runner.go:450 and errCheckpointUnresumable only at :461 and :465, all three above the moved assignment. Every return after it — AddSubscription, the multi-chunker construction, StartFromPosition — is a non-definitive error, so force cannot continue past the point where feeds are subscribed. Finding 2 is about keeping that true.

# Sev Where What
1 low-med check/check.go:82 The check registry is a map, so the new pre-wipe refusal names a random one of several failing source-side checks; the sibling check package already sorts by name for this exact reason
2 low-med runner.go:63, :690 The sentinel's safety depends on an unstated ordering invariant — every force-eligible error must be raised before any state mutation — and the most natural extension breaks it silently
3 low check/check.go:71, runner.go:1636 The only new pure logic has no direct test, and making RunChecks variadic would collapse four functions into two with zero caller churn
4 low runner.go:1192 The alias guard runs sources × targets with up to four queries per pair, and on a sharded move the four-query path is the common case

1 — the PR reasons about which check failed, over a randomly-ordered registry (low-med)

checks is map[string]check (check.go:56), and RunChecksExcluding returns on the first failure it encounters while ranging over it. Go randomizes map iteration, so when two post-setup checks fail, which error surfaces varies run to run.

That was tolerable while nothing distinguished the checks — and you've already noticed it, in the comment at :714: "RunChecks iterates a map, so the original failure was not necessarily target_state." That observation is what justifies the exclusion, and it's correct. The part it stops short of is that the new pre-wipe call has the same exposure one level down: refusing to wipe the target because a check that wiping cannot fix is failing: <X> picks a random X. An operator who re-runs to confirm gets a different diagnosis for the same broken state, on a path whose whole purpose is to explain why a --force they asked for was refused.

The fix already exists one package over. pkg/migration/check.RunChecks does exactly this, with the rationale written down:

Checks run in name order so that a statement failing more than one check always reports the same error.

and it goes further than ordering — maps.Clone(checks) under a lock, a namesInScope helper sorted so RunChecks and ChecksInScope agree, and check_test.go:48 pinning it with slices.IsSorted(statementScope). Porting the sorted iteration to pkg/move/check is a few lines and makes both the pre-wipe refusal and the post-wipe re-check deterministic. Worth doing here rather than later precisely because this PR is the first code in the package to care about check identity.

(The unlocked map read is fine in practice — registration happens in init() — so it's the ordering, not the locking, that matters for move.)

2 — the invariant that makes the sentinel safe isn't written down, and the obvious next extension violates it (low-med)

// Only definitive checkpoint failures permit --force to discard a partial copy.
var errCheckpointUnresumable = errors.New("checkpoint is not resumable")

The comment states the policy (definitive failures only). The property the code actually depends on is stronger and unstated: a force-eligible error must be raised before resumeFromCheckpoint mutates any runner state. Today that's true, and it's true only because both sentinels happen to be raised in the first third of the function.

Consider the most natural future addition. StartFromPosition failing because the binlog file has been purged is about as definitively unresumable as a checkpoint gets, and someone will reasonably reach for errCheckpointUnresumable when wrapping it. That call is at the end of resumeFromCheckpoint, well past the watermark assignment, past AddSubscription, past the multi-chunker construction. Force would then continue into a wipe carrying r.checksumWatermark from the abandoned attempt — reintroducing exactly the hole the reorder closes — plus subscriptions registered against change clients the fresh path is about to replace. Nothing would fail; the copy would just be verified less than it claims.

Two things would keep this safe against that:

  • Make the fresh path independent of where the error was raised. On the force-continuation branch, explicitly reset the resume-derived state before falling through:
    r.logger.Warn("force set and checkpoint is definitively unresumable; starting fresh", "reason", resumeErr)
    r.checksumWatermark = ""
    Two lines, and correctness stops depending on the ordering of a function forty lines away. If any other field is resume-derived, it belongs here too.
  • Say the invariant where the next person will read it — next to the sentinel, or on the // All definitive validation has passed before changing runner or target state. line, which currently records that the property holds but not that it must. That comment is the natural home for "do not tag errors raised below this point with errCheckpointUnresumable."

The first is what I'd actually want; the comment alone leaves a load-bearing ordering constraint enforced by nothing.

3 — the new pure logic is untested, and the indirection isn't needed (low)

RunChecksExcluding is the one piece of this PR that is pure map-and-slice logic over a registry, and grep -rn RunChecksExcluding --include=*_test.go returns nothing. All five new tests are in pkg/move/runner_test.go and need a live MySQL source and target — which means the safety property the comment says must not drift ("new checks are deliberately included by default") is pinned only behind a container.

pkg/move/check has a test file per check but nothing exercising the runner, and no ScopeTesting the way pkg/migration/check does. So the ask is a testing scope plus a test registering two fakes and asserting that excluding one still runs the other — a handful of lines, no container, and it would catch an exclusion list that silently over-matches.

While you're in there: check.RunChecks has exactly one caller outside its own package (r.runChecks), and RunChecksExcluding one (r.runChecksExcluding). Making RunChecks variadic — RunChecks(ctx, r, logger, scope, exclude ...string) — is source-compatible with every existing call, so RunChecksExcluding and runChecksExcluding both disappear and four functions become two. The Excluding name also slightly undersells what it does; a variadic RunChecks reads as "run the checks, minus these," which is the actual contract.

4 — the alias guard is quadratic, and sharded moves take the expensive branch (low)

	for si := range r.sources {
		for ti := range r.targets {
			if err := dbconn.RequireDifferentDatabase(ctx, r.sources[si].db, r.targets[ti].DB); err != nil {

Each call issues two SELECT DATABASE() round trips, plus two SELECT @@server_uuid when the schema names match. That's fine for 1:1. For the N:M moves sourceInfo's own doc comment describes, it's N×M calls — 8×8 is 64 pairs, 128–256 round trips before the move starts.

The part worth noting is which branch dominates. The cheap two-query path is taken when the schema names differ — but a sharded move typically has the same database name on both sides, on different servers. So the UUID reads fire on every pair, and the four-query path is the common case rather than the exception, re-reading the same handful of servers' UUIDs dozens of times.

Startup-only, so this is a genuine low. But hoisting it is straightforward and reads better than the nested loop: resolve (schema, uuid) once per distinct source and per distinct target — N+M reads — then compare the cached pairs. That also gives you a better error than source %d / target %d, since you'd have both schema names and both UUIDs in hand for every pair.

Practical note, not a finding: pkg/dbconn/database_identity.go and its test are byte-identical to #1043's copies (git diff pr1043:… HEAD:… is empty), and both PRs are open. Whichever merges second gets an add/add conflict that resolves by keeping either copy — trivial, but easy to fumble into a duplicate-symbol build break if resolved by concatenation. My #1043 review covers the shared file, so the verdict on it carries here and I haven't repeated it below.


Verified — the ordering, and two attacks that dissolved

⭐ Attack that dissolved: the pre-wipe run replaced the post-wipe run. If the new runChecksExcluding had been added instead of the existing full re-check, target_state would never be validated against the cleaned target and the docs' claim of "re-running the full post-setup checks against the cleaned target" would be false. Both are present: runChecksExcluding at :703 before wipeTargets, and the full runChecks(ScopePostSetup) at :716 after, with its original comment intact. The docs sentence is accurate.

⭐ Attack that dissolved: a past-cutover checkpoint becoming force-eligible. The most dangerous thing --force could be allowed to do here is wipe a target whose source tables have already been renamed to _old — a checkpoint with rec.Phase != "". That error is deliberately not wrapped with errCheckpointUnresumable, so isDefinitivelyUnresumable returns false and force cannot reach the wipe. Correct, and the kind of exclusion that is easy to get wrong by wrapping "all checkpoint problems" with one sentinel. Same for the incompatible-version and read-failure cases the PR body calls out as intentionally transient.

The alias guard runs before anything touches a target. RequireDifferentDatabase sits in Run after target resolution and sorting but before maybeResumeReverseWindow and setupUnderLocks — so ahead of target table creation, ahead of wipeTargets, and ahead of the cutover rename that would be catastrophic under an alias. Everything preceding it is connection setup and sorting.

The position check's new pos == "" arm is a real tightening. if pos, ok := positions[key]; !ok || pos == "" now rejects a present-but-empty position rather than passing it to StartFromPosition. The two conditions share one message, but "checkpoint missing binlog position for source %s" is accurate for both readings, so this isn't the conflation it might look like.

--force no longer contradicts its own advice. The age-check error changed from "wipe the target tables … and restart" to "re-run with --force to wipe the target tables", and isDefinitivelyUnresumable now makes that advice actually work — the two halves of that change are consistent, which is what the equivalent fix in the datasync runner also needed.

Local: go build ./... clean, go vet ./pkg/move/... ./pkg/dbconn/ clean, gofmt -l empty, golangci-lint run ./pkg/move/... ./pkg/dbconn/... → 0 issues. CI 15/15 green. pkg/move/check and pkg/move both need a live MySQL (confirmed locally — Access denied for user 'spirit'@'localhost'), so all five new tests were read rather than run here.

This review was generated by Claude Code (claude-opus-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Approved — validating source-side checks before the wipe is the right shape, and restricting forced recovery to typed sentinels keeps a transient read failure from becoming permission to destroy a partial copy. Worth calling out in the summary that the reordered watermark assignment is a co-requisite of the new force path rather than cleanup: without it, forced recovery would have opened the checksum chunker at the abandoned attempt's watermark. Findings in a separate comment.

This stamp was left by Claude Code (claude-opus-5).

@morgo

morgo commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

🤖 Addressed the approval feedback in 2077d84b: post-setup checks now run deterministically by name; the exclusion path has direct coverage and uses the regular RunChecks API; force fallback explicitly clears checkpoint-derived checksum state; and source/target identities are resolved once per connection for sharded moves. I also updated the PR summary to call out the validation-before-state-mutation invariant.

@morgo
morgo enabled auto-merge (squash) September 5, 2026 17:38
@morgo
morgo merged commit f763a0e into block:main Sep 5, 2026
15 checks passed
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.

3 participants