EmergencyReparentShard: filter lagging candidates from relaylog wait, handle partial failures and split-brain#18707
Conversation
Review ChecklistHello reviewers! 👋 Please follow this checklist when reviewing this Pull Request. General
Tests
Documentation
New flags
If a workflow is added or modified:
Backward compatibility
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #18707 +/- ##
===========================================
- Coverage 69.67% 54.01% -15.66%
===========================================
Files 1614 111 -1503
Lines 216793 22840 -193953
===========================================
- Hits 151044 12337 -138707
+ Misses 65749 10503 -55246
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Copying some conclusions from an offline discussion with @arthurschreiber:
|
|
The reason, AFAIUI, for the current behavior is to prevent any of the healthy tablets from becoming forever unhealthy/unusable due to the new primary not having binary logs covering/containing the GTIDs that the lagging replica(s) may still need (the new primary may have recently been restored from a backup and have minimal binary logs). Have you already thought about that in this context? |
@mattlord I don't think that has changed, but I would appreciate you double checking my assumption because that is a very important functionality One part of the code that could affect that was actually changed in #18531. Previous to this PR, the code called The TL;DR on that wrapper func: we do the same sort but put now prioritise positions with the most advanced SQL thread if two combined sets are equal. In the end the same And in terms of being certain we're ignoring the right tablets: after |
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
Signed-off-by: Tim Vaillancourt <tim@timvaillancourt.com>
|
Promptless prepared a documentation update related to this change. Triggered by PR #18707 Added documentation for the new Review: EmergencyReparentShard: document split-brain detection and partial failure tolerance |
|
Docs PR: vitessio/website#2128 |
mattlord
left a comment
There was a problem hiding this comment.
We should not let split-brain override promote a lagging survivor in
go/vt/vtctl/reparentutil/emergency_reparenter.go:331-342. With AllowSplitBrainPromotion=true, errant-GTID detection restores the pre-detection set only when it removes every candidate. In the mixed case of two mutually-errant leading candidates plus a lagging survivor, both leaders can be pruned while the lagger remains, so ERS can re-wait and promote the lagger. That loses the unique writes from both split-brain sides, which is worse than the advertised “pick one side; losing side becomes errant” semantics. Please either require/validate --new-primary for this override path or restore/limit to the pre-errant leading set when all leading split-brain candidates are pruned and add a regression test with two mutually-errant leaders plus a lagging survivor.
We should preserve SQL-thread state during failed-ERS cleanup in
go/vt/vtctl/reparentutil/replication.go:283-285, go/vt/vtctl/reparentutil/emergency_reparenter.go:487-490. The new cleanup restarts any replica whose IO thread was healthy before ERS stopped it, but it calls StartReplication, which starts both IO and SQL threads. If a replica intentionally had SQL_THREAD stopped but IO running before ERS, an early abort will restart SQL unexpectedly. Cleanup should restore the original thread state exactly, or avoid calling full StartReplication for SQL-stopped replicas and cover that case with a unit test.
Description
After
StopReplicationAndGetStatuscompletes during ERS, replication is stopped on all tablets and theirCombined(relay log) positions are frozen. Today ERS waits for all tablets to apply relay logs before picking a winner — but a tablet whoseCombinedposition is strictly behind the leading group can never win. Waiting for it is pointless and can only hurt us (by timing out the entire ERS over a tablet that was never a contender)Filtering out known-problem tablets early make reparents less brittle and faster 🚀
This PR address two major gaps in ERS (#18529 and #20199) by making ERS more tolerant of lagging tablets and better at detect split-brains, while preserving the
AGENTS.md/CLAUDE.mdcontracts that we must pick the most-advanced candidate with certainty and must error out when that candidate isn't clearWhat changed
GTID-only relay-log-apply optimisation — for GTID-based replication,
Combinedis the received relay-log position, so we can prove which tablets can never win and filter them out of the wait. Tablets at the leadingCombinedposition are waited on; the first success short-circuits the rest. Lagging tablets stay in the candidate pool (they can still be repointed at the new primary later), they just don't block the wait phase. For non-GTID flavours (FilePos, MariaDB) this optimisation is unsafe —Combinedthere is the executed position and doesn't reflect received-but-not-applied relay logs — so those flavours keep the pre-PRrequireAll=truebehaviour unchangedFail-fast on suspected split-brain —
filterToMostAdvancedCombined()uses pairwise dominance (not "compare to a single max") so it correctly handles partially-ordered GTID sets. If the leading group has incomparableCombinedpositions (two tablets with disjoint UUIDs, neither dominating the other) we now abort upfront withFAILED_PRECONDITIONand a list of the diverged tablets, rather than silently pick one side. The filter + uniform check + metric increment are consolidated in a newfilterAndCheckUniform()helper so both call sites (first wait and errant-GTID re-wait) get identical semanticsErrant-GTID re-wait pass — errant filtering can remove every originally-applied tablet, leaving only "unwaited survivors" (tablets cancelled mid-apply by our own short-circuit, or strictly-behind tablets we excluded from the first wait). Promoting one of those would risk a primary with received-but-unapplied transactions 😱 We detect this case (no applied tablet survives errant detection) and run a second
filterAndCheckUniform→ wait pipeline over the survivors before promotion. The uniformity re-check is mandatory — the survivor set is a different shape than the original leading group and could have its own split-brain signal--allow-split-brain-promotionoperator escape hatch — by default the upfrontuniformCombinedcheck aborts ERS withFAILED_PRECONDITIONon incomparable Combined positions, which is the safe behaviour but can leave a shard without a primary in genuine split-brain scenarios where the operator already knows which side to keep. Setting--allow-split-brain-promotion=true(off by default) converts the abort into aWARNlog naming both diverged tablets + their positions, increments a newEmergencyReparentSplitBrainOverridescounter, and lets ERS proceed. The losing side's unique GTIDs become errant after promotion — the flag is a deliberate operator override, not a default. Flag is wired through the proto (field 9 onEmergencyReparentShardRequest),vtctldclient(--allow-split-brain-promotion), legacyvtctl(--allow_split_brain_promotion), and theEmergencyReparentOptionsstruct. ThefindMostAdvancedsecondary split-brain check honours the same flag for consistencyImplementation details
A few smaller mechanics behind the headline changes:
applyRelayLogsAndReconcile()helper — applied tablets getExecutedbumped toCombinedso the existing sorter prefers them via theCombined→Executed→ promotion-rule tiebreak; failed tablets are removed fromvalidCandidates, cancelled ones are left untouchedstatusMap(current/stuck PRIMARY fromErrNotReplica) has no relay logs to apply, so it's markedtrueinsuccessMapupfront. This bumps itsExecuted = Combinedin reconcile, preventing cancelled-mid-apply peers (non-zero pre-waitExecuted) from sorting ahead of it infindMostAdvancedgroupCancel()or from a cancelled parent context are treated as expected noise (must check botherrors.Is(err, context.Canceled)and gRPC-wrappedvtrpc.Code_CANCELED, since the latter does not satisfy the former). When the parent ctx is cancelled with no real failure to surface, we return the wrappedctx.Err()directly so operators see "aborted while waiting for relay logs to apply"Stats
Three new stats are exported for observability:
EmergencyReparentFilteredCandidates{Keyspace, Shard}— tablets excluded from the relay-log wait because theirCombinedposition is strictly behind the leading group. A single ERS run may increment this twice if errant-GTID detection forces a second wait pass over the surviving candidatesEmergencyReparentRelayLogFailedCandidates{Keyspace, Shard}— tablets that genuinely failed to apply relay logs (RPC error, MySQL error, or timeout). Cancellations after a peer succeeded — or after parent-ctx cancel — are not counted. The metric is also incremented on the error path before any abort returns, so operators can still see failure counts when ERS aborts for some other reasonEmergencyReparentSplitBrainOverrides{Keyspace, Shard}— ERS runs that proceeded despite incomparable Combined positions because--allow-split-brain-promotionwas set. Always zero unless an operator has deliberately invoked the escape hatchTesting
E2E tests in
ers_test.go:TestERSFiltersNonMostAdvancedCandidates— stops the IO thread on one replica, writes data the lagger won't see, kills the primary, runs ERS, then assertsEmergencyReparentFilteredCandidatesincremented via the vtctld/debug/varsendpoint and that the lagging tablet was not chosen as the new primaryTestERSSplitBrainDetection— detaches two replicas and writes to each independently to produce two-sided GTID divergence, then asserts ERS aborts with the upfront"suspected split-brain"error naming both diverged tabletsTestReplicationStoppedupdated — previously asserted ERS failed with 2 replicas having replication stopped; now asserts ERS succeeds with the third tablet as the surviving candidate, since partial relay-log failures are toleratede2eutils.SkipIfBinaryIsBelowVersion(t, 25, "vtctld")so theReparent Old Vtctlupgrade-downgrade job (which runs against the previous release'svtctld) skips them cleanlyRelated Issue(s)
Resolves: #18529
Resolves: #20199
Checklist
Deployment Notes
This is a user-visible behavioural change in
EmergencyReparentShardand is called out inchangelog/25.0/25.0.0/summary.mdunder VTCtld. No new required flags or configuration — the one new flag is an opt-in operator escape hatch:GTID-based shards — ERS now tolerates a minority of replicas failing or hanging during the relay-log-apply wait. As long as at least one tablet at the leading
Combinedposition applies successfully (or a no-status PRIMARY-like tablet is present at that position), ERS proceeds. The pre-PR behaviour (any single failure aborts ERS) was unnecessarily fragileNon-GTID shards (FilePos, MariaDB) — behaviour is unchanged. The optimisation is gated on
isGTIDBasedand these flavours still wait for every candidateSuspected split-brain — when the leading GTID candidates have incomparable
Combinedpositions, ERS now aborts upfront with aFAILED_PRECONDITIONerror naming the diverged tablets, rather than silently picking one side. This is a stricter check than before and may surface as a new failure mode on shards that previously survived a split-brain scenario by luck. The pre-PR behaviour was silent data loss + errant GTIDs on the losing side — this PR converts that invisible data-integrity incident into a visible operational one. See Bug Report: EmergencyReparentShard silently promotes one side in a split-brain, leaving errant GTIDs #20199 for the bug--allow-split-brain-promotion(off by default) — operators who deliberately need to force ERS through a detected split-brain (eg: they know which side to keep, plan to manually re-clone the losing side after) can set this flag. ERS will log aWARNnaming the diverged tablets + their positions, incrementEmergencyReparentSplitBrainOverrides, and proceed. The losing side's unique GTIDs will become errant after promotion — the flag is an override, not a default. Available as--allow-split-brain-promotion(vtctldclient) and--allow_split_brain_promotion(legacyvtctl)Three new stats (
EmergencyReparentFilteredCandidates,EmergencyReparentRelayLogFailedCandidates,EmergencyReparentSplitBrainOverrides) are exported from vtctld for operators to track filter, failure, and split-brain-override counts per keyspace/shardAI Disclosure
Claude Code assisted with development, testing and this PR summary