Skip to content

server: limit accumulated COM_STMT_SEND_LONG_DATA size - #69694

Merged
ti-chi-bot[bot] merged 3 commits into
pingcap:masterfrom
bb7133:codex/stmt-send-long-data-limit
Jul 23, 2026
Merged

ti-chi-bot[bot] merged 3 commits into
pingcap:masterfrom
bb7133:codex/stmt-send-long-data-limit

Conversation

@bb7133

@bb7133 bb7133 commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

Issue Number: close #69693

Problem Summary:

COM_STMT_SEND_LONG_DATA appends each payload chunk into the prepared statement's bound parameter buffers. Before this PR, TiDB did not check the cumulative size of those buffers, so an authenticated client could keep sending long-data chunks for a prepared statement and grow connection memory without executing the statement.

What changed and how does it work?

This PR tracks the total bytes accumulated by COM_STMT_SEND_LONG_DATA for each prepared statement. Before appending a new chunk, TiDB checks whether the statement-level accumulated long-data size would exceed the session max_allowed_packet. If it would exceed the limit, TiDB returns the existing ErrNetPacketTooLarge error and keeps the already buffered data unchanged.

COM_STMT_RESET clears both the buffered parameters and the byte counter.

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.

Tested locally:

  • git diff --check
  • go test ./pkg/server -run '^(TestStmtSendLongDataMaxAllowedPacket|TestCursorFetchSendLongData|TestCursorFetchSendLongDataReset)$' -count=1
  • go test --tags=intest ./pkg/server -run '^(TestStmtSendLongDataMaxAllowedPacket|TestCursorFetchSendLongData|TestCursorFetchSendLongDataReset)$' -count=1

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

TiDB now limits the accumulated `COM_STMT_SEND_LONG_DATA` size for a prepared statement by `max_allowed_packet`.

Summary by CodeRabbit

  • Bug Fixes

    • Added pre-execution validation for accumulated COM_STMT_SEND_LONG_DATA payload sizes.
    • Execution now fails early when long-data exceeds MaxAllowedPacket, instead of proceeding with parameter parsing.
    • After oversized-packet failures, affected bound parameters are cleared and the prepared statement can be safely reused.
  • Tests

    • Added a regression test covering the MaxAllowedPacket boundary and oversized long-data submissions, including post-error buffer clearing and continued validation success.

Signed-off-by: bb7133 <bb7133@gmail.com>
@ti-chi-bot

ti-chi-bot Bot commented Jul 6, 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 Denotes a PR that will be considered when it comes time to generate release notes. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. do-not-merge/needs-triage-completed labels Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Long-data packet limits

Layer / File(s) Summary
Accumulated size enforcement
pkg/server/driver.go, pkg/server/driver_tidb.go
Prepared statements track cumulative long-data size, reject oversized parameters with ErrNetPacketTooLarge, and clear overflow state on reset.
Execution validation and regression coverage
pkg/server/conn_stmt.go, pkg/server/conn_stmt_test.go
Statement execution validates long-data size before parsing parameters, and tests verify rejection and parameter cleanup.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TiDBStatement
  participant handleStmtExecute
  Client->>TiDBStatement: Send long-data chunks
  TiDBStatement->>TiDBStatement: Track cumulative size
  Client->>handleStmtExecute: Execute prepared statement
  handleStmtExecute->>TiDBStatement: CheckLongDataSize()
  TiDBStatement-->>handleStmtExecute: ErrNetPacketTooLarge
  handleStmtExecute-->>Client: Return packet-too-large error
Loading

Poem

A bunny stacks chunks in a byte-sized queue,
Then checks the limit before parsing anew.
Too large? “Hop back!” says the packet guard,
Reset clears the burrow, tidy and hard.
The statement bounds now hold true!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: limiting accumulated COM_STMT_SEND_LONG_DATA size.
Description check ✅ Passed The description follows the template with issue number, problem summary, implementation details, tests, side effects, documentation, and release note.
Linked Issues check ✅ Passed The code matches #69693 by capping accumulated long-data at max_allowed_packet and returning ErrNetPacketTooLarge.
Out of Scope Changes check ✅ Passed All changes are directly tied to long-data size limiting, reset handling, and coverage; no unrelated edits stand out.
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

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.

@ti-chi-bot ti-chi-bot Bot added size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed do-not-merge/needs-triage-completed labels Jul 6, 2026
Comment thread pkg/server/driver_tidb.go Resolved
Comment thread pkg/server/driver_tidb.go Resolved
@bb7133 bb7133 removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 22, 2026
@bb7133
bb7133 marked this pull request as ready for review July 22, 2026 03:05
@pingcap-cla-assistant

pingcap-cla-assistant Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.7835%. Comparing base (09d2140) to head (ecf29a5).
⚠️ Report is 58 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #69694        +/-   ##
================================================
- Coverage   76.3227%   73.7835%   -2.5393%     
================================================
  Files          2041       2058        +17     
  Lines        560399     591773     +31374     
================================================
+ Hits         427712     436631      +8919     
- Misses       131786     153540     +21754     
- Partials        901       1602       +701     
Flag Coverage Δ
integration 40.9651% <0.0000%> (+1.2598%) ⬆️

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

Components Coverage Δ
dumpling 60.4471% <ø> (ø)
parser ∅ <ø> (∅)
br 46.9281% <ø> (-15.7932%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@YangKeao

Copy link
Copy Markdown
Member

/retest

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

@YangKeao YangKeao left a comment

Copy link
Copy Markdown
Member

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 commented Jul 22, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: tiancaiamao, 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:
  • OWNERS [YangKeao,tiancaiamao]

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 Jul 22, 2026
@ti-chi-bot

ti-chi-bot Bot commented Jul 22, 2026

Copy link
Copy Markdown

[LGTM Timeline notifier]

Timeline:

  • 2026-07-22 07:44:13.793380113 +0000 UTC m=+1390839.829475169: ☑️ agreed by tiancaiamao.
  • 2026-07-22 10:12:38.037915611 +0000 UTC m=+1399744.074010667: ☑️ agreed by YangKeao.

@bb7133
bb7133 force-pushed the codex/stmt-send-long-data-limit branch from 86aeefb to ecf29a5 Compare July 23, 2026 02:26

@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/server/conn_stmt_test.go`:
- Around line 597-614: Update the long-data test around dispatchSendLongData so
the initial chunks cumulatively total 1024 bytes, then assert the next append
returns servererr.ErrNetPacketTooLarge. Verify the rejected append leaves both
stmt.BoundParams() buffers unchanged, and remove the deferred execution-time
error expectation while preserving the successful CheckLongDataSize assertion.
🪄 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 Plus

Run ID: 45838da0-61ac-4a14-a1b8-9e4d08e59135

📥 Commits

Reviewing files that changed from the base of the PR and between 86aeefb and ecf29a5.

📒 Files selected for processing (4)
  • pkg/server/conn_stmt.go
  • pkg/server/conn_stmt_test.go
  • pkg/server/driver.go
  • pkg/server/driver_tidb.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/server/conn_stmt.go
  • pkg/server/driver.go
  • pkg/server/driver_tidb.go

Comment on lines +597 to +614
require.NoError(t, dispatchSendLongData(c, stmt.ID(), 0, bytes.Repeat([]byte{'a'}, 1024)))
require.NoError(t, dispatchSendLongData(c, stmt.ID(), 1, bytes.Repeat([]byte{'b'}, 1024)))
require.NoError(t, stmt.CheckLongDataSize())

err = dispatchSendLongData(c, stmt.ID(), 0, []byte{'c'})
require.NoError(t, err)
require.Len(t, stmt.BoundParams()[0], 1024)
require.Len(t, stmt.BoundParams()[1], 1024)

err = c.Dispatch(context.Background(), append(
binary.LittleEndian.AppendUint32([]byte{mysql.ComStmtExecute}, uint32(stmt.ID())),
0x0, 0x1, 0x0, 0x0, 0x0,
0x0, 0x0,
))
require.ErrorIs(t, err, servererr.ErrNetPacketTooLarge)
require.Nil(t, stmt.BoundParams()[0])
require.Nil(t, stmt.BoundParams()[1])
require.NoError(t, stmt.CheckLongDataSize())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Assert the cumulative limit at send time.

With a 1024-byte limit, the second 1024-byte append already exceeds the statement’s cumulative limit. The extra byte must also be rejected by dispatchSendLongData, while existing buffered data remains unchanged; this test currently expects both sends to succeed and defers the error to execution.

Use chunks whose combined size equals 1024, assert servererr.ErrNetPacketTooLarge on the next append, and verify the existing buffers are preserved.

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 606-606: Narrowing a non-constant integer to a smaller fixed-width type (int8/int16/int32, uint8/uint16/uint32) can silently overflow or wrap, yielding negative or truncated values that are dangerous in size, length, or index logic. Validate the source value is within the target type's range before converting (e.g. bounds-check, or use a checked helper), and avoid narrowing untrusted or len()/parsed values.
Context: uint32(stmt.ID())
Note: [CWE-190] Integer Overflow or Wraparound.

(integer-overflow-narrowing-conversion-go)

🤖 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 597 - 614, Update the long-data
test around dispatchSendLongData so the initial chunks cumulatively total 1024
bytes, then assert the next append returns servererr.ErrNetPacketTooLarge.
Verify the rejected append leaves both stmt.BoundParams() buffers unchanged, and
remove the deferred execution-time error expectation while preserving the
successful CheckLongDataSize assertion.

@bb7133

bb7133 commented Jul 23, 2026

Copy link
Copy Markdown
Member Author

/retest

@ti-chi-bot
ti-chi-bot Bot merged commit ed2376a into pingcap:master Jul 23, 2026
34 checks passed
ti-chi-bot Bot pushed a commit that referenced this pull request Jul 27, 2026
@YangKeao

Copy link
Copy Markdown
Member

/cherry-pick release-8.5

@ti-chi-bot

Copy link
Copy Markdown
Member

@YangKeao: new pull request created to branch release-8.5: #70231.
But this PR has conflicts, please resolve them!

Details

In response to this:

/cherry-pick release-8.5

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.

@djshow832

Copy link
Copy Markdown
Contributor

/cherry-pick release-7.5

@ti-chi-bot

Copy link
Copy Markdown
Member

@djshow832: new pull request created to branch release-7.5: #70848.
But this PR has conflicts, please resolve them!

Details

In response to this:

/cherry-pick release-7.5

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.

djshow832 added a commit to ti-chi-bot/tidb that referenced this pull request Sep 3, 2026
…it (pingcap#69694)

Keep CheckLongDataSize while using release-7.5 parse.ExecArgs, and drop the master-only planner/core/resolve import.

Signed-off-by: djshow832 <zhangming@pingcap.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

server: limit accumulated COM_STMT_SEND_LONG_DATA payloads

5 participants