Skip to content

perf(prepare): statement-owned storage for planner parameter values (#33076) - #33083

Merged
fengttt merged 18 commits into
matrixorigin:mainfrom
fengttt:prepared-paramvals-pointer-storage
Nov 24, 2026
Merged

fengttt merged 18 commits into
matrixorigin:mainfrom
fengttt:prepared-paramvals-pointer-storage

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

  • 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 fix(prepare): never allocate for parameter binding after the first execution (#33076) #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

fengttt and others added 7 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]>
@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.

@fengttt

fengttt commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Local BVT: test/distributed/cases/prepare passes 100% (all cases) on a single-node server built from prepared-paramvals-pointer-storage (#33081 + #33083 combined).

fengttt and others added 2 commits November 22, 2026 21:23
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]>
@fengttt

fengttt commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in d31fa59b5f, after merging main, which now contains the squashed #33081:

  • P2, stored-procedure borrowers (computation_wrapper.go:2672): fixed on fix(prepare): never allocate for parameter binding after the first execution (#33076) #33081 in d369ebbb06, now on main. executeUserParams.lend forgets processes that no longer borrow the statement storage. TestExecuteUserParamsForgetsFinishedProcesses runs 32 executions on fresh processes over one pool and retains one borrower.
  • P2, eager retry snapshot (prepared_execution.go:221):
    • CopyParamValues copies into contiguous storage, so the snapshot's allocations no longer grow with the parameter count (TestPreparedExecutionRetryAndBindingsReuseStatementStorage: 2 and 100 parameters cost the same).
    • The snapshot itself stays per execution. A statement-owned snapshot breaks TestPreparedFieldRetryDeclarationGeneration, where a retry snapshot outlives the next execution as a generation proof.
    • The execution's source bindings are now statement-owned (preparedExecutionBindingsInto), with zero allocations after the first execution.
  • P3, buffer freed per command (mysql_protocol.go:1087):
    • clearBinaryParamState keeps the TEXT transport's memory; only Close and COM_STMT_RESET free it.
    • Keeping it exposed a NULL-after-value leftover, so the decoder now clears every row before decoding.
    • TestExecuteParamStorageSurvivesCommandCleanup runs the real per-command cleanup between executions. It fails without the fix.

Verification:

  • Unit tests pass for frontend, plan, compile, colexec, process and vector.
  • prepare BVT: 100%.
  • A Go COM_STMT differential client produces identical output to a897ce9.

@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Nov 23, 2026
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 23, 2026
…eview fixes, main) into prepared-params-typed-source
@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 5a9d1c855fc0f6963e828d6bf1ecad9aed94b437

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: 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: preparedParamValues copies 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.jsonl and checks/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.

@fengttt
fengttt requested a review from XuPeng-SH November 23, 2026 23:09
@fengttt
fengttt merged commit 98d7e9e into matrixorigin:main Nov 24, 2026
fengttt added a commit to fengttt/matrixone that referenced this pull request Nov 24, 2026
…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]>
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 was successfully deployed

No deployments
ci — 73b10bd7 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/enhancement 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