Repository navigation
perf(prepare): statement-owned storage for planner parameter values (#33076) - #33083
Conversation
…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]>
…o fix-prepared-param-no-alloc
…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]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
This pull request is merged. |
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]>
…ge' into prepared-paramvals-pointer-storage
|
Addressed in
Verification:
|
…eview fixes, main) into prepared-params-typed-source
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 5a9d1c855fc0f6963e828d6bf1ecad9aed94b437
Assessment: request_changes
Statement-owned storage removes repeated parameter boxing, and contiguous retry snapshots preserve execution isolation. The earlier borrower, retry allocation, and decoder reuse findings are resolved. Binary prepared statements still retain the planner’s copy of the last parameter payload after an explicit reset.
Model: gpt-6.2-sol / xhigh
Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3
- P2
pkg/frontend/types.go:1019: A client executes a binary prepared statement with a large string parameter and leaves the handle open, even after a successful COM_STMT_RESET.
Impact: Each open handle can pin a heap copy of its last payload until the next execution or close. Clear the planner value slots after their last execution consumer while keeping the backing arrays reusable and leaving retry snapshots independent.
Evidence:preparedParamValuescopies the input into the statement-owned store. Command cleanup empties only the protocol vector, and reset frees only that vector. The wire probe confirmed that 1,048,576 planner bytes remained after both operations. A later execution on the same handle succeeded.
Validation:
-
Verified the frozen 26-file patch, pinned policy, seven discussion entries, native inputs, and isolated executor preflight.
-
All 18 maintained frontend and planner test roots passed under race. Only the added wire retention probe failed. See
prepared-race.jsonlandchecks/1795475268313809138-3.json. -
Frozen CI reports successful Ubuntu unit tests, coverage, and Proxy and Pessimistic multi-CN BVT.
Limitations:
-
The frozen Connector/J pool-reset job failed and its causal log was unavailable. Local wire tests for session reset and change-user passed.
-
The prepare BVT and differential-client results are author-reported. End-to-end sysbench performance was unmeasured.
…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]>
… 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>
What type of PR is this?
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[]anyofplan.ParamValue) were rebuilt on every EXECUTE: a new[]any, and eachParamValuestruct 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.ParamValueStoreis owned by the prepared statement. Every execution resets and rewrites it in place, andparamValsholds*ParamValuepointing 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.SetParamValueAtwrites adjusted values back through the pointer. Three sites do this: conversion runtime types and BIT_COUNT numeric rebinding.preparedParamValuesand SQLEXECUTE … USINGfill the statement's store.ParamValue.Value(any) is unchanged, so its string copy and interface box remain. Removing them is the typed redesign in Redesign prepared parameters: planner reads the typed parameter batch; remove ParamValue string-conversion #33082. Zero-copy strings into reused storage are intentionally not done: parameter values can outlive an execution (plan literals, cache keys, warnings).Audit notes:
case ParamValue, so no consumer silently falls through on a pointer.fmtrenderings receive the unwrappedValue, never the wrapper.[]executor.ParamValue.ResetParamRefRulecopies the slice and only reads it, and the compile's slice is reset each execution.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)d369ebbb06, on main).executeUserParams.lendforgets processes that have finished. It arrives here with the merge of main.CopyParamValuesnow copies into contiguous storage, so the snapshot's cost no longer grows with the parameter count.TestPreparedFieldRetryDeclarationGeneration, which relies on an old snapshot surviving the next execution.preparedExecutionBindingsInto), with no allocation after the first execution.clearBinaryParamState, which runs after every COM_STMT_EXECUTE, now keeps the TEXT transport's memory.ResetForNextQuery.Measured
testing.AllocsPerRunofpreparedParamValueswith 10 BIGINT parameters:ParamValueboxes + 2 per parameter)Valuebox)Tests
AsParamValuecopy semantics for both forms;SetParamValueAtwrite-through;ParamValueStorereuse with zero allocations once large enough.paramValsthroughAsParamValue, since elements are now pointers.pkg/frontend,pkg/sql/plan,pkg/sql/compile,pkg/sql/colexec,pkg/vm/process,pkg/container/vector.test/distributed/cases/preparepasses 100%.a897ce9.🤖 Generated with Claude Code