Skip to content

planner: cache mpp info to avoid frequent grpc calling (#65694) - #69403

Merged
ti-chi-bot[bot] merged 2 commits into
pingcap:release-8.5from
ti-chi-bot:cherry-pick-65694-to-release-8.5
Sep 3, 2026
Merged

ti-chi-bot[bot] merged 2 commits into
pingcap:release-8.5from
ti-chi-bot:cherry-pick-65694-to-release-8.5

Conversation

@ti-chi-bot

@ti-chi-bot ti-chi-bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

This is an automated cherry-pick of #65694

What problem does this PR solve?

Issue Number: close #65701

Problem Summary:

What changed and how does it work?

We define a new struct called MPPInfoManager and set a global variable GlobalMPPInfoManager with MPPInfoManager type. mpp info are all cached in this variable. In getTiFlashServerMinLogicalCores, we will check the cache first then call grpc for uncached tiflash stores. When we get a failed tiflash store in filterAliveStoresHelper, we will remove it's cache.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

None

Summary by CodeRabbit

  • Performance Improvements

    • TiFlash query planning now reuses cached MPP server hardware info and refreshes only stale entries when computing minimum logical CPU cores.
  • Bug Fixes

    • Cluster server information retrieval now consolidates per-server outcomes so that failures don’t disrupt successful rows, returning results consistently.
  • Tests

    • Added and expanded test coverage for server-info cache behavior, refresh selection, and bounded eviction.

Signed-off-by: ti-chi-bot <ti-community-prow-bot@tidb.io>
@ti-chi-bot ti-chi-bot added do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. ok-to-test Indicates a PR is ready to be tested. release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/L Denotes a PR that changes 100-499 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR. labels Jun 23, 2026
@ti-chi-bot

Copy link
Copy Markdown
Member Author

@xzhangxian1008 This PR has conflicts, I have hold it.
Please resolve them or ask others to resolve them, then comment /unhold to remove the hold label.

@ti-chi-bot

ti-chi-bot Bot commented Jun 23, 2026

Copy link
Copy Markdown

@ti-chi-bot: ## If you want to know how to resolve it, please read the guide in TiDB Dev Guide.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the ti-community-infra/tichi repository.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 837db668-c3fd-4c48-bedb-bf4d1974c086

📥 Commits

Reviewing files that changed from the base of the PR and between ac99f1f and 49c2b61.

📒 Files selected for processing (2)
  • pkg/planner/core/optimizer.go
  • pkg/store/copr/BUILD.bazel
💤 Files with no reviewable changes (1)
  • pkg/planner/core/optimizer.go

📝 Walkthrough

Walkthrough

Introduces a global LRU cache (MppServerInfoManager) in pkg/store/copr for TiFlash/MPP server hardware info. Refactors FetchClusterServerInfoWithoutPrivilegeCheck in pkg/infoschema to return structured ServerInfoResult values instead of flattened rows plus an error. Updates the optimizer's getTiFlashServerMinLogicalCores to use a new splitTiFlashLogicalCoreCache helper that skips re-fetching up-to-date cache entries, only re-querying stale servers.

Changes

TiFlash Server Info Caching

Layer / File(s) Summary
MPP server info LRU cache
pkg/store/copr/BUILD.bazel, pkg/store/copr/mpp_probe.go, pkg/store/copr/mpp_probe_test.go
Adds MPPServerInfo struct, MppServerInfoManager with mutex-guarded Add/Delete/Get over a SimpleLRUCache (capacity 1000), a GlobalMPPServerInfoManager singleton initialized in init(), and TestMppServerInfoManager covering add/delete/get and eviction behavior.
ServerInfoResult struct and fetch refactor
pkg/infoschema/tables.go, pkg/executor/memtable_reader.go
Adds exported ServerInfoResult{Idx, Rows, Err} struct; changes FetchClusterServerInfoWithoutPrivilegeCheck return type from ([][]types.Datum, error) to []ServerInfoResult with per-goroutine index-sorted results; updates clusterServerInfoRetriever.retrieve to skip errored entries when assembling output rows.
Optimizer cache-split and conditional re-fetch
pkg/planner/core/optimizer.go, pkg/planner/core/optimizer_test.go, pkg/planner/core/BUILD.bazel
Adds splitTiFlashLogicalCoreCache to partition servers into cache-hit and stale sets; reworks getTiFlashServerMinLogicalCores to defer-time the fetch, use the helper, and re-query only stale servers while updating GlobalMPPServerInfoManager; adds copr to BUILD deps and tests the split logic with stale/valid server scenarios.

Sequence Diagram

sequenceDiagram
    participant Optimizer
    participant splitTiFlashLogicalCoreCache
    participant GlobalMPPServerInfoManager
    participant FetchCluster as FetchClusterServerInfoWithoutPrivilegeCheck
    participant Goroutines

    Optimizer->>splitTiFlashLogicalCoreCache: tiflashServersInfo
    splitTiFlashLogicalCoreCache->>GlobalMPPServerInfoManager: Get(address) per server
    GlobalMPPServerInfoManager-->>splitTiFlashLogicalCoreCache: MPPServerInfo or nil
    splitTiFlashLogicalCoreCache-->>Optimizer: serversNeedingRefresh, minLogicalCores

    alt serversNeedingRefresh not empty
        Optimizer->>FetchCluster: serversNeedingRefresh, HardwareInfo
        FetchCluster->>Goroutines: spawn per-server goroutines
        Goroutines-->>FetchCluster: ServerInfoResult{Idx, Rows or Err}
        FetchCluster-->>Optimizer: []ServerInfoResult (sorted by Idx)
        Optimizer->>GlobalMPPServerInfoManager: Add(MPPServerInfo) per refreshed server
        Optimizer->>Optimizer: recompute minLogicalCores
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • pingcap/tidb#65694: Directly overlaps with this PR's changes to FetchClusterServerInfoWithoutPrivilegeCheck/ServerInfoResult and the TiFlash getTiFlashServerMinLogicalCores caching via copr.GlobalMPPServerInfoManager.

Suggested labels

approved, lgtm

Suggested reviewers

  • windtalker
  • gengliqi
  • cfzjywxk

Poem

🐇 Hoppin' through the cache with glee,
Stale TiFlash servers? Not for me!
LRU stores each core count tight,
Only fresh fetches see the light.
No more socket leaks in the night! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: implementing a cache for MPP info to avoid frequent gRPC calls.
Description check ✅ Passed The description includes the required Issue Number line and explains the changes and how they work, though it notes manual testing without unit tests and has merge conflicts.
Linked Issues check ✅ Passed The PR implements caching for MPP store metadata to reduce gRPC calls, directly addressing issue #65701's stability problem of socket leaks causing 'Too many open files' errors.
Out of Scope Changes check ✅ Passed All changes are within scope: adding MPPServerInfo cache, updating FetchClusterServerInfoWithoutPrivilegeCheck to return structured results, and modifying getTiFlashServerMinLogicalCores to check cache before gRPC calls.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
pkg/infoschema/tables.go (2)

2628-2633: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the Idx input-order contract.

Idx is now used by callers to map rows back to the corresponding serversInfo entry. Please make that invariant explicit on the exported type/field.

Proposed documentation tweak
-// ServerInfoResult contains server info results
+// ServerInfoResult contains the fetch result for one input ServerInfo.
 type ServerInfoResult struct {
-	Idx  int
+	// Idx is the index of the corresponding ServerInfo in the input slice.
+	Idx  int
 	Rows [][]types.Datum
 	Err  error
 }

As per coding guidelines, comments should explain non-obvious intent, constraints, invariants, and exported-symbol doc comments should prefer semantic constraints over name restatement.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/infoschema/tables.go` around lines 2628 - 2633, The `Idx` field in the
`ServerInfoResult` struct is missing documentation about an important invariant
that callers depend on. Add a comment above the `Idx` field in the
`ServerInfoResult` struct that explicitly documents that this field is used by
callers to map the returned rows back to the corresponding entry in the original
`serversInfo` input, making this contract and constraint clear to anyone using
this exported type.

Source: Coding guidelines


2665-2670: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Include the failed server in the warning log.

When recordWarningInStmtCtx is false, the log drops which server failed even though result.Idx can identify it. Add address/type fields so the gRPC failure is actionable.

As per coding guidelines, error handling should be actionable and contextual.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/infoschema/tables.go` around lines 2665 - 2670, When
recordWarningInStmtCtx is false, the log.Warn call does not include which server
failed, making the gRPC failure non-actionable. Enhance the log.Warn call in the
else branch to include the server address and type information that can be
identified using result.Idx, so that the error log message contains contextual
details about which server caused the failure alongside the error message from
result.Err.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/planner/core/optimizer.go`:
- Around line 51-56: The file contains unresolved merge conflict markers in two
locations that must be resolved before the code can compile. In the import block
at the top of the file, remove the merge conflict markers (<<<<<<< HEAD,
=======, and >>>>>>> 84f3ca52e57) and decide which imports are needed: keep the
variable import from HEAD and also include the vardef and copr imports from the
incoming branch if both are required by the code. Similarly, locate and resolve
the merge conflict in the getTiFlashServerMinLogicalCores function (around line
687-721) by removing the conflict markers and determining which version of the
function implementation is correct based on the cache MPP info feature being
implemented. Ensure all merge conflict markers are completely removed and the
resulting imports and function implementation are syntactically valid Go code.

In `@pkg/store/copr/BUILD.bazel`:
- Around line 92-96: Resolve the merge conflict in the BUILD.bazel file at the
shard_count declaration. Remove all merge conflict markers (the lines starting
with <<<<<<<, =======, and >>>>>>>) and replace them with a single shard_count
assignment. Choose the appropriate value for the release-8.5 branch (either 33
from HEAD or 43 from the incoming commit 84f3ca52e57) based on your branch's
requirements, then delete all marker lines so Bazel can properly parse the
target definition.

---

Nitpick comments:
In `@pkg/infoschema/tables.go`:
- Around line 2628-2633: The `Idx` field in the `ServerInfoResult` struct is
missing documentation about an important invariant that callers depend on. Add a
comment above the `Idx` field in the `ServerInfoResult` struct that explicitly
documents that this field is used by callers to map the returned rows back to
the corresponding entry in the original `serversInfo` input, making this
contract and constraint clear to anyone using this exported type.
- Around line 2665-2670: When recordWarningInStmtCtx is false, the log.Warn call
does not include which server failed, making the gRPC failure non-actionable.
Enhance the log.Warn call in the else branch to include the server address and
type information that can be identified using result.Idx, so that the error log
message contains contextual details about which server caused the failure
alongside the error message from result.Err.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b50a9495-2a7f-4c17-91dd-fe7b4ee3c735

📥 Commits

Reviewing files that changed from the base of the PR and between 3733e2a and ac99f1f.

📒 Files selected for processing (8)
  • pkg/executor/memtable_reader.go
  • pkg/infoschema/tables.go
  • pkg/planner/core/BUILD.bazel
  • pkg/planner/core/optimizer.go
  • pkg/planner/core/optimizer_test.go
  • pkg/store/copr/BUILD.bazel
  • pkg/store/copr/mpp_probe.go
  • pkg/store/copr/mpp_probe_test.go

Comment thread pkg/planner/core/optimizer.go Outdated
Comment thread pkg/store/copr/BUILD.bazel Outdated
@codecov

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.22078% with 16 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-8.5@3733e2a). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff                @@
##             release-8.5     #69403   +/-   ##
================================================
  Coverage               ?   56.5944%           
================================================
  Files                  ?       1852           
  Lines                  ?     676824           
  Branches               ?          0           
================================================
  Hits                   ?     383045           
  Misses                 ?     265818           
  Partials               ?      27961           
Flag Coverage Δ
integration 40.3088% <7.7922%> (?)
unit 65.6120% <79.2207%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 55.3108% <0.0000%> (?)
parser ∅ <0.0000%> (?)
br 66.1106% <0.0000%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ti-chi-bot ti-chi-bot Bot added the needs-1-more-lgtm Indicates a PR needs 1 more LGTM. label Jul 13, 2026

@windtalker windtalker left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Aug 31, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-07-13 02:15:42.13691632 +0000 UTC m=+593528.173011366: ☑️ agreed by xzhangxian1008.
  • 2026-08-31 01:33:02.712560541 +0000 UTC m=+1070217.883654656: ☑️ agreed by windtalker.

@ti-chi-bot ti-chi-bot Bot added cherry-pick-approved Cherry pick PR approved by release team. and removed do-not-merge/cherry-pick-not-approved labels Aug 31, 2026
@xzhangxian1008

Copy link
Copy Markdown
Contributor

/unhold

@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Sep 2, 2026
@ti-chi-bot

ti-chi-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: windtalker, winoros, wjhuang2016, xzhangxian1008

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added the approved label Sep 3, 2026
@ti-chi-bot
ti-chi-bot Bot merged commit ac41d7e into pingcap:release-8.5 Sep 3, 2026
20 checks passed
@ti-chi-bot
ti-chi-bot Bot deleted the cherry-pick-65694-to-release-8.5 branch September 3, 2026 09:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved cherry-pick-approved Cherry pick PR approved by release team. lgtm ok-to-test Indicates a PR is ready to be tested. release-note-none Denotes a PR that doesn't merit a release note. sig/planner SIG: Planner size/L Denotes a PR that changes 100-499 lines, ignoring generated files. type/cherry-pick-for-release-8.5 This PR is cherry-picked to release-8.5 from a source PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants