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

Aperta Adatta ai principianti
#11,639 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

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
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
go
Ambito
backend

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

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).

Lingua principale
Go
Stelle
1.2k
Fork
794
Merge medio
5g 32m
PR unite (30g)
81

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di tikv/pd

Tutte le issue di tikv/pd

Issue simili

Altre issue su Go

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.