Skip to content

server: limit the size for COM_STMT_SEND_LONG_DATA in each connection (release-7.5-20260724-v7.5.7) (#70350) | tidb-test=release-7.5.7 tikv=v7.5.7 pd=v7.5.7 tiflash=v7.5.7 - #70442

Merged
ti-chi-bot[bot] merged 2 commits into
pingcap:release-7.5-20260724-v7.5.7from
bb7133:cp-70350-7.5-v7.5.7
Aug 12, 2026

Conversation

@bb7133

@bb7133 bb7133 commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: close #70349

Problem Summary:
Cherry-pick #70350 (limit connection-scoped COM_STMT_SEND_LONG_DATA memory usage) to release-7.5-20260724-v7.5.7.

What changed and how does it work?

Cherry-pick of bff1263. Conflict adaptations for release-7.5:

  • Kept this branch's cursor cleanup through GetRowContainerReader() while adding the new long-data release call to statement reset/close.
  • Release-7.5 predates the structured ErrMemoryExceedForQuery error introduced by *: unified the cancel/kill logic in tidb #47063, so the quota-exceeded path returns the equivalent release-7.5 single-query memory-limit message from pkg/util/memory.
  • Dropped master-only imports that are unused on this branch.

The prepared-statement long-data buffers are charged to the session memory tracker, rejected before the existing query-memory quota is reached, and uncharged when the statement is executed, reset, or closed.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test

Local validation:

GOFLAGS=-buildvcs=false go test ./pkg/server -run '^TestStmtSendLongData(MaxAllowedPacket|MemQuotaQuery)$' -count=1

The focused tests pass. With local Go 1.25.8, go vet ./pkg/server/ additionally reports two pre-existing append with no values diagnostics in conn_stmt_test.go; both calls are already present in the target branch and are outside this patch.

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

None

Summary by CodeRabbit

  • Bug Fixes
    • Added memory-quota enforcement for large prepared-statement parameter data.
    • Clearer handling distinguishes memory-quota errors from packet-size errors.
    • Memory is now released correctly after execution failures, parameter resets, and statement closure.
    • Empty parameter data no longer retains previously allocated memory.
    • Prepared statements can accept new data after memory has been released.

…pingcap#70350)

close pingcap#70349

(cherry picked from commit bff1263)
Signed-off-by: bb7133 <bb7133@gmail.com>
@ti-chi-bot

ti-chi-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@ti-chi-bot ti-chi-bot Bot added release-note-none Denotes a PR that doesn't merit a release note. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 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 Plus

Run ID: b6e94c7d-9ee0-4b32-92fd-c38c21208ba9

📥 Commits

Reviewing files that changed from the base of the PR and between a4f861b and 8b746ce.

📒 Files selected for processing (1)
  • pkg/server/stat_test.go

📝 Walkthrough

Walkthrough

Prepared-statement long-data bytes now use session memory tracking. Quota refusal is reported separately from packet-size overflow. Reset and Close release tracked memory. Tests cover quota enforcement, cleanup, later acceptance, and statistics lease isolation.

Changes

Long-data memory quota enforcement

Layer / File(s) Summary
Quota tracking and rejection
pkg/server/driver_tidb.go
TiDBStatement tracks long-data memory. Accepted data charges the session tracker. Empty data releases charges. Packet-size and memory-quota refusals use separate states.
Cleanup lifecycle and validation
pkg/server/driver_tidb.go, pkg/server/conn_stmt_test.go, pkg/server/stat_test.go
Reset and Close release tracked memory and clear long-data state. Tests validate quota refusal, execution failure, cleanup, later acceptance, and statistics lease reset.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: yangkeao, tiancaiamao

Poem

A rabbit tracks each data byte,
The quota keeps the bounds tight.
When memory blocks another stream,
Cleanup clears the tracked beam.
Reset and Close restore the light. 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: limiting COM_STMT_SEND_LONG_DATA size per connection, although it includes release metadata.
Description check ✅ Passed The description includes the required issue, problem, implementation, test, side-effect, documentation, and release-note sections.
Linked Issues check ✅ Passed The changes address issue #70349 by limiting long-data memory growth and releasing tracked memory during execution, reset, and close.
Out of Scope Changes check ✅ Passed All changes support the memory-limit fix, including the stats-lease reset needed for test isolation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


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.

@bb7133
bb7133 marked this pull request as ready for review August 11, 2026 10:02
@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Aug 11, 2026

@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

🧹 Nitpick comments (1)
pkg/server/conn_stmt_test.go (1)

612-617: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Exercise the Reset cleanup path.

This test covers cleanup after failed COM_STMT_EXECUTE and Close. It does not exercise the new TiDBStatement.Reset cleanup call.

Add an accepted long-data sequence, dispatch COM_STMT_RESET, and verify that MemTracker.BytesConsumed() returns to base and the parameter buffer is cleared.

🤖 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/server/conn_stmt_test.go` around lines 612 - 617, Extend the statement
cleanup test around TiDBStatement.Reset by dispatching COM_STMT_RESET after an
accepted long-data sequence, then assert BoundParams()[0] is cleared and
vars.MemTracker.BytesConsumed() returns to base. Keep the existing release and
Close assertions intact.
🤖 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/server/driver_tidb.go`:
- Around line 115-120: Update the long-data handling around boundParams and its
release paths to track each parameter’s reserved slice capacity, not only
len(data). Reserve and charge the capacity before appending or replacing
boundParams, store the reservation per parameter, and release that exact
reservation in the cleanup paths at the current release blocks. Add a
multi-chunk test that forces backing-slice growth and verifies session memory
tracking remains balanced.

---

Nitpick comments:
In `@pkg/server/conn_stmt_test.go`:
- Around line 612-617: Extend the statement cleanup test around
TiDBStatement.Reset by dispatching COM_STMT_RESET after an accepted long-data
sequence, then assert BoundParams()[0] is cleared and
vars.MemTracker.BytesConsumed() returns to base. Keep the existing release and
Close assertions intact.
🪄 Autofix

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 Plus

Run ID: dcd23c26-d27b-46f6-9e5f-411b88210c23

📥 Commits

Reviewing files that changed from the base of the PR and between 92d7d96 and a4f861b.

📒 Files selected for processing (2)
  • pkg/server/conn_stmt_test.go
  • pkg/server/driver_tidb.go

Comment thread pkg/server/driver_tidb.go
Comment on lines +115 to +120
released := int64(len(ts.boundParams[paramID]))
if released > 0 {
ts.ctx.GetSessionVars().MemTracker.Consume(-released)
ts.boundLongDataBytes -= released
}
ts.boundParams[paramID] = append(ts.boundParams[paramID], data...)
ts.boundParams[paramID] = []byte{}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Track retained buffer capacity before appending.

Line 148 charges only len(data). Line 149 can grow the slice backing array to a capacity greater than its length. The connection can therefore retain more long-data memory than the session tracker charges.

Lines 115-120 and 172-179 also release accepted lengths. Track the reserved capacity for each parameter and release that same reservation. Reserve memory before changing boundParams. Add a multi-chunk test that forces slice growth.

Also applies to: 148-150, 172-179

🤖 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/server/driver_tidb.go` around lines 115 - 120, Update the long-data
handling around boundParams and its release paths to track each parameter’s
reserved slice capacity, not only len(data). Reserve and charge the capacity
before appending or replacing boundParams, store the reservation per parameter,
and release that exact reservation in the cleanup paths at the current release
blocks. Add a multi-chunk test that forces backing-slice growth and verifies
session memory tracking remains balanced.

@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.06977% with 9 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (release-7.5-20260724-v7.5.7@92d7d96). Learn more about missing BASE report.

Additional details and impacted files
@@                       Coverage Diff                        @@
##             release-7.5-20260724-v7.5.7     #70442   +/-   ##
================================================================
  Coverage                               ?   73.0208%           
================================================================
  Files                                  ?       1445           
  Lines                                  ?     421859           
  Branches                               ?          0           
================================================================
  Hits                                   ?     308045           
  Misses                                 ?      94534           
  Partials                               ?      19280           
Flag Coverage Δ
integration 41.1261% <0.0000%> (?)
unit 72.2040% <79.0697%> (?)

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

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

@jebter

jebter commented Aug 12, 2026

Copy link
Copy Markdown

/retest

…independent

The new TestStmtSendLongDataMemQuotaQuery uses testkit.CreateMockStoreAndDomain,
which calls session.DisableStats4Test and leaves the process-global stats lease
at -1. TestInitStatsSessionBlockGC then no longer blocks GC as expected when the
two tests share a test shard. Reset the lease explicitly (adapted from pingcap#67206,
which fixed this on master).
@bb7133

bb7133 commented Aug 12, 2026

Copy link
Copy Markdown
Member Author

/retest

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

ti-chi-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: djshow832, 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 lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Aug 12, 2026
@ti-chi-bot

ti-chi-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-08-12 09:35:39.500732379 +0000 UTC m=+3211925.536827435: ☑️ agreed by YangKeao.
  • 2026-08-12 09:36:40.147916061 +0000 UTC m=+3211986.184011147: ☑️ agreed by djshow832.

@ti-chi-bot
ti-chi-bot Bot merged commit 4964d33 into pingcap:release-7.5-20260724-v7.5.7 Aug 12, 2026
17 of 19 checks passed
@bb7133
bb7133 deleted the cp-70350-7.5-v7.5.7 branch August 12, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note-none Denotes a PR that doesn't merit a release note. 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