Skip to content

statistics, executor, session: integrate analyze resource control#69452

Merged
ti-chi-bot[bot] merged 9 commits into
pingcap:masterfrom
0xPoe:poe-patch-stats-processing
Jul 7, 2026
Merged

statistics, executor, session: integrate analyze resource control#69452
ti-chi-bot[bot] merged 9 commits into
pingcap:masterfrom
0xPoe:poe-patch-stats-processing

Conversation

@0xPoe

@0xPoe 0xPoe commented Jun 24, 2026

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: ref #69472

Problem Summary:

ANALYZE Resource Control needs to throttle ANALYZE without throttling unrelated internal statistics work.

What changed and how does it work?

  • Add an internal StatsForegroundPriority request source for non-ANALYZE statistics work.

The test result summary: #69452 (comment) I will do more tests once the whole project is finished. Then we can connect all the dots to see what the real performance impact is.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test
  • 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.

New TiDB clusters throttle ANALYZE through Resource Control background task scheduling by default. Existing upgraded clusters keep their current resource group background settings.

Summary by CodeRabbit

  • New Features

    • Added a separate internal request category for statistics processing, improving how stats-related work is tracked and controlled.
    • Auto-analyze and stats initialization now better distinguish between standard analyze requests and background stats processing.
    • Plan replayer and related background operations now use the updated stats-processing path.
  • Bug Fixes

    • Improved request routing so stats-processing work follows the same bypass behavior as existing stats requests.
    • Updated several stats and analyze flows to use the correct internal source type, making background processing more consistent.

@ti-chi-bot ti-chi-bot Bot added do-not-merge/needs-linked-issue release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/needs-triage-completed size/S Denotes a PR that changes 10-29 lines, ignoring generated files. component/statistics sig/planner SIG: Planner labels Jun 24, 2026
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds InternalTxnStatsProcessing and routes analyze, stats, plan replayer, and session execution paths through it where internal request-source handling is separated from InternalTxnStats. The PR also adds bootstrap-time resource-group configuration and matching tests.

Changes

Stats processing source type update

Layer / File(s) Summary
New source type and shared helpers
pkg/kv/option.go, pkg/statistics/handle/util/util.go, pkg/statistics/handle/util/test/ctx_matcher.go, pkg/statistics/handle/lockstats/query_lock_test.go
Adds InternalTxnStatsProcessing, updates the shared stats execution context and explicit-context helper, and aligns matcher tests with the new source type.
Analyze request source mapping
pkg/distsql/*
Analyze derives its request source from context, and the distsql test target shard count increases.
Restricted SQL callers
pkg/executor/..., pkg/planner/..., pkg/ddl/index.go, pkg/domain/extract.go
Analyze-related restricted SQL paths and extraction queries now tag their execution contexts with InternalTxnStatsProcessing.
Plan replayer capture
pkg/domain/domain.go, pkg/domain/plan_replayer.go, pkg/executor/adapter.go, pkg/executor/plan_replayer.go, pkg/executor/test/planreplayer/*
Plan replayer setup, capture gating, and status persistence now use InternalTxnStatsProcessing, and the capture test covers stats and normal digests.
Stats bootstrap initialization
pkg/statistics/handle/bootstrap.go
Stats bootstrap helpers now run their restricted SQL under InternalTxnStatsProcessing, and the bucket-existence TODO comment is removed.
Auto-analyze execution
pkg/statistics/handle/autoanalyze/exec/*
Auto-analyze execution now selects its request context from the configured time window and passes it into restricted SQL execution; the test target adds //pkg/kv and the test checks both source types.
Session bootstrap background config
pkg/session/bootstrap.go, pkg/session/test/bootstraptest/*
Bootstrap adds a background resource-group configuration for the default group, and the bootstrap test target shard count increases while the test checks fresh-bootstrap and upgrade behavior.
Session bypass policy
pkg/session/session.go, pkg/session/tidb_test.go
RUV2 bypass now treats InternalTxnStatsProcessing the same as InternalTxnStats, and the session test adds coverage for that context.

Sequence Diagram(s)

sequenceDiagram
  participant RunAnalyzeStmt
  participant GetAutoAnalyzeParameters
  participant autoAnalyzeRequestContext
  participant statsutilExec as statsutil.ExecWithCtxAndOpts
  participant ExecRestrictedSQL
  RunAnalyzeStmt->>GetAutoAnalyzeParameters: read auto-analyze parameters
  GetAutoAnalyzeParameters-->>RunAnalyzeStmt: analyzeParameters
  RunAnalyzeStmt->>autoAnalyzeRequestContext: build request context
  autoAnalyzeRequestContext-->>RunAnalyzeStmt: ctx with internal source type
  RunAnalyzeStmt->>statsutilExec: execute stats SQL with ctx
  statsutilExec->>ExecRestrictedSQL: run restricted SQL with provided ctx
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • issue 69472 — Directly adds the StatsProcessing split and routes non-ANALYZE stats work through it.

Possibly related PRs

  • pingcap/tidb#65249 — Touches the same analyze execution path in pkg/executor/analyze.go and pkg/distsql/distsql.go.
  • pingcap/tidb#68754 — Modifies pkg/distsql/distsql.go's Analyze flow in the same area now using the request-context source type.

Suggested labels

size/XXL

Suggested reviewers

  • yudongusa
  • XuHuaiyu
  • gengliqi
  • wshwsh12

Poem

A rabbit hopped through stats and sand,
with StatsProcessing close at hand.
Analyze and plan replayer sprang,
while quiet tests in moonlight sang.
🥕 The carrots glowed, the queues were grand.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 concisely summarizes the main change: integrating analyze resource control across statistics, executor, and session code.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description follows the required template and includes the issue link, problem summary, change summary, checklist, and release note.
✨ 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: 1

🤖 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/statistics/handle/util/util.go`:
- Around line 59-60: The capture guard in the plan replayer currently only
excludes requests marked with kv.InternalTxnStats, so the new StatsCtx source
type kv.InternalTxnStatsProcessing can still be captured. Update the condition
in pkg/executor/adapter.go where the capture skip is decided to treat both
internal stats source types as excluded, using the existing context/source check
around the adapter logic so StatsCtx remains uncaptured.
🪄 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: f71aa3c7-8506-4a82-8108-53fe436714be

📥 Commits

Reviewing files that changed from the base of the PR and between 42edcdf and 9bae863.

📒 Files selected for processing (4)
  • pkg/kv/option.go
  • pkg/statistics/handle/lockstats/query_lock_test.go
  • pkg/statistics/handle/util/test/ctx_matcher.go
  • pkg/statistics/handle/util/util.go

Comment thread pkg/statistics/handle/util/util.go Outdated
@codecov

codecov Bot commented Jun 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.9371%. Comparing base (09d2140) to head (87e964c).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #69452        +/-   ##
================================================
- Coverage   76.3227%   75.9371%   -0.3857%     
================================================
  Files          2041       2078        +37     
  Lines        560399     580342     +19943     
================================================
+ Hits         427712     440695     +12983     
- Misses       131786     137508      +5722     
- Partials        901       2139      +1238     
Flag Coverage Δ
integration 45.9620% <50.0000%> (+6.2568%) ⬆️

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

Components Coverage Δ
dumpling 60.4471% <ø> (ø)
parser ∅ <ø> (∅)
br 64.5789% <ø> (+1.8576%) ⬆️
🚀 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 size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed size/S Denotes a PR that changes 10-29 lines, ignoring generated files. do-not-merge/needs-linked-issue do-not-merge/needs-triage-completed labels Jun 24, 2026
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 6d2329a to 873577b Compare June 26, 2026 10:40
@ti-chi-bot ti-chi-bot Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Jun 26, 2026
@0xPoe 0xPoe changed the title statistics: separate stats processing request source statistics, executor, session: integrate analyze resource control Jun 26, 2026
@ti-chi-bot ti-chi-bot Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. and removed release-note-none Denotes a PR that doesn't merit a release note. labels Jun 26, 2026
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 873577b to 9ba3af4 Compare June 26, 2026 10:48

@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/session/bootstrap.go (1)

421-422: 🩺 Stability & Availability | 🔵 Trivial

Fresh-bootstrap-only configuration creates fresh-vs-upgraded divergence.

This ALTER RESOURCE GROUP runs in doDDLWorks, which only executes on fresh bootstrap. The accompanying upgrade test asserts that upgraded clusters end up with Background == nil. Net effect: newly bootstrapped clusters get the stats background throttling (UTILIZATION_LIMIT=30) on the default group, while existing clusters upgraded to this version do not. If that asymmetry is intentional (preserve operator-configured settings on existing clusters), no action is needed; otherwise consider whether upgraded clusters should receive an equivalent default.

🤖 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/session/bootstrap.go` around lines 421 - 422, The ALTER RESOURCE GROUP in
doDDLWorks only affects fresh bootstrap, creating a mismatch with upgraded
clusters that keep Background nil. Check the bootstrap/upgrade path around
doDDLWorks and the default ResourceGroup setup for
resourcegroup.DefaultResourceGroupName, and decide whether upgraded clusters
should also receive the same stats throttling (kv.InternalTxnStats with
defaultAnalyzeBackgroundUtilizationLimit) or whether the asymmetry is
intentional. If the default should be consistent, add the equivalent
initialization in the upgrade path/testable bootstrap logic rather than only in
fresh bootstrap.
pkg/statistics/handle/autoanalyze/exec/exec.go (1)

112-139: 🎯 Functional Correctness | 🔵 Trivial

RunAnalyzeStmt is exported but hardcoded to auto-analyze context.

Verification found that RunAnalyzeStmt is currently called only by AutoAnalyze within the same package, confirming no immediate non-auto-analyze callers exist. However, the function is exported and unconditionally derives its request context from auto-analyze window parameters (GetAutoAnalyzeParameters). This design couples the function strictly to the auto-analyze flow, creating a risk if exported usage expands to manual or ad-hoc analysis paths in the future. Consider renaming to RunAutoAnalyzeStmt or factoring the context derivation to allow explicit caller control.

🤖 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/statistics/handle/autoanalyze/exec/exec.go` around lines 112 - 139,
RunAnalyzeStmt is exported but its behavior is hardwired to the auto-analyze
flow by always building the request context with auto-analyze window parameters.
Update the API in exec.go so the naming and intent match the behavior: either
rename RunAnalyzeStmt to RunAutoAnalyzeStmt, or refactor it to accept an
explicit request context/parameter source instead of always calling
autoAnalyzeRequestContext(GetAutoAnalyzeParameters(sctx)). Keep the AutoAnalyze
caller aligned with the chosen symbol.
🤖 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/distsql/distsql.go`:
- Around line 209-214: The analyze execution path is using a context-based
source type in distsql.Analyze while the stats-processing session var is already
set to InternalTxnStatsProcessing, so the two paths diverge. Update the analyze
call sites in the analyze execution flow to pass a context wrapped with
contextWithAnalyzeRequestSource (or an equivalent kv.WithInternalSourceType
setup) before invoking distsql.Analyze, so analyzeRequestSourceType in
pkg/distsql/distsql.go sees InternalTxnStatsProcessing just like the sibling
helper in pkg/executor/analyze.go.

In `@pkg/session/bootstrap.go`:
- Around line 421-422: The bootstrap flow in doDDLWorks() alters the default
resource group without guaranteeing it exists in storage first. Add a CREATE
RESOURCE GROUP IF NOT EXISTS for resourcegroup.DefaultResourceGroupName before
the existing ALTER RESOURCE GROUP call, so the default group is present for both
classic and next-gen kernels. Keep the fix localized around the mustExecute DDL
sequence in pkg/session/bootstrap.go and preserve the existing ALTER RESOURCE
GROUP settings afterward.

---

Nitpick comments:
In `@pkg/session/bootstrap.go`:
- Around line 421-422: The ALTER RESOURCE GROUP in doDDLWorks only affects fresh
bootstrap, creating a mismatch with upgraded clusters that keep Background nil.
Check the bootstrap/upgrade path around doDDLWorks and the default ResourceGroup
setup for resourcegroup.DefaultResourceGroupName, and decide whether upgraded
clusters should also receive the same stats throttling (kv.InternalTxnStats with
defaultAnalyzeBackgroundUtilizationLimit) or whether the asymmetry is
intentional. If the default should be consistent, add the equivalent
initialization in the upgrade path/testable bootstrap logic rather than only in
fresh bootstrap.

In `@pkg/statistics/handle/autoanalyze/exec/exec.go`:
- Around line 112-139: RunAnalyzeStmt is exported but its behavior is hardwired
to the auto-analyze flow by always building the request context with
auto-analyze window parameters. Update the API in exec.go so the naming and
intent match the behavior: either rename RunAnalyzeStmt to RunAutoAnalyzeStmt,
or refactor it to accept an explicit request context/parameter source instead of
always calling autoAnalyzeRequestContext(GetAutoAnalyzeParameters(sctx)). Keep
the AutoAnalyze caller aligned with the chosen symbol.
🪄 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: c6ef31fe-eb21-4694-831d-1ee5caf4a0b9

📥 Commits

Reviewing files that changed from the base of the PR and between 6d2329a and 873577b.

📒 Files selected for processing (31)
  • pkg/ddl/index.go
  • pkg/ddl/options_test.go
  • pkg/distsql/BUILD.bazel
  • pkg/distsql/distsql.go
  • pkg/distsql/distsql_test.go
  • pkg/domain/domain.go
  • pkg/domain/extract.go
  • pkg/domain/plan_replayer.go
  • pkg/executor/adapter.go
  • pkg/executor/analyze.go
  • pkg/executor/builder.go
  • pkg/executor/infoschema_reader.go
  • pkg/executor/internal/pdhelper/pd.go
  • pkg/executor/plan_replayer.go
  • pkg/executor/show.go
  • pkg/executor/test/planreplayer/BUILD.bazel
  • pkg/executor/test/planreplayer/plan_replayer_test.go
  • pkg/kv/option.go
  • pkg/planner/indexadvisor/utils.go
  • pkg/session/bootstrap.go
  • pkg/session/session.go
  • pkg/session/test/bootstraptest/BUILD.bazel
  • pkg/session/test/bootstraptest/bootstrap_upgrade_test.go
  • pkg/session/tidb_test.go
  • pkg/statistics/handle/autoanalyze/exec/BUILD.bazel
  • pkg/statistics/handle/autoanalyze/exec/exec.go
  • pkg/statistics/handle/autoanalyze/exec/request_source_test.go
  • pkg/statistics/handle/bootstrap.go
  • pkg/statistics/handle/lockstats/query_lock_test.go
  • pkg/statistics/handle/util/test/ctx_matcher.go
  • pkg/statistics/handle/util/util.go
✅ Files skipped from review due to trivial changes (5)
  • pkg/executor/test/planreplayer/BUILD.bazel
  • pkg/distsql/BUILD.bazel
  • pkg/session/test/bootstraptest/BUILD.bazel
  • pkg/executor/builder.go
  • pkg/kv/option.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/statistics/handle/util/test/ctx_matcher.go
  • pkg/executor/adapter.go
  • pkg/statistics/handle/lockstats/query_lock_test.go
  • pkg/executor/test/planreplayer/plan_replayer_test.go

Comment thread pkg/distsql/distsql.go Outdated
Comment thread pkg/session/bootstrap.go Outdated
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 9ba3af4 to 166063b Compare June 26, 2026 15:37
@ti-chi-bot ti-chi-bot Bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. labels Jun 26, 2026
@0xPoe

0xPoe commented Jun 26, 2026

Copy link
Copy Markdown
Member Author

/retest

@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 166063b to 2d5b22f Compare June 26, 2026 17:27
Comment thread pkg/session/bootstrap.go Outdated
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch 3 times, most recently from 8e1b291 to 5bdef14 Compare June 30, 2026 16:09
@ti-chi-bot ti-chi-bot Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Jul 6, 2026
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 69fbf08 to 54de99a Compare July 6, 2026 18:51
@0xPoe 0xPoe requested a review from time-and-fate July 6, 2026 19:00
@0xPoe 0xPoe force-pushed the poe-patch-stats-processing branch from 4e5a683 to 8a7eb6c Compare July 6, 2026 19:22
@0xPoe

0xPoe commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/retest

@0xPoe

0xPoe commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/test pull-unit-test-next-gen
/test idc-jenkins-ci-tidb/check_dev

@0xPoe

0xPoe commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/test pull-unit-test-next-gen

@pingcap pingcap deleted a comment from ti-chi-bot Bot Jul 6, 2026
@pingcap pingcap deleted a comment from ti-chi-bot Bot Jul 6, 2026
@pingcap pingcap deleted a comment from ti-chi-bot Bot Jul 6, 2026
@0xPoe

0xPoe commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/retest

1 similar comment
@0xPoe

0xPoe commented Jul 6, 2026

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot

ti-chi-bot Bot commented Jul 7, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: time-and-fate, winoros, YangKeao

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 Jul 7, 2026
@0xPoe

0xPoe commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

/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 Jul 7, 2026
@ti-chi-bot ti-chi-bot Bot merged commit e3dc39f into pingcap:master Jul 7, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved component/statistics lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. sig/planner SIG: Planner size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants