affinity: stale Region cache leaks when a cached Region's key range leaves the group

Open Beginner friendly
#11,639 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
go
Domain
backend

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

contribution type/bug

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)
  1. 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 (say R_left and R_right, both on Store 1) and SHOW AFFINITY; shows Status = Stable, Region_count = 2, Affinity_region_count = 2.

  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; shows Status = Preparing, Region_count = 2, Affinity_region_count = 0.

  3. Find the adjacent Region R_outside immediately to the right of R_right (R_outside.start_key == R_right.end_key), and merge R_outside into R_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 outside t_stuck.

  4. Re-enable affinity scheduling (affinity-schedule-limit = 4) and wait for all Regions of t_stuck to 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, and GET /metrics (pd_affinity_status).

What did you expect to see?
  • When GetAndCacheRegionAffinityGroupState recalculates a cached Region whose key range no longer matches any affinity group (group == nil), it should evict the stale entry for region.GetID() from m.regions and groupInfo.Regions (respecting labelRuleVer / locking).
  • After all 2 actual Regions of t_stuck migrate to Store 4, SHOW AFFINITY and /pd/api/v2/affinity-groups should report Region_count = 2, Affinity_region_count = 2, and Status / phase = Stable, and pd_affinity_status metrics should match the actual count of affinity Regions.
What did you see instead?
  • SHOW TABLE t_stuck REGIONS shows 2 actual Regions (155 and 170), 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 AFFINITY and GET /pd/api/v2/affinity-groups/_tidb_t_135 permanently report 3 Regions and stay stuck in Preparing indefinitely (even after waiting minutes / thousands of patrol rounds), because Region 153 (now covering keys outside t_stuck on Store 1) remains leaked in the group's cache with isAffinity = 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_count and affinity_region_count are permanently inflated by +1 (and Prometheus pd_affinity_status{type="region-count"} / pd_affinity_status{type="affinity-region-count"} drift permanently upward), and the stale *core.RegionInfo pointer 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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from tikv/pd

All issues in tikv/pd

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.