affinity: stale Region cache leaks when a cached Region's key range leaves the group
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 74/100
Research direction
Start in pkg/schedule/affinity/manager.go at calcRegionAffinityGroupState, specifically the group == nil return path, and compare it with how InvalidCache removes entries from m.regions and groupInfo.Regions (mind labelRuleVer and locking). Reproduce first by adding the issue's TestStaleCacheLeakWhenCachedRegionLeavesGroup under pkg/schedule/affinity and running go test ./pkg/schedule/affinity -run TestStaleCacheLeakWhenCachedRegionLeavesGroup. Done means the stale entry is evicted and that test's final g1.RegionCount assertion passes, with existing affinity tests still green.
Written by the indexing model from the issue text.
Description
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).
- Dominant language
- Go
- Stars
- 1.2k
- Forks
- 794
- Avg merge
- 5d 32m
- Merged PRs (30d)
- 81
Getting set up
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from tikv/pd
-
needs-type
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
type/ci
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
affects-8.5 contribution needs-type
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 1 day
-
contribution type/enhancement
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
Maintainers usually reply within 1 day
-
contribution type/enhancement
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
agent-in-progress
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
jordansmall/spindrift#7716 ·
Maintainers usually reply within 1 day
-
bug 🪲 needs-triage :mag:
Difficulty 2/5 1-3 hours Newbie friendliness 67/100
Azure/azure-service-operator#5880 ·
Maintainers usually reply within 1 day
-
`create_branch` returns a bare 404 when the token has no push accessPossibly taken @aloneangel45 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
github/github-mcp-server#3994 ·
Maintainers usually reply within 2 days
-
Add rebaseWhen: conflicted to major Go module Renovate updatesPossibly taken @WadekarPrashant claimed this today. Openenhancement feature good first issue ready-for-triage triaged
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
konflux-ci/build-definitions#3943 · 3 comments ·
Maintainers usually reply within 1 day