affinity: stale Region cache leaks when a cached Region's key range leaves the group
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Idoneità per principianti
- 74/100
Direzione di ricerca
Inizia in pkg/schedule/affinity/manager.go da calcRegionAffinityGroupState, in particolare il percorso di ritorno group == nil, e confrontalo con il modo in cui InvalidCache rimuove le voci da m.regions e groupInfo.Regions (attenzione a labelRuleVer e al locking). Riproduci prima aggiungendo il TestStaleCacheLeakWhenCachedRegionLeavesGroup dell'issue sotto pkg/schedule/affinity ed eseguendo go test ./pkg/schedule/affinity -run TestStaleCacheLeakWhenCachedRegionLeavesGroup. Fatto significa che la voce obsoleta viene rimossa e che l'asserzione finale g1.RegionCount di quel test passa, con i test di affinità esistenti ancora verdi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
Bug Report
What did you do?
A Region that was previously cached inside an affinity group (Manager.regions[id] and runtimeGroupInfo.Regions[id]) changed its key range and left the affinity group while keeping the same Region ID.
Specifically, in pkg/schedule/affinity/manager.go (calcRegionAffinityGroupState, lines 395–421, introduced in #9997 and updated in #10080; related stale-cache handling in #11451):
func (m *Manager) calcRegionAffinityGroupState(region *core.RegionInfo, saveCache bool) (group *GroupState, isAffinity bool) {
if region == nil || !m.IsAvailable() {
return nil, false
}
var cache *regionCache
cache, group = m.getCache(region)
if cache == nil || group == nil || cache.affinityVer != group.affinityVer || region != cache.region {
labelRuleVer := m.labelRuleVer.Load()
groupID := m.regionLabeler.GetRegionLabel(region, AffinityLabelKey)
failpoint.InjectCall("afterRegionLabelLookup")
group = m.GetAffinityGroupState(groupID)
if group == nil {
return nil, false // <-- does not evict stale cache entry when saveCache && cache != nil
}
...
When a Region's key range changes while preserving its Region ID (for example, when an out-of-group adjacent Region is merged into an in-group Region via merge-region, followed by PD's boundary split keeping the original Region ID on the right half outside the group), RegionsInfo.setRegionLocked (pkg/core/region.go#L1381-L1394) intentionally excludes the Region's own ID from overlaps. As a result, cluster.HandleOverlaps (pkg/cluster/cluster.go#L67-L69) only invalidates the merged-away Region's ID and never calls affinityManager.InvalidCache(survivingRegionID).
On subsequent AffinityChecker patrol rounds, GetAndCacheRegionAffinityGroupState(region) observes region != cache.region, looks up groupID == "" / group == nil, and returns (nil, false) directly without deleting the stale entry from m.regions and groupInfo.Regions.
Minimal Unit Test Reproduction (pkg/schedule/affinity)
func TestStaleCacheLeakWhenCachedRegionLeavesGroup(t *testing.T) {
re := require.New(t)
ctx := t.Context()
store := storage.NewStorageWithMemoryBackend()
bc := core.NewBasicCluster()
for i := uint64(1); i <= 2; i++ {
s := core.NewStoreInfo(&metapb.Store{Id: i, Address: fmt.Sprintf("127.0.0.1:2016%d", i)})
s = s.Clone(core.SetLastHeartbeatTS(time.Now()))
bc.PutStore(s)
}
opt := mockconfig.NewTestOptions()
opt.SetAffinityScheduleLimit(4)
rl, err := labeler.NewRegionLabeler(ctx, store, 5*time.Second)
re.NoError(err)
mgr, err := NewManager(ctx, store, bc, opt, rl)
re.NoError(err)
// 1. Create affinity group g1 covering [a, b) with target store 1.
re.NoError(mgr.CreateAffinityGroups([]GroupKeyRanges{{
GroupID: "g1",
KeyRanges: []keyutil.KeyRange{{StartKey: []byte("a"), EndKey: []byte("b")}},
}}))
_, err = mgr.UpdateAffinityGroupPeers("g1", 1, []uint64{1})
re.NoError(err)
// 2. r101=[a, b) is initially on store 2 (not affinity) and cached by AffinityChecker.
r101 := core.NewRegionInfo(
&metapb.Region{
Id: 101,
StartKey: []byte("a"),
EndKey: []byte("b"),
Peers: []*metapb.Peer{{Id: 1011, StoreId: 2, Role: metapb.PeerRole_Voter}},
},
&metapb.Peer{Id: 1011, StoreId: 2, Role: metapb.PeerRole_Voter},
)
r102 := core.NewRegionInfo(
&metapb.Region{
Id: 102,
StartKey: []byte("b"),
EndKey: []byte("c"),
Peers: []*metapb.Peer{{Id: 1021, StoreId: 1, Role: metapb.PeerRole_Voter}},
},
&metapb.Peer{Id: 1021, StoreId: 1, Role: metapb.PeerRole_Voter},
)
bc.PutRegion(r101)
bc.PutRegion(r102)
st, isAff := mgr.GetAndCacheRegionAffinityGroupState(r101)
re.NotNil(st)
re.Equal("g1", st.ID)
re.False(isAff)
// 3. r102 merges into r101 => surviving r101 expands to [a, c), outside g1=[a, b).
// BasicCluster.PutRegion only returns r102 in overlaps, not r101 itself.
r101Merged := r101.Clone(core.WithEndKey([]byte("c")))
for _, ov := range bc.PutRegion(r101Merged) {
mgr.InvalidCache(ov.GetID())
}
// 4. Next patrol checks r101Merged; it no longer belongs to g1.
stAfter, isAffAfter := mgr.GetAndCacheRegionAffinityGroupState(r101Merged)
re.Nil(stAfter)
re.False(isAffAfter)
// 5. Fails on master: g1 still reports RegionCount == 1 (Phase == "preparing").
g1 := mgr.GetAffinityGroupState("g1")
re.Zero(g1.RegionCount)
}
Real Cluster Reproduction Steps (1 PD + 2 TiKV + 1 TiDB, max-replicas = 1, affinity-schedule-limit = 4)
-
Create an affinity table with 2 Regions in TiDB:
CREATE DATABASE IF NOT EXISTS aff_verify; USE aff_verify; CREATE TABLE t_stuck (id INT PRIMARY KEY, v VARCHAR(64)) AFFINITY = 'table'; SPLIT TABLE t_stuck BETWEEN (0) AND (100000) REGIONS 2;Verify
SHOW TABLE t_stuck REGIONS;shows 2 Regions (sayR_leftandR_right, both on Store 1) andSHOW AFFINITY;showsStatus = Stable, Region_count = 2, Affinity_region_count = 2. -
Temporarily pause affinity scheduling and set the group's target to Store 4 so both Regions are cached as
isAffinity = false(Preparing):curl -X POST http://<pd-addr>:2379/pd/api/v1/config \ -H "Content-Type: application/json" -d '{"affinity-schedule-limit": 0}' curl -X PUT http://<pd-addr>:2379/pd/api/v2/affinity-groups/_tidb_t_<table_id> \ -H "Content-Type: application/json" -d '{"leader_store_id": 4, "voter_store_ids": [4]}'Wait 2 seconds and confirm
SHOW AFFINITY;showsStatus = Preparing, Region_count = 2, Affinity_region_count = 0. -
Find the adjacent Region
R_outsideimmediately to the right ofR_right(R_outside.start_key == R_right.end_key), and mergeR_outsideintoR_right:curl -X POST http://<pd-addr>:2379/pd/api/v1/operators \ -H "Content-Type: application/json" \ -d '{"name":"merge-region","source_region_id": <R_outside>, "target_region_id": <R_right>}'After the merge, PD's split checker splits the merged Region at the table's affinity boundary: a new Region ID is created for the left half inside
t_stuck, while the original ID<R_right>stays on the right half outsidet_stuck. -
Re-enable affinity scheduling (
affinity-schedule-limit = 4) and wait for all Regions oft_stuckto migrate to Store 4:curl -X POST http://<pd-addr>:2379/pd/api/v1/config \ -H "Content-Type: application/json" -d '{"affinity-schedule-limit": 4}'Check
SHOW TABLE t_stuck REGIONS;,SHOW AFFINITY;,GET /pd/api/v2/affinity-groups, andGET /metrics(pd_affinity_status).
What did you expect to see?
- When
GetAndCacheRegionAffinityGroupStaterecalculates a cached Region whose key range no longer matches any affinity group (group == nil), it should evict the stale entry forregion.GetID()fromm.regionsandgroupInfo.Regions(respectinglabelRuleVer/ locking). - After all 2 actual Regions of
t_stuckmigrate to Store 4,SHOW AFFINITYand/pd/api/v2/affinity-groupsshould reportRegion_count = 2,Affinity_region_count = 2, andStatus / phase = Stable, andpd_affinity_statusmetrics should match the actual count of affinity Regions.
What did you see instead?
SHOW TABLE t_stuck REGIONSshows 2 actual Regions (155and170), both 100% aligned on Store 4:REGION_ID START_KEY END_KEY LEADER_STORE_ID 155 t_135_ t_135_r_50000 4 170 t_135_r_50000 t_136_ 4- Yet
SHOW AFFINITYandGET /pd/api/v2/affinity-groups/_tidb_t_135permanently report 3 Regions and stay stuck inPreparingindefinitely (even after waiting minutes / thousands of patrol rounds), because Region153(now covering keys outsidet_stuckon Store 1) remains leaked in the group's cache withisAffinity = false:Db_name Table_name Leader_store_id Voter_store_ids Status Region_count Affinity_region_count aff_verify t_stuck 4 4 Preparing 3 2{ "id": "_tidb_t_135", "leader_store_id": 4, "voter_store_ids": [4], "phase": "preparing", "range_count": 1, "region_count": 3, "affinity_region_count": 2 } - Similarly, if the leaked Region was previously cached with
isAffinity = true,region_countandaffinity_region_countare permanently inflated by+1(and Prometheuspd_affinity_status{type="region-count"}/pd_affinity_status{type="affinity-region-count"}drift permanently upward), and the stale*core.RegionInfopointer leaks in memory until the group is deleted or PD restarts / transfers leader.
What version of PD are you using (pd-server -V)?
Release Version: v9.0.0-beta.2.pre-624-g832369c
Git Commit Hash: 832369c415d4f9ab86c8e1cd79bf583d342b1a84
Kernel Type: Classic
Introduced in #9997 / #10080 (related: #11451).
- Lingua principale
- Go
- Stelle
- 1.2k
- Fork
- 794
- Merge medio
- 5g 32m
- PR unite (30g)
- 81
Preparare l'ambiente
- Include un Dockerfile o un file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di tikv/pd
-
needs-type
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
type/ci
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
affects-8.5 contribution needs-type
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno
-
contribution type/enhancement
Difficoltà 2/5 1-3 ore Idoneità per principianti 88/100
I maintainer di solito rispondono entro 1 giorno
-
contribution type/enhancement
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
I maintainer di solito rispondono entro 1 giorno
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
projectdiscovery/dnsx#1113 ·
I maintainer di solito rispondono entro 1 giorno
-
enhancement needs:triage
Difficoltà 2/5 1-3 ore Idoneità per principianti 83/100
crossplane-contrib/provider-upjet-azure#1374 ·
I maintainer di solito rispondono entro 2 giorni
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
I maintainer di solito rispondono entro 1 giorno
-
agent-in-progress
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
jordansmall/spindrift#7716 ·
I maintainer di solito rispondono entro 1 giorno
-
bug 🪲 needs-triage :mag:
Difficoltà 2/5 1-3 ore Idoneità per principianti 67/100
Azure/azure-service-operator#5880 ·
I maintainer di solito rispondono entro 1 giorno