Skip to content

fix(prepare): never allocate for parameter binding after the first execution (#33076) - #33081

Merged
fengttt merged 9 commits into
matrixorigin:mainfrom
fengttt:fix-prepared-param-no-alloc
Nov 23, 2026
Merged

fengttt merged 9 commits into
matrixorigin:mainfrom
fengttt:fix-prepared-param-no-alloc

Conversation

@fengttt

@fengttt fengttt commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #33076

What this PR does / why we need it:

Fixes the sysbench regression from #33011 (typed prepared parameters) without reverting it. The affected workloads are random_points, random_ranges and nopk_random_points, with ps-mode=auto.

Rule applied: a prepared statement allocates what parameter binding needs, holds it in the statement, and reuses it. After the first execution, binding allocates only when a value needs more room than before.

Cause

Binding allocated on every EXECUTE and in every expression executor:

  • installTypedPrepareParams built a new batch, plus one vector per parameter, on every execution.
  • Each ParamExpressionExecutor copied its parameter: a Dup of the typed value, or a new constant for a string. The per-EXECUTE diagnostic probes (ProbePreparedDiagnosticCandidatesWithProof) and EvalFoldExpr build fresh executor trees, so every ? in k IN (?, …) was copied several times per statement.
  • A ? that the planner narrows to its consumer's integer type (protocol BIGINT vs an INT column) built a whole CAST executor inside each executor.

This matches the CI profiles in #33074, where 30–44% of CPU was under evalTyped and runtime.Callers.

Changes

  • Typed parameters. PrepareStmt owns the typed parameter vectors and an integer-conversion store (process.TypedParamConversions). EXECUTE rewrites them in place and the process only borrows them.
    • A narrowed integer is converted once per (position, type), then rewritten in place.
    • A value that doesn't fit keeps the CAST adapter, so error and selection semantics are unchanged.
  • Executor reads. ParamExpressionExecutor returns a read-only reference instead of a copy.
    • The reference is a descriptor embedded in the executor, filled by the new Vector.WindowInto (a method only; no new Vector fields).
    • Typed values reference the statement-owned typed vector.
    • String values reference their row of the TEXT transport.
    • EvalWithoutResultReusing still hands out an owned copy.
    • A folded value is re-read when the process holds different parameter values, so a reference can't go stale.
  • COM_STMT_EXECUTE TEXT transport. The vector is rewritten from an empty area that keeps its capacity. SetBytesAt appends, so before this change the area grew (and reallocated) on every execution that had a string parameter longer than the inline varlena.
  • SQL EXECUTE … USING. The statement owns the TEXT vector and its metadata slices (executeUserParams), rewritten in place and borrowed by the process. Previously they were built fresh on every execution.

Benchmark

Setup: local single-node, ps-mode=auto, 16 threads, 60 s, 10 tables × 1M rows. sbidx has PK(id) + KEY(k); sbnopk has KEY(id) + KEY(k) and no PK, matching CI's nopk case. Runs are interleaved ABBA (main, fix, fix, main) with sync and a 90 s settle between them, because a fixed run order skewed earlier comparisons.

workload (qps) main A1 fix B1 fix B2 main A2 main avg fix avg Δ
random_points 12,329 18,664 19,332 13,846 13,088 18,998 +45%
random_ranges 13,486 18,237 18,740 14,896 14,191 18,488 +30%
nopk_random_points 11,501 17,069 17,628 12,715 12,108 17,348 +43%

main = 4cadd4f. The fix binary includes the typed-parameter and string-parameter changes. The SQL EXECUTE … USING change is not exercised by sysbench.

CPU profile of random_points:

main this PR
ParamExpressionExecutor.Eval 16.3% 0.9%
mpool.alloc 8.2% 1.2%

Follow-ups

Tests

  • New tests:
    • Typed binding: a second EXECUTE makes zero mpool allocations and reuses the same vectors; the narrowed conversion is refreshed in place; a value that no longer fits isn't served; release detaches the process.
    • Fresh executors reading typed and string parameters allocate nothing and don't mutate the shared value. EvalWithoutResultReusing returns an owned copy. New TEXT parameters are re-read rather than served through a stale reference.
    • Integer conversion boundaries, plus out-of-range and negative→unsigned values keeping the CAST error.
    • COM_STMT_EXECUTE with a 40-byte string: no allocation on re-execute; a longer value grows the area once.
    • SQL EXECUTE … USING: storage reused with no allocation on re-execute; release detaches the borrowing process.
  • Passing: pkg/frontend, pkg/sql/colexec, pkg/vm/process, pkg/container/vector.
  • Not run locally: make static-check, plan/compile UTs and BVT. CI will cover them.

🤖 Generated with Claude Code

…rst execution (matrixorigin#33076)

matrixorigin#33011 made prepared parameters typed values, but binding them allocated on
every EXECUTE and in every expression executor:

- installTypedPrepareParams built a new batch and one vector per parameter
  per execution.
- each ParamExpressionExecutor Dup'ed the typed value; the per-EXECUTE
  diagnostic probes and EvalFoldExpr build fresh executor trees, so every
  `?` was copied several times per statement.
- a `?` the planner narrowed to its consumer's integer type (protocol
  BIGINT vs an INT column) built a whole CAST executor per executor.

That is the sysbench random_points / random_ranges / nopk_random_points
regression (CI profiles: 30-44% of CPU under evalTyped / runtime.Callers).

Now:
- PrepareStmt owns the typed parameter vectors (typedPrepareParams) and an
  integer-conversion store; EXECUTE rewrites them in place and the process
  borrows them. Allocation happens only the first time a position/type is
  bound, or when its type changes. TEXT bytes are parsed in place.
- process.TypedParamConversions converts a narrowed integer once per
  (position, type) and Refresh rewrites it in place each execution; a value
  that does not fit keeps the CAST adapter and its error semantics.
- ParamExpressionExecutor returns a read-only reference (new
  Vector.WindowInto into an embedded descriptor) instead of a copy, skips
  routing once folded, and re-routes if the process holds new typed values.
  EvalWithoutResultReusing still hands out an owned copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

…#33076)

- ParamExpressionExecutor reads a string parameter as a read-only const
  reference to its row of the TEXT transport (embedded descriptor via
  Vector.WindowInto) instead of copying it into its own vector. A caller of
  EvalWithoutResultReusing still gets an owned copy, and a folded value is
  re-read when the process holds a different TEXT transport.
- COM_STMT_EXECUTE rewrites the statement's TEXT parameter vector from an
  empty area that keeps its capacity. SetBytesAt appends to the area, so it
  previously grew (and reallocated) on every execution with a string
  parameter longer than the inline varlena; now it grows only when an
  execution needs more room than any earlier one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · superseded

Commit: c3e10645f8be680345914c457eb2d7af978d8466

"interrupted"

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d369ebbb06fe6cab90ba7ae64a761c5bf90d94cf

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: d369ebbb06fe6cab90ba7ae64a761c5bf90d94cf

Assessment: request_changes

The patch addresses the earlier borrower-growth and whole-buffer copy findings. Statement-owned storage and borrowed reads reduce repeated copies, but the new ownership paths leave gaps in binary EXECUTE reuse, RESET cleanup, and allocation error handling.

Model: gpt-6.2-sol / xhigh

Session: 01a1ed86-9b09-7303-8d78-76024e7bf652 · slot 3 · generation 0

  • P2 pkg/sql/colexec/evalExpression.go:985: An operator requests an owned string parameter and its allocation account admits the payload but rejects the vector descriptor.
    Impact: The error path leaves the payload allocated and charged to the query account. Merge-order discards the returned vector on error, so executor cleanup cannot reclaim it.
    Evidence: The corrected probe left 65,536 bytes charged after freeing the executor. On the merge base, the executor retains the partially allocated vector for cleanup. Free the partial vector through its owning pool before returning the error. See colexec.jsonl and receipt 1795419811637984400-5.

  • P2 pkg/frontend/mysql_protocol.go:1087: A client repeatedly executes the same binary prepared statement with an equal-sized string parameter.
    Impact: Normal command teardown discards the TEXT transport after each execution, so the next packet allocates fresh storage despite the parser's reuse logic.
    Evidence: ExecRequest calls clearBinaryParamState at mysql_cmd_executor.go:7672, which frees the transport. The parser-only test passes, while a probe that includes this cleanup records two allocations between equal-sized packets. Keep reusable capacity across successful executions and preserve explicit cleanup on RESET and CLOSE. See frontend.jsonl and receipt 1795419706415971778-5.

  • P2 pkg/frontend/types.go:919: A client executes a binary prepared statement with a large JSON parameter, then resets the handle while keeping it open.
    Impact: RESET leaves the large typed payload buffer charged to the session. An idle handle can retain that capacity after subsequent smaller executions.
    Evidence: The focused probe retained 1,056,792 bytes after binding a 1 MiB JSON value, rebinding a small value, and resetting. The merge base frees the typed batch when it clears the Process binding. Release the statement-owned typed storage on explicit RESET. See frontend.jsonl and receipt 1795419706415971778-5.

  • P3 pkg/container/vector/vector.go:6391: A caller passes a read-only vector as both the source and destination of WindowInto for a nonempty range.
    Impact: The call passes the ownership and range checks, then panics when it slices the source data it just cleared.
    Evidence: The distinct-destination control passed and the self-alias case panicked. Reject self-aliasing before changing the destination or snapshot the source descriptor first. See core.jsonl and receipt 1795419681404209365-5.

Validation:

  • Verified the frozen patch, pinned policy, isolation preflight, native library hashes, and all 13 discussion entries. Reconciled the test commands, source fingerprints, exits, and logs in validation-reconciliation.json.

  • The focused borrower, typed-slot, integer-conversion, and selected-value copy tests passed. The first allocation probe used the wrong cleanup pool. The corrected probe confirmed account enforcement and reproduced the partial-allocation leak.

Limitations:

  • Local probes exercised the changed frontend and executor paths. The reported prepare BVT used a combined branch, and the sysbench comparison is author-reported. No full race suite, BVT, or benchmark was run locally on this head.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I independently verified that the successful-execution borrower list stays bounded and that the owned result copies only the selected parameter on this head. There is still a borrower leak on the early validation error path, reproduced through a real MySQL connection and called out inline.

I also confirmed two memory cleanup regressions from the current review:

  • At evalExpression.go:985, an owned string result got its payload allocation and then failed to allocate its descriptor. After executor teardown the PR still had 65,536 B charged to the allocation account. The same test on base f86cc46cfc returned the same capacity error with 0 B left charged. Free the partial result through its owning pool on error.
  • At types.go:975, binding a 1 MiB JSON value, rebinding a small value, and calling the RESET cleanup left 1,056,792 B charged while the handle was open. CLOSE brought the charge back to zero. Please release the typed parameter store on explicit RESET.

The regular COM_STMT_EXECUTE cleanup also frees the TEXT transport, so the second equal-sized bind still made two allocations. The parser-only reuse test misses that command boundary.

Twenty-one existing MySQL protocol integration cases passed, including multi-CN handle migration, NULL rebinding and streamed parameters. The error-path findings above still block merge.

// owner that runs many executions, each on a fresh process, such as a stored
// procedure, retains only the processes that still borrow the storage.
func (u *executeUserParams) lend(proc *process.Process) {
u.borrowers = slices.DeleteFunc(u.borrowers, func(borrower *process.Process) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] A failed background EXECUTE can still leave its Process in this slice. Binding calls lend before pagination validation. If validation returns an error, executeStmtInBack returns before installing the compiled runner cleanup. The next lend sees that Process still bound to u.vec and keeps it.

I reproduced this using a real MySQL connection to an embedded cluster. One prepared SELECT with a bound LIMIT was called from a stored procedure. Four successful CALLs left 1 borrower. After 32 CALLs with a rejected negative LIMIT, the same prepared statement retained 32 borrowers. DEALLOCATE brought the count to 0.

Please detach and drop the borrow on the execution's terminal path, including returns before a Compile exists. Add a regression test that keeps the prepared handle open across repeated validation failures.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d369ebbb06fe6cab90ba7ae64a761c5bf90d94cf

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: d369ebbb06fe6cab90ba7ae64a761c5bf90d94cf

Assessment: request_changes

The new MySQL reproduction confirms that a failed background EXECUTE can retain its Process until DEALLOCATE. The four findings from review 6018029216 remain open. Reusable statement storage and borrowed reads reduce copying, and the successful-execution borrower list now stays bounded. The borrow still needs cleanup when validation fails before compilation.

Model: gpt-6.2-sol / xhigh

Session: 01a1ee80-0d82-7030-a965-b51f496c3054 · slot 2 · generation 1

  • P2 pkg/frontend/computation_wrapper.go:1839: A stored procedure repeatedly runs EXECUTE … USING against the same open prepared statement, and validation rejects a bound value such as a negative LIMIT.
    Impact: Each failed execution leaves a Process reachable from the prepared handle. The borrower list grows with each failure, and subsequent binds scan that growing list.
    Evidence: Binding registers the Process before validation at line 1855. The error returns at back_exec.go:844 before the compiled-runner cleanup is installed, and wrapper teardown leaves the binding intact. The same-head MySQL report found one borrower after four successful calls, 32 after 32 rejected calls, and zero after DEALLOCATE. Detach and remove the borrower on every execution exit, including returns before a Compile exists, and cover repeated failures on an open handle.

  • P2 pkg/sql/colexec/evalExpression.go:985: An operator requests an owned TEXT parameter, and the allocation account admits the payload but rejects the vector descriptor.
    Impact: The payload remains allocated and charged after executor cleanup. Merge-order drops the result when it receives the error.
    Evidence: The retained probe left 65,536 bytes charged after freeing the executor. The follow-up reports zero bytes left charged on the merge-base control. Free the partial vector through its owning pool before returning the error.

  • P2 pkg/frontend/mysql_protocol.go:1087: A client repeatedly sends COM_STMT_EXECUTE with an equal-sized out-of-line string.
    Impact: Each execution allocates fresh TEXT transport storage despite the parser's reuse logic.
    Evidence: The command handler calls clearBinaryParamState at mysql_cmd_executor.go:7672, which frees the vector. The retained probe recorded two allocations for the next equal-sized packet after that cleanup. Preserve reusable capacity across successful executions and release it on explicit RESET and CLOSE.

  • P2 pkg/frontend/types.go:975: A client binds a large JSON value and issues COM_STMT_RESET while keeping the handle open.
    Impact: The idle handle retains the large typed payload allocation, even after a smaller execution.
    Evidence: The retained probe bound a 1 MiB JSON value, rebound a small value, and measured 1,056,792 bytes still charged after RESET. The follow-up reports that CLOSE released the charge. Release the statement-owned typed parameter store on explicit RESET.

  • P3 pkg/container/vector/vector.go:6391: A caller passes the same read-only flat vector as the source and destination of WindowInto for a nonempty range.
    Impact: WindowInto panics after overwriting the source descriptor and then slicing its cleared backing.
    Evidence: The retained distinct-destination control passed, and the same-descriptor case produced a slice-bounds panic. Reject self-aliasing before mutation or snapshot the source descriptor before filling the destination.

Validation:

  • The frozen scope, pinned policy, and patch whitespace check passed. The patch matches the prior reviewed head byte for byte.

  • Reconciled the retained frontend, vector, process, and colexec probes with their commands, source fingerprints, exits, and logs. Successful borrower pruning, selected-value copying, and typed reuse passed their focused checks.

  • Traced the newly reported MySQL failure through parameter binding, pagination validation, compile return, and background teardown. Receipts and discussion evidence are indexed in review-validation.md.

Limitations:

  • The new MySQL reproduction and the 21 protocol passes are reviewer-reported. The reported prepare BVT used a combined branch, and the sysbench results are author-reported.

@fengttt
fengttt merged commit 32c9bc6 into matrixorigin:main Nov 23, 2026
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 23, 2026
…ad) into prepared-paramvals-pointer-storage
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 23, 2026
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 23, 2026
… copy retry values contiguously

Address review on matrixorigin#33083:

- clearBinaryParamState, run after every COM_STMT_EXECUTE, now drops the
  execution's values and detaches the TEXT transport from the processes
  but keeps its memory for the next execution; Close and an explicit
  COM_STMT_RESET free it. Before, it freed the vector after every command,
  so the next execute allocated a new one and the decoder's in-place reuse
  never happened across commands. An empty vector reads as "no binary
  parameters" to every consumer; cached plans re-window it through
  ResetForNextQuery, as they already do for typed parameters.

- The decoder clears every parameter row before decoding. A NULL only sets
  its bit, so with the buffer reused a NULL row kept the previous
  execution's value (found by an existing diagnostic-proof test).

- An execution's parameter source bindings are computed into storage the
  statement owns (preparedExecutionBindingsInto): no allocation after the
  first execution.

- The retry snapshot stays a per-execution immutable copy (retry snapshots
  are generation proofs that can outlive their execution), but
  CopyParamValues copies into contiguous storage: a constant number of
  allocations instead of boxing every parameter again.

The stored-procedure borrower finding was fixed on matrixorigin#33081 (d369ebb,
merged to main) and arrives with the merge of main.

Tests: re-executing through the per-command cleanup reuses the protocol
buffer without allocating and leaves no value behind a NULL (fails without
the fix); binding allocates nothing after the first execution; a retry
snapshot's allocations do not grow with the parameter count and the
snapshot is independent of later writes; failed-command tests now check
that no values remain rather than that the buffer is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt added a commit that referenced this pull request Nov 24, 2026
…33076) (#33083)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #33076 (follow-up). The full redesign is tracked in #33082.

#33081 is merged, and main is merged into this branch. #33091 builds on
this PR, so merge this one first.

## What this PR does / why we need it:

The planner's parameter values for an execution (`paramVals`, an `[]any`
of `plan.ParamValue`) were rebuilt on every EXECUTE: a new `[]any`, and
each `ParamValue` struct boxed into an interface, one heap allocation
per parameter per execution. This continues the rule from #33081: a
prepared statement allocates what parameter binding needs once and
reuses it.

- **`plan.ParamValueStore`** is owned by the prepared statement. Every
execution resets and rewrites it in place, and `paramVals` holds
`*ParamValue` pointing into it. Boxing a pointer doesn't allocate.
- **`plan.AsParamValue(any) (ParamValue, bool)`** reads a value held by
pointer or by value and returns a copy. The ~70 consumers (`frontend`,
`plan`, `compile`) that adjust their copy locally keep value semantics;
changing the copy never changes the statement's storage.
- **`plan.SetParamValueAt`** writes adjusted values back through the
pointer. Three sites do this: conversion runtime types and BIT_COUNT
numeric rebinding.
- Both binary-protocol `preparedParamValues` and SQL `EXECUTE … USING`
fill the statement's store.
- `ParamValue.Value` (`any`) is unchanged, so its string copy and
interface box remain. Removing them is the typed redesign in #33082.
Zero-copy strings into reused storage are intentionally not done:
parameter values can outlive an execution (plan literals, cache keys,
warnings).

Audit notes:
- No type switch dispatches on `case ParamValue`, so no consumer
silently falls through on a pointer.
- `fmt` renderings receive the unwrapped `Value`, never the wrapper.
- CTAS copies the values into its own `[]executor.ParamValue`.
- Values aren't retained past the execution: `ResetParamRefRule` copies
the slice and only reads it, and the compile's slice is reset each
execution.
- The retry snapshot (`preparedExecutionRetry`) is an immutable
generation proof that can outlive its execution. It copies the values
out (`CopyParamValues`) into contiguous storage: a constant number of
allocations, not one box per parameter.

### Review fixes (mo-bot review of `a897ce9`)
- **P2, stored-procedure borrowers:** already fixed on #33081
(`d369ebbb06`, on main). `executeUserParams.lend` forgets processes that
have finished. It arrives here with the merge of main.
- **P2, retry snapshot re-boxing every value:** `CopyParamValues` now
copies into contiguous storage, so the snapshot's cost no longer grows
with the parameter count.
- The snapshot stays per execution. Making it statement-owned breaks
`TestPreparedFieldRetryDeclarationGeneration`, which relies on an old
snapshot surviving the next execution.
- An execution's source bindings are now computed into statement-owned
storage (`preparedExecutionBindingsInto`), with no allocation after the
first execution.
- **P3, protocol buffer freed after every command:**
`clearBinaryParamState`, which runs after every COM_STMT_EXECUTE, now
keeps the TEXT transport's memory.
- It drops the values and detaches the vector from the processes. Close
and an explicit COM_STMT_RESET free it.
- An emptied vector reads as "no binary parameters" to every consumer,
and cached plans re-window it through `ResetForNextQuery`.
- The decoder now clears every parameter row before decoding. A NULL
only sets its bit, so with the buffer reused, a NULL row kept the
previous execution's value. An existing diagnostic-proof test caught
this.

### Measured
`testing.AllocsPerRun` of `preparedParamValues` with 10 BIGINT
parameters:

| | Go allocations per EXECUTE |
|---|---|
| before | 31 (slice + 10 `ParamValue` boxes + 2 per parameter) |
| after | 20 (the 2 per parameter that remain: string copy and `Value`
box) |

## Tests
- **New:** `AsParamValue` copy semantics for both forms;
`SetParamValueAt` write-through; `ParamValueStore` reuse with zero
allocations once large enough.
- **Updated:** existing tests compare `paramVals` through
`AsParamValue`, since elements are now pointers.
- **New (review):**
- Re-executing through the real per-command cleanup reuses the protocol
buffer without allocating, and leaves no value behind a NULL. Fails
without the fix.
  - Binding allocates nothing after the first execution.
- A retry snapshot's allocations do not grow with the parameter count,
and it is independent of later writes.
- Failed-command tests now check that no values remain, instead of
checking that the buffer is gone.
- **Passing:** `pkg/frontend`, `pkg/sql/plan`, `pkg/sql/compile`,
`pkg/sql/colexec`, `pkg/vm/process`, `pkg/container/vector`.
- **Local BVT:** `test/distributed/cases/prepare` passes 100%.
- **Go differential client** (COM_STMT and interpolated text:
int/uint/float/bool/string, typed NULLs, and one statement re-executed
across value and NULL types): output identical to the build reviewed at
`a897ce9`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
fengttt added a commit that referenced this pull request Nov 24, 2026
… PrepareParamKind (#33082) (#33091)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes:

issue #33082 (stages 1, 2, 3a and 3b)

Builds on #33081 and #33083, both merged; the diff against main is this
PR's own work only.

## What this PR does / why we need it:

The planner now plans prepared parameters from typed values and types,
instead of re-parsing a TEXT spelling according to a separately recorded
`StringConversionKind`.

### Stage 1: numeric COM_STMT parameters are native
- **1a.** A COM_STMT_EXECUTE integer, float or Boolean parameter now
reaches the planner as a native value (`int64`, `uint64`, `float64`,
`bool`), the same types SQL `EXECUTE … USING` user variables already
use.
- **1c.** No producer gives the planner integer, float or Boolean text
with a non-string kind any more, so the branches that re-parsed it are
removed:
  - pagination validators;
  - `isPositive` / `isNonNegativePreparedInteger`;
  - `PreparedParamValueNumericReprepareType`;
  - `ResetParamRefRule.runtimeParamType`.

### Stage 2: a COM_STMT DECIMAL is decoded once
- **Before:** the parameter carried the raw packet spelling in `Value`
and a canonical lexeme in `MaterializedValue`. Every reader had to pick
the right one, and the DECIMAL literal path did not.
- **Now:** `Value` holds the canonical lexeme, which the executor also
reads, and `MaterializedValue` and its ten reader branches are removed.
- **Unchanged:** the visible scale of the spelling (`1.5` vs `1.50`) is
decided at decode in `DirectResultType` and carried by the binding, so
result types are as before.
- **Temporal parameters keep their text,** which is a pure function of
the wire bytes.

### Stage 3a: kind comes from the type
- **Readers:** all ~25 planner and frontend readers of
`PrepareParamKind` now use `plan.ParamValueKind`. It takes the kind from
the parameter's type (`RuntimeType`, else `SourceType`) when that type
is integer, float, DECIMAL or Boolean.
- **Fallback:** the recorded kind is used only when the type is
text-like or absent, which covers two cases:
  - NULL parameters;
- user variables copied from a system variable (`SET @v = @@var`), which
hold the variable's text with its numeric kind.

### Stage 3b: the kind is no longer stored
- **Removed:** the `PrepareParamKind` field from `ParamValue` and
`UserDefinedVar`. Also removed: the SET path's kind out-parameter,
`transparentPrepareParamKind`, and the kind-taking user-variable setter
variants.
- **Rule:** `plan.ParamValueKind` derives the kind only from the
parameter's type. A parameter with no type, which is an untyped NULL, is
String.
- **NULL parameters:** a NULL takes no part in deciding how a parameter
is planned, as in MySQL. MO already planned COM_STMT NULLs as untyped
(except BLOB), whatever wire type the packet names. The stored kind only
split their plan-cache entries.
- **`SET @v = @@var`:** the copy is now plain text with String kind.
Before, it was the variable's text with the variable's numeric kind.
Making system-variable copies MySQL-typed is out of scope.
- **Rolling upgrade:** `MigrateUserDefinedVar.PrepareParamKind` stays on
the wire. A new CN writes the kind derived from the type, so older CNs
read the same value, and it ignores the field on receipt.
- **Tests:** tests that hand-built kind-only values now build the type
production gives them, such as the DECIMAL type of the spelling.

## Verification
Every stage was checked against the previous build with:
- **`test/distributed/cases/prepare` BVT:** 100%.
- **445 further BVT files that use PREPARE/EXECUTE:** identical results.
The only failures are 5 files that fail identically on the pre-change
build (`foreign_exttab` 19, `isolation_2` 60, `clone` 5, `like_operator`
1, `replace_view` 1), which need external services or are environmental.
- **A Go differential client** (`database/sql`;
int64/uint64/float64/bool/string arguments). It runs 48 query shapes
plus `SET @v = ?` and `EXECUTE … USING @v` sequences, each over COM_STMT
and as interpolated text. Output is identical to the pre-change build.
- From stage 3b on, its driver is patched to also send NULLs that carry
a wire type (TINY, LONG, LONGLONG, DOUBLE, NEWDECIMAL, VAR_STRING, BLOB,
DATE), the way C and PHP clients send them.
- It also re-executes one prepared statement while alternating integer,
typed-NULL, string, float and DECIMAL-NULL arguments.
- **A JDBC differential client** (Connector/J with
`useServerPrepStmts=true`). It sends real binary-protocol `NEWDECIMAL`,
`DATE`, `TIME`, `DATETIME`, `LONG`, `SHORT`, `TINY`, `DOUBLE` and
`FLOAT` parameters: 50 queries × 25 arguments, including DECIMAL
spelling variants, exponents, 23-digit values and SRIDs. It also covers
`SET @v = ?`, `SELECT … INTO @v` and `EXECUTE … USING @v`. Output is
identical to the previous stage.

In stage 3b, the Go client caught one regression in my first version: a
COM_STMT text offset in `LAG`/`LEAD` was accepted. It is fixed and
covered by a unit test, and the rerun is identical.

For stages 1c and 3a, instrumented builds confirmed that the removed or
replaced logic never disagreed with the new logic in production. The
legacy branches never fired, and kind matched the type-derived kind at
every producer except the `SET @v = @@var` copies, which keep their
recorded kind. Unit tests that hand-built legacy value shapes now build
the shapes the frontend produces (`prepared_param_shapes_test.go`).

## Follow-on
Per #33082, the next step is the MySQL model: plan with the actual
parameter types and cache one plan per type signature. That removes
`ResetParamRefRule`'s per-function execute-time rebinding.

## Tests
- **Passing:** `pkg/frontend`, `pkg/sql/plan`, `pkg/sql/compile`,
`pkg/vm/process`, `pkg/util/executor`.
- **BVT and differential clients:** see Verification above.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch had an error being deployed

1 failed deployment
ci — 5dd8f1b4 Deployed Nov 23, 2026 by fengttt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants