Skip to content

refactor(prepare): plan prepared parameters from typed values; remove PrepareParamKind (#33082) - #33091

Merged
fengttt merged 32 commits into
matrixorigin:mainfrom
fengttt:prepared-params-typed-source
Nov 24, 2026
Merged

fengttt merged 32 commits into
matrixorigin:mainfrom
fengttt:prepared-params-typed-source

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 #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

fengttt and others added 14 commits November 22, 2026 20:14
…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]>
…#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]>
…igin#33076)

SQL EXECUTE ... USING built a new TEXT parameter vector and five metadata
slices on every execution and handed them to the process to free. The
prepared statement now owns that storage (executeUserParams) and every
execution rewrites it in place: the vector restarts from an empty area that
keeps its capacity and the slices are reused, so after the first execution
binding allocates only when a value needs more room than before. The process
borrows the vector; the statement detaches its borrowers and frees the
storage on Close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An execution's planner parameter values (paramVals, []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).

The prepared statement now owns the values (plan.ParamValueStore): every
execution resets and rewrites them in place, and paramVals holds
*ParamValue pointing into the store, which boxes without allocating.

- plan.AsParamValue reads a value held by pointer or by value and returns a
  copy, so the ~70 consumers that adjust their copy locally keep value
  semantics; plan.SetParamValueAt writes back through the pointer.
- Binary protocol (preparedParamValues) and SQL EXECUTE ... USING both fill
  the statement's store.
- ParamValue.Value is unchanged: its string copy and interface box remain
  (the typed redesign is tracked in matrixorigin#33082).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
preparedExecutionRetry is an immutable snapshot of the execution-time
parameter values. With paramVals pointing into the statement-owned
ParamValueStore, a shallow copy of the slice aliased that storage, so a
write-back or a re-fill during the retry would change the snapshot.
CopyParamValues copies the values out (retries are rare; this is the only
allocation they add).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
matrixorigin#33082 stage 1a)

A COM_STMT_EXECUTE parameter whose runtime type is a fixed-width integer,
float or Boolean now reaches the planner as the native Go value (int64,
uint64, float64, bool) that SQL EXECUTE user variables already use, instead
of its TEXT spelling that consumers parse again. BIT, YEAR, DECIMAL, temporal
and string parameters keep their text. PrepareParamKind is unchanged, so the
deliberate COM_STMT vs SQL EXECUTE behaviour keyed on "this parameter is
text" is untouched.

Verified behaviour-neutral: frontend/plan/compile UT, prepare BVT 100%, and a
differential COM_STMT client (42 parameterized queries x 12 int64/uint64/
float64/bool/string arguments, prepared vs interpolated) with identical
output before and after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…string parameter (matrixorigin#33076)

Address review on matrixorigin#33081:

- executeUserParams.lend now forgets processes that no longer borrow the
  statement storage (freed, or rebound). A stored procedure that runs the
  same EXECUTE ... USING on a fresh process per execution over one session
  pool no longer retains every process until the statement closes.

- ParamExpressionExecutor.EvalWithoutResultReusing materializes only the
  selected TEXT parameter into its own constant vector, preserving type and
  logical length. Dup of the read-only reference copied the whole TEXT
  transport area, i.e. every parameter of the execution.

Regression tests: 32 executions on fresh processes over one pool retain one
borrower; owning an inline parameter next to a 1 MiB parameter copies only
the inline value. Both fail without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
matrixorigin#33082 stage 1c)

With COM_STMT numeric parameters planned from native values (stage 1a) and
SQL EXECUTE user variables already native, no producer gives the planner an
integer, float or Boolean parameter as text with a non-string
StringConversionKind any more. Remove the branches that re-parsed that text:

- validatePreparedPaginationValue: Integer/Boolean text forms. Text remains
  valid only as the COM_STMT Connector/ODBC MYSQL_TYPE_STRING integer form.
- isPositivePreparedInteger / isNonNegativePreparedInteger: Integer and
  Boolean text forms.
- PreparedParamValueNumericReprepareType: the Integer/Float/Boolean kind
  switch; DECIMAL text keeps its envelope.
- ResetParamRefRule.runtimeParamType: Integer/Float/Boolean kind cases;
  DECIMAL and text keep spelling-based typing.

Evidence the branches were dead in production: instrumented, they never
fired in the prepare BVT, in 445 further BVT files that use PREPARE/EXECUTE,
or in a differential COM_STMT / SET @v = ? / EXECUTE USING client; only plan
unit tests built such values by hand. Those tests now build the shapes the
frontend produces (prepared_param_shapes_test.go).

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

Queue requested — the merge queue status continues in this comment ↓.

…alue (matrixorigin#33082 stage 2)

A COM_STMT DECIMAL parameter carried two spellings: Value kept the raw
packet lexeme and MaterializedValue the bounded canonical one, and every
consumer had to prefer the right one (typedDecimalParamExpr did not, and
reparsed the possibly packet-sized raw text). The frontend now decodes the
lexeme once and Value holds the canonical form, which is also what the
executor reads from the TEXT vector. MaterializedValue and its ten reader
branches are removed.

The visible scale of the spelling ("1.5" vs "1.50") is unchanged: it is
decided at decode into DirectResultType and carried by the binding, so
result types, typed-batch scale and the binding cache key are as before.
Temporal parameters keep their text, which is a pure function of the wire
bytes.

Verified with a JDBC differential client that sends real binary-protocol
NEWDECIMAL/DATE/TIME/DATETIME/LONG/SHORT/TINY/DOUBLE/FLOAT parameters (50
queries x 23 arguments, including decimal spelling variants, exponents,
38-digit values and SRIDs): output identical to stage 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt and others added 2 commits November 23, 2026 16:10
…itch:partial

The MySQL wire protocol has only FLOAT and DOUBLE, so a COM_STMT parameter
never carries a low-precision float runtime type; TestTypeSwitchFamilies
(from main) requires the omission to be stated.

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

XuPeng-SH commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: cf0e9b1a7d4cfc2c191825008fcda942f91cb09d

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: cf0e9b1a7d4cfc2c191825008fcda942f91cb09d

Assessment: request_changes

Deriving conversion kind from SQL type removes duplicate planner metadata. The frozen head rejects previously accepted BIT, YEAR, and spatial SRID bindings. The stacked storage change also retains a copied parameter payload after a successful statement reset.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/frontend/computation_wrapper.go:2444: Bind MYSQL_TYPE_BIT to a prepared LIMIT or LAG argument, or MYSQL_TYPE_YEAR to an OFFSET or NTH_VALUE argument.
    Impact: The server rejects previously accepted executions with an incorrect-arguments error.
    Evidence: The native decoder leaves BIT and YEAR as strings, while the new pagination and window validators require native values for integer domains. All four packet cases passed on the frozen base and failed on the candidate. Decode BIT and YEAR to native values while preserving their SQL domains and the existing rules for actual text bindings.

  • P2 pkg/frontend/computation_wrapper.go:2415: Bind signed MYSQL_TYPE_TINY value 1 or MYSQL_TYPE_DOUBLE value 1.0 to the SRID marker in a prepared ST_SRID call.
    Impact: A geometry statement that accepted SRID 1 on the base now fails with SRID should be an integer.
    Evidence: The old planner received the text 1 for both packets. The new planner receives a bool or float64, which geometrySRIDRuntimeValue rejects. Both packets passed on the frozen base and failed on the candidate. Preserve the established SRID validation when consuming native wire values, including its range and fractional-value checks.

  • P2 pkg/frontend/types.go:986: Execute a prepared statement with a large string parameter, issue COM_STMT_RESET, and leave the handle open.
    Impact: The live statement keeps the previous payload on the Go heap despite a successful reset. Pooled connections can retain these copies across idle prepared handles.
    Evidence: The reset frees the protocol vector but leaves the new statement-owned paramValues store populated. The wire probe measured 1,048,576 bytes retained by that store after a successful reset and verified that the statement still re-executed. Clear the stored payloads on explicit reset while preserving statement reuse.

Validation:

  • Verified the frozen head, merge base, patch content, and 37 target-base policy files. Private /tmp and loopback preflight passed, and the retained native libraries matched the current inputs.

  • Focused frontend and planner tests ran with the supplied executor. The reset probe was the sole failing test in that run. See checks/1795483980675430159-2.json and review-go-test.stdout.

  • Ran the same packet probe on the candidate and a verified frozen-base overlay. Six cases passed on the base and failed on the candidate. Three SHORT controls passed on both. See checks/1795484072606809126-2.json, checks/1795484159175975834-2.json, and the corresponding review-wire logs.

Limitations:

  • Local execution covered focused Go and protocol tests. Full distributed BVT, the author’s differential clients, and the follow-on design’s sysbench comparison were outside the local validation coverage.

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 and others added 2 commits November 23, 2026 20:36
…s-typed-source

The branch already contains matrixorigin#33083's final tree; conflict hunks take ours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r values on reset

Review fixes for matrixorigin#33091 (mo-bot review 6032325177):

- BIT and YEAR parameters decode to native values like the other integer
  types (uint64 / int64), keeping T_bit / T_year as their runtime type. The
  pagination and window-offset validators only accept native values for an
  integer-domain parameter, so a BIT LIMIT/LAG or YEAR OFFSET/NTH_VALUE was
  rejected after stage 1.
- A COM_STMT TINY 0/1 (Boolean) or FLOAT/DOUBLE SRID is validated as the text
  the wire carried (preparedProtocolTextValue), so ST_SRID(g, ?) accepts 1 and
  1.0 again and still rejects fractional and out-of-range values. SQL EXECUTE
  values keep their own validation.
- preparedNumericValueSpelling spells a Boolean as 1/0 (TINYINT(1)), and the
  COALESCE and numeric-prefix witnesses use it instead of fmt.Sprint, which
  spelled a native Boolean as "true".
- COM_STMT_RESET clears the statement's planner parameter values
  (ParamValueStore.Clear), which could hold a large string payload, and keeps
  the memory for the next execution.

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

fengttt commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — all three findings reproduced and are fixed in 58f4552 (on top of a merge of main with the squashed #33083).

P2 BIT/YEAR (LIMIT, OFFSET, LAG, NTH_VALUE). Stage 1 decoded only plain integer, float and Boolean wire types to native values, so BIT and YEAR stayed text while their kind is Integer, which the pagination/window validators no longer accept as text. binaryProtocolNativeParamValue now decodes BIT to uint64 and YEAR to int64; the runtime type stays T_bit / T_year, so the SQL domain is unchanged. Actual text bindings (MYSQL_TYPE_STRING) keep their existing rules.

P2 ST_SRID with TINY 1 / DOUBLE 1.0. A COM_STMT Boolean or float SRID is now validated as the text the wire carried (preparedProtocolTextValue): 1 and 1.0 are SRID 1 again; 1.5, negative and out-of-range values are still rejected with the same errors. This is keyed on IsBinaryProtocol, so SQL EXECUTE values keep their existing validation (a float/bool user variable is still rejected, as TestGeometrySRIDRuntimeValueValidation pins). Related: the numeric witnesses for COALESCE and numeric-prefix rebinding used fmt.Sprint, which spells a native Boolean as true; they now use preparedNumericValueSpelling, which spells it 1/0 (TINYINT(1)).

P2 COM_STMT_RESET retains payload. resetBinaryParamState now calls ParamValueStore.Clear(), which drops every stored value (including entries past the current length) and keeps the memory for the next execution.

Tests: TestParseExecuteDataNativeValuesKeepValidation drives the six packet cases (BIT LIMIT, YEAR OFFSET, BIT LAG, YEAR NTH_VALUE, TINY 1 SRID, DOUBLE 1.0 SRID) through ParseExecuteData → preparedParamValues → the EXECUTE validators / plan fill; each case fails without its fix. Plus TestPrepareStmtResetDropsPlannerParamValues, TestParamValueStoreClearDropsPayloads, TestPreparedProtocolTextValue.

Validation: frontend / plan / compile / types / process unit tests pass; prepare BVT 100%; Go differential COM_STMT client identical to the previous build; JDBC differential client identical apart from current-date values.

@mergify

mergify Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🛑 Queue command cancelled

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request once it meets the queue conditions

@XuPeng-SH

XuPeng-SH commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: fa6a8d308516016d6c54bb26cca12908fd821ed1

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: fa6a8d308516016d6c54bb26cca12908fd821ed1

Assessment: request_changes

Deriving conversion kind from SQL type removes redundant parameter state. The revision addresses the earlier BIT, YEAR, TINY and DOUBLE SRID, and statement-reset findings. Two compatibility regressions remain in SQL EXECUTE pagination and binary-protocol SRID validation.

Model: gpt-6.2-sol / xhigh

Session: 01a20682-9189-75a0-839a-f36d8b2372a5 · slot 1 · generation 3

  • P2 pkg/frontend/mysql_cmd_executor.go:1675: Enable autocommit, run SET @lim = @@SESSION.autocommit, then bind @lim to LIMIT ? through SQL EXECUTE … USING.
    Impact: The prepared statement now returns Incorrect arguments to EXECUTE for a value the baseline admitted.
    Evidence: The system-variable projection produces text 1. The baseline SET path carried the underlying integer conversion kind alongside that text. The new SET path stores only the text type, and pkg/sql/plan/utils.go:5551 rejects text from SQL EXECUTE. The extracted validators confirmed the admission change and preserved the literal integer and string controls. Preserve the numeric source when copying the setting so a literal string remains invalid.

  • P2 pkg/frontend/computation_wrapper.go:2403: Execute a binary prepared SET @srid = ST_SRID(ST_SRID(ST_GeomFromText('POINT(1 2)'), ?)) with a NEWDECIMAL payload of 10.
    Impact: The prepared SET now rejects SRID 10 with SRID should be an integer.
    Evidence: Prepared SET uses the plan-fill path, where the baseline passed the raw 10 to the SRID validator. The new parameter value holds the canonical 1e1, which reaches the strict integer parser through pkg/sql/plan/visit_plan_rule.go:1241. The extracted production canonicalizer and validator confirmed that 10 is accepted and 1e1 is rejected. The 11 and 1.5 controls kept their prior outcomes. Preserve SRID admission when discarding the raw DECIMAL spelling and cover the prepared SET path.

Validation:

  • Verified the frozen head, complete patch, merge base, and 37 pinned policy files. Private /tmp and loopback preflight and native-library provenance checks passed. See frozen-inputs.stdout, preflight.stdout, and native.stdout.

  • The extracted pagination, native BIT and YEAR, and SRID checks passed with the supplied test executor. See receipts 1795515436888991588-5.json and 1795515460558503457-2.json, with logs review-scalar.jsonl and review-srid.jsonl.

  • The frozen CI snapshot reports successful Ubuntu unit tests, Connector/J Pool Reset E2E, proxy BVT, and pessimistic multi-CN BVT. The receipt and discussion audit passed in 1795515526789799441-6.json.

Limitations:

  • The local frontend, planner, wire, and SQL integration runs timed out before reporting test execution. The two findings rely on the frozen source paths and extracted checks. The full server entry points were traced in source.

  • The linked issue's follow-on sysbench comparison had no local execution evidence for this review.

@mergify

mergify Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

queue

🛑 The queue request has been cancelled: new commits were pushed

Details

@fengttt pushed to this pull request after queue was requested. Review the new commits and request it again.

…OM_STMT DECIMAL

SET @v = @@x copies a Boolean or DOUBLE system variable, which the synthetic
SELECT projects as TEXT. The variable's kind now comes from its type, so the
copy became a text parameter and SQL EXECUTE rejected it in LIMIT (SET @lim =
@@autocommit). The copy now takes the system variable's numeric value and
type, as in MySQL, where @lim is the integer 1. String system variables and
literal strings keep their TEXT copy.

A COM_STMT DECIMAL reaches the planner as its canonical lexeme, which spells
10 as 1e1, and the SRID check parsed that text strictly. A DECIMAL without a
visible fraction is now read as its integer digits; 10.0 and 1.5 are still
rejected.

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

fengttt commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Both findings reproduced, and both are fixed in b651d93.

P2: SQL EXECUTE pagination with SET @lim = @@autocommit. A Boolean or DOUBLE system variable is projected as TEXT by the synthetic SELECT (systemVariableDeclaredType keeps the legacy envelope for those classes). The parameter kind now comes from the variable's type, so the copy became a text parameter. When the right-hand side is a system variable (parentheses allowed) and the projected value is text, SET @v = @@x now stores the variable's numeric value and type: integer → BIGINT, unsigned → BIGINT UNSIGNED, double → DOUBLE, Boolean → BIGINT 0/1. This matches MySQL, where @lim is the integer 1. String system variables and literal strings keep their TEXT copy, so SET @lim = '1' is still rejected by LIMIT ?.

P2: prepared SRID with a NEWDECIMAL 10. The planner gets the DECIMAL's canonical lexeme, which spells 10 as 1e1. preparedProtocolTextValue, which feeds both SRID paths (the binder and the plan fill that prepared SET uses), now reads a COM_STMT DECIMAL whose visible scale is 0 as its integer digits. 10.0 (visible scale 1) and 1.5 are still rejected with SRID should be an integer. A lexeme with more than 20 digits stays as it is and is rejected, as the raw spelling was.

Tests:

  • TestSetUserVarFromSystemVarKeepsNumericType covers @@autocommit, a parenthesized session copy, a double, a string variable and a literal string. It goes through buildExecuteUserParams… and ValidatePreparedPaginationParams.
  • TestParseExecuteDataNativeValuesKeepValidation gains NEWDECIMAL 10/11/10.0/1.5 SRID packets on the plan-fill path.
  • TestPreparedProtocolTextValue and TestPreparedDecimalIntegerSpelling are extended.
  • With either fix reverted, only the autocommit, parenthesized, double and NEWDECIMAL 10 cases fail.

Validation: the frontend, plan and compile package tests pass. golangci-lint reports 0 issues.

This branch was previously deployed

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

Labels

kind/refactor Code refactor size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants