[release-8.5] ResetRegionCache leaves live Regions missing from per-store indexes after heartbeats

Aperta
#11,624 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à
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
38/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
go
Ambito
backend, databases

Direzione di ricerca

Read pkg/core/region.go, especially ResetRegionCache and UpdateSubTreeOrderInsensitive; the report identifies stale subRegions entries and the required mutex for clearing them. Start by adding same-ID rebuild regression coverage in pkg/core, then check concurrent reset/update behavior and the recovery integration path. Done means unchanged-topology updates restore per-store counts, size, overlap entries, and leader candidates, with race and recovery coverage.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

contribution type/bug

Bug Report

This is a release-8.5 follow-up to #9657, with a core-level reproduction showing missing scheduling candidates as well as incorrect statistics. Master has #9658 and the subsequent locking correction #10165, but the reset remains incomplete on release-8.5.

What did you do?

Ran a local regression test against v8.5.8 (4ecadf2f59e4fa04fe0e611c6d7808e8b1806ce7), using the production core APIs called by the split root/subtree heartbeat path:

  1. Populate RegionsInfo with one Region: ID 1, leader on store 1, range [a,b), approximate size 64.
  2. Update it through CheckAndPutRootTree followed by CheckAndPutSubTree.
  3. Call ResetRegionCache().
  4. Apply three more updates for the same Region through the same APIs. Only flow statistics change; ID, range, leader and peers remain unchanged.
  5. Check the root lookup, per-store counts/size, overlap tree and RandLeaderRegions.
  6. In separate control subtests, change either the peer set or key range after those three updates.

This is a sequential core API test, not an RPC heartbeat test or a full Unsafe Recovery cluster reproduction.

Complete regression test

Save as pkg/core/issue9657_probe_test.go in an unpatched v8.5.8 checkout:

package core

import (
	"testing"

	"github.com/pingcap/kvproto/pkg/metapb"
	"github.com/stretchr/testify/require"
)

// TestIssue9657ResetRebuild drives the same split root/subtree APIs as heartbeat processing.
// It expects consistency, so the unpatched baseline must fail the unchanged case.
func TestIssue9657ResetRebuild(t *testing.T) {
	for _, change := range []string{"unchanged", "peer", "range"} {
		t.Run(change, func(t *testing.T) {
			r := NewRegionsInfo()
			region := NewTestRegionInfo(1, 1, []byte("a"), []byte("b"), SetApproximateSize(64))
			put := func(region *RegionInfo) {
				_, err := r.CheckAndPutRootTree(ContextTODO(), region)
				require.NoError(t, err)
				r.CheckAndPutSubTree(region)
			}
			logState := func(stage string) {
				t.Logf("%s: root=%d subRegions=%d storeRegions=%d storeLeaders=%d storeSize=%d candidates=%d overlap=%d", stage,
					r.GetTotalRegionCount(), len(r.subRegions), r.GetStoreRegionCount(1), r.GetStoreLeaderCount(1),
					r.GetStoreRegionSize(1), len(r.RandLeaderRegions(1, nil)), r.overlapTree.length())
			}
			put(region)
			require.Equal(t, 1, r.GetStoreLeaderCount(1))
			logState("before-reset")
			r.ResetRegionCache()
			logState("after-reset")
			for i := 0; i < 3; i++ {
				region = region.Clone(SetWrittenBytes(uint64(i + 1)))
				put(region)
				logState("unchanged-heartbeat")
			}
			switch change {
			case "peer":
				region = region.Clone(WithAddPeer(&metapb.Peer{Id: 2, StoreId: 2}), WithIncConfVer())
				put(region)
				logState("peer-change")
			case "range":
				region = region.Clone(WithEndKey([]byte("c")), WithIncVersion())
				put(region)
				logState("range-change")
			}
			require.Equal(t, 1, r.GetTotalRegionCount())
			require.NotNil(t, r.GetRegionByKey([]byte("a")))
			require.Equal(t, 1, r.GetStoreRegionCount(1), "root region must be reflected in store subtree")
			require.Equal(t, 1, r.GetStoreLeaderCount(1))
			require.EqualValues(t, 64, r.GetStoreRegionSize(1))
			require.NotEmpty(t, r.RandLeaderRegions(1, nil))
		})
	}
}

The test asserts the expected consistent state, so its unchanged subtest intentionally fails on the affected source.

The recorded run used these commands with failpoint-ctl already built and available on PATH; -o install-tools skips reinstalling the tool set:

make -o install-tools PACKAGES=github.com/tikv/pd/pkg/core failpoint-enable
go test ./pkg/core -run '^TestIssue9657ResetRebuild$' -count=1 -v
make -o install-tools PACKAGES=github.com/tikv/pd/pkg/core failpoint-disable

Failpoints were disabled after both the baseline and fixed-control runs.

Production callers of the reset include:

What did you expect to see?

Once a Region is reported again after reset, the root and per-store indexes should agree. With this one-Region fixture, the first update should restore:

  • Root Region count and store Region/leader count to 1.
  • Store Region size to 64.
  • A nonempty RandLeaderRegions(1, nil) result and an overlap-tree entry.

Rebuilding the index should not require a peer, leader or key-range change.

What did you see instead?
Observed test results
Stage Root count subRegions entries Store Region count Store leader count Store Region size Leader candidates overlapTree entries
Before reset 1 1 1 1 64 nonempty 1
Immediately after reset 0 1 0 0 0 empty 0
After each of three unchanged-topology updates 1 1 0 0 0 empty 0
After a peer change (independent subtest) 1 1 1 1 64 nonempty 1
After a range change (independent subtest) 1 1 1 1 64 nonempty 1

GetRegionByKey("a") succeeds, but the per-store index still does not contain the Region. The unchanged subtest fails with expected: 1, actual: 0 for GetStoreRegionCount(1). The peer-change and range-change subtests pass.

Relevant baseline output:

before-reset: root=1 subRegions=1 storeRegions=1 storeLeaders=1 storeSize=64 candidates=10 overlap=1
after-reset: root=0 subRegions=1 storeRegions=0 storeLeaders=0 storeSize=0 candidates=0 overlap=0
unchanged-heartbeat: root=1 subRegions=1 storeRegions=0 storeLeaders=0 storeSize=0 candidates=0 overlap=0
unchanged-heartbeat: root=1 subRegions=1 storeRegions=0 storeLeaders=0 storeSize=0 candidates=0 overlap=0
unchanged-heartbeat: root=1 subRegions=1 storeRegions=0 storeLeaders=0 storeSize=0 candidates=0 overlap=0
--- FAIL: TestIssue9657ResetRebuild
    --- FAIL: TestIssue9657ResetRebuild/unchanged
    --- PASS: TestIssue9657ResetRebuild/peer
    --- PASS: TestIssue9657ResetRebuild/range

The candidate count of 10 is the random selection sample count, not 10 distinct Regions. The relevant signal is empty versus nonempty selection.

Root cause

ResetRegionCache clears the root tree/map, all per-store trees and the overlap tree, but leaves subRegions populated.

UpdateSubTreeOrderInsensitive / preUpdateSubTreeLocked then finds the stale same-ID entry. When range and peer composition are unchanged, it follows the statistics-only branch and returns without reinserting into the emptied per-store trees. This explains why more updates with unchanged topology do not rebuild those entries.

The reset is global, so Regions unaffected by the failed stores can also be omitted from the per-store indexes. Ordinary operation without a reset is not the trigger identified here.

Expected user impact
  • Confirmed at core level: live Regions can remain absent from per-store statistics and scheduler candidate selection across repeated updates.
  • Monitoring consequence from the call chain: BasicCluster.UpdateStoreStatus derives counts/sizes from these indexes, and store_collection.go publishes them. This supports the abnormal Region/peer statistics originally reported in #9657.
  • Scheduling consequence from the call chain: balance-region, balance-leader, and evict-leader use the affected per-store candidates and/or statistics. Missing entries can prevent these paths from selecting live Regions and distort balancing decisions after recovery. End-to-end scheduler behavior was not executed in this test.
  • The trigger is infrequent, but its scope can span the cluster's cached Regions. This merits an 8.5 maintenance backport rather than treating the symptom only as a dashboard discrepancy.

This test does not establish data loss, SQL errors, cluster-wide unavailability, or failure of every scheduler. The root lookup recovers in the test. Unsafe Recovery's inherent lossy semantics are separate from this cache defect.

Related #8634 addresses rebalancing before heartbeats have refilled the cache. Here the same Region has already been processed repeatedly and its per-store index remains absent.

Fixed control and backport proposal

Added the following line inside the existing r.st critical section in ResetRegionCache:

 r.st.Lock()
 defer r.st.Unlock()
+r.subRegions = make(map[uint64]*regionItem)
 r.leaders = make(map[uint64]*regionTree)

With this change, the first unchanged-topology update restores count=1, size=64 and nonempty candidates. The same test passes all three subtests:

--- PASS: TestIssue9657ResetRebuild
    --- PASS: TestIssue9657ResetRebuild/unchanged
    --- PASS: TestIssue9657ResetRebuild/peer
    --- PASS: TestIssue9657ResetRebuild/range
PASS

Please backport the combined final semantics of #9658 and #10165 to release-8.5. #9658 initially put the assignment under r.t; #10165 moved it under the correct subtree mutex r.st. Backporting #9658 alone would miss that locking correction.

The change is local in-memory bookkeeping, with no persisted format, wire protocol or configuration default change. Before merging the backport, retain same-ID rebuild regression coverage and add concurrent reset/update race coverage and a recovery integration smoke test. The local test above only validates sequential core behavior; it does not prove concurrency safety.

What version of PD are you using (pd-server -V)?

No pd-server binary was started for this reproduction.

  • Runtime-tested source: v8.5.8, commit 4ecadf2f59e4fa04fe0e611c6d7808e8b1806ce7.
  • Test environment: Go go1.25.12 darwin/arm64.
  • Source inspection on 2026-11-19: stable tags v8.5.0 through v8.5.8 and release-8.5 HEAD aa9ae7b62fcbc27e4d99954150f784a15fd6e25b all omit the subRegions reset. The defect-relevant reset/subtree logic and heartbeat function in the tested v8.5.8 snapshot match this branch head.
  • Early 8.5 path check: v8.5.0 and v8.5.3 also use the split root/subtree update path. Disabling enable-heartbeat-concurrent-runner changes the runner, but does not bypass that path.
  • Existing master fixes: #9658 (af9ddbe0fbdd9747ce1a21c63ea8035a90ac2461) and #10165 (b273ae0421dd1c8344eb0a073c782bbd7de2557b). This report tracks the remaining release-8.5 exposure.
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.