Skip to content

refactor(vector): remove prepareParamKind from Vector; carry prepared parameters as typed values (#33007) - #33011

Merged
fengttt merged 10 commits into
matrixorigin:mainfrom
fengttt:vector-prepareparam-out
Nov 20, 2026
Merged

fengttt merged 10 commits into
matrixorigin:mainfrom
fengttt:vector-prepareparam-out

Conversation

@fengttt

@fengttt fengttt commented Nov 20, 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 #33007

What this PR does / why we need it:

Vector is a data container. It should not carry prepared-statement state. Over time it had acquired a per-row "prepare param kind" tag (None/Integer/Float/Decimal/Boolean), plus a parameter SQL type and a prepared-JSON marker. These were propagated through every vector operation, the batch codec, spill files, remote dispatch and the group/window/timewin/aggregate operators.

The tag existed only because prepared parameters reached the executor as TEXT. EXECUTE already re-binds each ? to its real source type, but lowerPreparedSourceTransports turned it back into cast(text -> type). The tag then told every consumer how to undo the stringification: NaN written as "NaN", Boolean as "true", float vs. decimal rounding, and so on. This PR makes the parameter value itself typed and deletes the tag.

1. Typed prepared parameters (commit feat(prepare): ...)

  • Process: carries the parameters as a one-row typed batch (column i is parameter i) next to the TEXT transport. Detach, borrow and restore move it together with the TEXT parameters, and installing new TEXT parameters clears it.
  • Frontend, at every EXECUTE with parameters: builds typed values from the bound source types. Covered types: integers, floats (NaN/±Inf included), bool, decimals at their bound scale, BIT, date, time, datetime, timestamp and JSON. Strings, NULL and other types keep the TEXT transport.
  • ParamExpressionExecutor:
    • A typed value of the bound type is used as is.
    • A typed value of another type is cast from its own source type.
    • With no typed value, it falls back to the TEXT cast. That cast is built in the expression's own context, so folding, selected-row evaluation and diagnostics are unchanged on that path.
  • Remote CNs: typed values travel in the new PrepareParamInfo.typed_params field. A peer that ignores the field reads the TEXT transport.
  • lowerPreparedSourceTransports is removed.

2. Remove the lineage (commit refactor(vector): ...)

  • Vector:
    • Removed: the kind scalar and per-row sidecar, prepareParamType, the prepared-JSON marker, and all of their accessors, preflight, propagation, remap, checkpoint and accounting code.
    • String-source preflight and propagation used to share those code paths. They now have their own string-source-only helpers: PreflightUnion*StringSources and propagateStringSources*.
  • Batch trailer and selected-rows codec:
    • Writers no longer emit kinds.
    • Readers still accept kind data from older peers and drop it.
    • The trailer still carries binary/text string domains and string sources.
    • The batch API is renamed: MarshalBinaryWithMetadata, UnmarshalBinaryWithMetadata, HasTransportMetadata, TransportMetadataSize, ...
  • Operators:
    • Group: the trailer is now row_metadata_trailer.go, and old trailers are validated and discarded. A new GroupAggFuncExec.ResultVectorForChunk keeps the MORPC v18/v23/v37 string-metadata gates working.
    • Also cleaned: aggexec min/max/any/maxby winner kinds, window, timewin, IF/CASE/COALESCE kind merging, and the dispatch gate.
  • Functions:
    • Removed the kind branches in casts, json_*, MEMBER OF, inet_ntoa, random_bytes and between.
    • Removed the prepared JSON comparison adapters __mo_json_comparison_param and __mo_json_ordering_param; their function IDs stay reserved.
    • A typed ? now binds exactly like a literal of its type.
    • A string or untyped parameter compared with JSON binds as a JSON string (cast(json_quote(?) as json)), which is the MySQL rule.
    • A protocol BIT (no width) or a SQL array on the left of MEMBER OF is rejected when the statement is bound.
  • Process:
    • The kind/type metadata sections and the variable-kind resolver are removed.
    • Remote metadata from older peers (4N or 12N flags) is accepted and cut to the N binary flags.
  • vector.PrepareParamKind is gone. The planner and frontend binding descriptor that remains (ParamValue.PrepareParamKind, user variables) is types.StringConversionKind. It does not touch Vector, and replacing it with real SQL types is a follow-up.

The diff is about −12.5k / +3.1k lines across ~200 files. Most of the additions are typed-value tests and tests that old wire formats still decode.

Compatibility notes

  • Rolling upgrade: wire formats stay readable in both directions. New writers simply stop sending kinds.
  • Mixed-version remote plans: a plan from an older CN that contains the retired JSON adapter functions cannot run on a new CN.
  • MEMBER OF with a prepared BIT/array left operand: it is now rejected at bind time rather than per evaluated row. NULL parameters are unaffected, because they have no source type.

Testing

  • New tests:
    • typed transport in the executor;
    • process codec and lifecycle;
    • frontend typed-value parsing and installation;
    • group trailers from older writers, uniform and per-row;
    • batch and selected-rows decoding of old kind data;
    • remote 4N/12N parameter metadata.
  • Converted tests: where a test set a kind on a TEXT vector to get numeric semantics, it now feeds a typed input instead, e.g. prepared DOUBLE NaN/±Inf, Boolean to float, numeric to BIT, decimal rounding, random_bytes and pagination. Tests whose only purpose was kind propagation were deleted.
  • Unit tests: pass for pkg/container/..., pkg/vm/process/..., pkg/sql/colexec/..., pkg/sql/plan/..., pkg/sql/compile/..., pkg/frontend/... and pkg/util/executor/....
  • Static checks: golangci-lint (pinned v2.14.0) reports 0 issues on the changed packages; molint and license checks pass.
  • BVT: a full local BVT on a 2-CN cluster, compared against an upstream-main baseline, is still running. Results will be posted here.

🤖 Generated with Claude Code

…n#33007)

EXECUTE already binds each `?` to its real source type, but the value
still traveled as TEXT: lowerPreparedSourceTransports rewrote every typed
ParamRef into cast(text -> type), and per-vector prepareParamKind tags
told the casts how to undo the stringification (NaN text, Boolean text,
float rounding, ...).

This is the first step of removing that lineage from Vector:

- Process carries the parameters as a one-row typed batch (column i is
  parameter i) next to the TEXT transport. It shares the detach/borrow/
  restore ownership of the TEXT parameters and is cleared whenever new
  TEXT parameters are installed.
- At EXECUTE the frontend builds typed values from the bound source types
  (integers, floats incl. NaN/Inf, bool, decimals). Other types, strings
  and NULL keep the TEXT transport.
- ParamExpressionExecutor evaluates a non-string ParamRef from the typed
  value directly, casts it from its own source type when the types
  differ, and otherwise falls back to the TEXT cast built in the
  expression's own context (so folding, selection and diagnostics are
  unchanged on that path).
- The process codec sends typed values to remote CNs (new repeated
  bytes field). A peer that ignores the field reads the TEXT transport.
- lowerPreparedSourceTransports is removed; its tests now compare the
  TEXT and typed transports instead of logical and lowered plans.

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 added the kind/refactor Code refactor label Nov 20, 2026
@mergify

mergify Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

fengttt and others added 2 commits November 20, 2026 10:53
…origin#33007)

Prepared parameters now reach execution as typed values (previous commit),
so the per-row "prepare param kind" tag that rebuilt a parameter's type from
its TEXT transport carries no information. Remove it end to end:

- Vector: the kind scalar/sidecar, prepareParamType, the prepared JSON
  comparison marker, and every accessor, preflight, propagation, remap,
  checkpoint and accounting path for them. String-source preflight and
  propagation, which shared those code paths, keep string-source-only
  helpers (PreflightUnion*StringSources, propagateStringSources*).
- Batch transport trailer and the selected-rows codec: writers no longer
  emit kinds; readers still accept and drop kind data from older peers.
  Renamed the batch API (MarshalBinaryWithMetadata, HasTransportMetadata,
  ...). The trailer keeps carrying binary/text domains and string sources.
- Operators: group (trailer renamed row_metadata_trailer; old trailers are
  validated and discarded), aggexec min/max/any/maxby winner kinds, window,
  timewin, IF/CASE/COALESCE kind merging, dispatch.
- Functions: the kind branches in casts, json_*, MEMBER OF, inet_ntoa,
  random_bytes and between, and the prepared JSON comparison adapters
  (__mo_json_comparison_param / __mo_json_ordering_param; ids reserved).
  A typed parameter binds like a literal of its type; a string parameter
  compared with JSON binds as a JSON string (json_quote + cast).
- Process: kind/type metadata sections and the variable kind resolver.
  Remote metadata from older peers (4N/12N flags) is accepted and truncated.
- Frontend: typed values also for non-query EXECUTE (SHOW, DDL, SET), and
  BIT, date, time, datetime, timestamp and JSON typed values. A protocol
  BIT or SQL array on the left of MEMBER OF is rejected when binding.

The planner/frontend binding descriptor (types.StringConversionKind on
ParamValue and user variables) stays for now; it no longer touches Vector.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt fengttt changed the title feat(prepare): carry prepared parameters as typed values (#33007) refactor(vector): remove prepareParamKind from Vector; carry prepared parameters as typed values (#33007) Nov 20, 2026
…iteral

A string or untyped parameter compared with JSON was bound as
cast(json_quote(?) as json), so JSON true <=> 'true' returned 0 for a
prepared statement but 1 for the literal, which binds as
cast(json AS VARCHAR) <=> 'true'. Prepared parameters must behave like the
equivalent typed literal (docs/design/prepared_json_comparison.md), and
TestIssue27529JSONStringsDoNotCompareAsBooleans failed.

For =, <=>, <> and != with an untyped, CHAR, VARCHAR, TEXT or BLOB
parameter, cast the JSON operand to VARCHAR in either operand order.
Orderings and binary parameters keep the JSON-string binding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With lowerPreparedSourceTransports gone, a marker bound to a non-string
source type (e.g. BIGINT) stays typed. When parameter values are filled
into the plan, ResetParamRefRule replaced it with the TEXT transport
literal relabeled as that type: a string literal typed BIGINT. EXPLAIN
then printed '4294967296' instead of cast('4294967296' AS BIGINT), and
constant folding no longer applied ('12345' instead of 12345), failing
prepare/issue_29506, 29510, 29511 and 29512 in BVT.

Cast the TEXT literal to the marker's type instead, under the same
condition the removed lowering used (non-string, non-any targets).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt
fengttt merged commit 520ee5c into matrixorigin:main Nov 20, 2026
fengttt added a commit that referenced this pull request Nov 20, 2026
#33017)

## 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 #33004 (a step of the Vector cleanup; does not close it)

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

**Stacked on #33011.** This branch is built on
`vector-prepareparam-out`, so until #33011 merges the diff also contains
its commits. The change for this PR is the commit `refactor(vector):
remove string-source provenance from Vector (#33004)`.

`Vector` carried a per-row "string source" (Expression / Literal / User
variable / SQL PREPARE / COM_STMT) in `stringSource`, `stringSources`
and `stringSourcesMP`. Every append, union, shuffle, shrink, window,
sort, codec and operator kept it up to date.

The planner is its only semantic consumer, and it reads the source on
plan literals. The copy on the vector existed so that constant folding
could read the source back off an evaluated vector. This PR removes the
vector copy and has the planner work the source out from the expression
itself.

### Vector
- Removed the three fields and all their accessors, preflights,
propagation, remaps, normalization and copies.
- The append and union helpers lose their source and override
parameters. `UnionBatchPreflightedWithStringSources*` and
`Append*WithStringSource` are gone.

### Planner
- Constant folding derives a folded literal's source with
`rule.ExprStringSource(expr, proc)`, and `rule.ListStringSource` for IN
lists. A mixed-source list stays unfolded, as before. The rules are the
ones the executor used to apply to result vectors:
  - a literal or literal vector keeps its own source;
  - a variable is `UserVariable`;
  - a parameter has its execution's source;
  - an implicit cast (`CAST` overload 0) keeps its argument's source;
- COALESCE takes the source of its first arm that is not a NULL literal;
  - anything else is `Expression`.
- `rule.GetConstantValue(vec, transAll, row, source)` takes the source
explicitly, so every caller states it.
- Frontend `SET` evaluation derives the source from the SQL syntax tree
with the same rules.

### Process
- A parameter's source is recorded per execution with
`SetPrepareParamsStringSource` / `GetPrepareParamsStringSource`. The
frontend sets `COMStmt` (binary EXECUTE) or `SQLPrepare` (SQL EXECUTE
USING) after installing the parameters.
- The remote codec keeps its per-parameter `StringSources` field. It
writes one equal entry per parameter, and on decode it merges older
per-parameter entries into one value.

### Operators
The expression evaluator (literals, parameters, variables, implicit
casts, IF/CASE/COALESCE), aggexec (min/max/any/maxby winners, capacity
preflight, window, percentile), group, timewin, window, dispatch and
pSpool no longer stamp or propagate sources.

### Wire compatibility
New writers stop sending source data, and every reader still accepts it
from older peers, validates it and drops it:
- **Batch metadata trailer:** always written as v1, with no source
section. v2 is still read in both the buffered and the streaming/spill
decoders.
- **Selected-rows codec:** bits 6-7 of the metadata byte, the uniform
byte and the per-row trailer are no longer written.
- **Aggregate-state row trailer and retained-argument envelope:** the
source bits are no longer written.

### Behaviour notes
- COALESCE over non-literal arms (e.g. `coalesce(@v, 'x')`) takes its
source from the first arm, regardless of whether that arm is NULL at
runtime. The runtime used to decide this per row. Only the planner's
literal-source rules see the difference.
- `TestUnboundedRunSortFailureKeepsStagedData` (objectio/ioutil) was
removed. It forced a sort failure through the source sidecar's MPool
allocation, which no longer exists.

## Testing
- **Planner tests:** new `pkg/sql/plan/rule/string_source_test.go`
covers `ExprStringSource`, `ListStringSource` and the explicit source
encoding in `GetConstantValue`. The existing planner tests that assert
sources on folded literals and LiteralVecs keep their expected values
and pass.
- **Old-format decode tests:** the batch v2 trailer (buffered and
streaming), the selected-rows codec source field, the aggregate-state
trailer source bits, and remote per-parameter sources merged on decode.
- **Unit tests:** pass for `pkg/container/...`, `pkg/vm/process/...`,
`pkg/sql/colexec/...`, `pkg/sql/plan/...`, `pkg/sql/compile/...`,
`pkg/frontend/...`, keycodec, compare, `objectio/...` and
`sql/internal/...`. `go vet ./pkg/...` is clean.
- **Lint:** golangci-lint (pinned v2.14.0) reports 0 issues on the
changed packages.

🤖 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 21, 2026
… (#33024)

## 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 #33016 (subtask of #33004)

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

**Stacked on #33017 (itself on #33011).** Until those merge, the diff
also contains their commits. The change for this PR is the commit
`refactor(vector): remove binary/text string domain from Vector
(#33016)`.

`Vector` carried a per-row runtime string domain in `binaryString`,
`binaryStringRows`, `textStringRows` and `binaryStringRowsActive`. It
let a vector's rows override the binary/text semantics of its static
type. Every append, union, shrink, shuffle, sort, window, codec and
operator maintained it, and string functions branched on it per row.

This PR removes it. **The static type is now the only carrier of
binary-vs-text semantics.** `types.StaticStringDomain` reports binary
for the binary charset, and for the legacy zero charset on
BINARY/VARBINARY/BLOB.

### Vector
- Removed the four fields and every accessor, preflight, propagation,
remap, rollback and accounting path.
- Removed `SetBytesAtWithBinaryString`; callers use `SetBytesAt`.

### Functions and operators
- String functions read the static type through `isBinaryStringVector`.
There is no per-row branch, and functions no longer publish a result
domain.
- The evaluator no longer stamps a domain on literals, parameters,
variables or IF/CASE/COALESCE results.
- aggexec no longer merges equal candidates' domains
(min/max/any/maxby), and no longer restores one for window or
percentile.

### Planner
Two places where the runtime domain used to correct a text static type
are now typed correctly up front:
- **COALESCE:** with binary and CHAR/VARCHAR arms, COALESCE is typed
binary, as IF and CASE already were (MySQL).
- **Binary literals under collation normalization:** a binary literal
(hex, bit, `_binary`) is no longer converted to text in the cases where
its byte domain used to survive at runtime. Those cases are a
coercibility tie and a case-sensitive selection. For example, `'abc'
LIKE _binary 'ABC'` stays byte-wise (#31175).

### Process and frontend
- Prepared parameters no longer carry binary-string flags. A BLOB
COM_STMT parameter and a binary user variable are typed binary by their
bindings.
- The user-variable domain resolver stays on Process, because SQL
EXECUTE uses it to choose a parameter's source type.

### Wire compatibility
Writers no longer emit any of the following. Readers still accept them
from older peers, validate them and drop them:
- the batch metadata trailer ("PPB");
- the selected-rows codec's binary field and per-row binary/text flags;
- the aggregate binary-string state trailer;
- the `IsBinaryString` and `RuntimeStringDomains` prepared-parameter
fields.

Spill writers (top, fill, mergeorder) use the stable batch encoding.

### SQL-visible change
REVERSE, LENGTH and similar functions over an IF/CASE/COALESCE with a
binary arm now act on bytes for every row. Before, rows coming from the
text arm were treated as text. The result type was already binary, so
this matches MySQL. Some planner test expectations were updated for it.

## Testing
- **SQL probe script, against an isolated node built from this branch
and the main baseline:** identical results. It covers:
  - IF/CASE/COALESCE with mixed arms;
  - LIKE with a binary pattern;
  - binary user variables and SELECT INTO;
  - SQL EXECUTE with binary and text variables;
  - GROUP BY with MIN/MAX over varbinary;
  - JSON with binary keys and MEMBER OF.
- **Unit tests:** pass for `pkg/container/...`, `pkg/vm/process/...`,
`pkg/sql/colexec/...`, `pkg/sql/plan/...`, `pkg/sql/compile/...`,
`pkg/frontend/...`, `objectio/...`, `sql/internal/...`, hashmap and
compare.
- Tests that only exercised the removed sidecar were deleted: its
accounting, propagation, rollback and wire emission.
  - Behaviour tests were converted to binary static types.
- New and adapted tests check that old-writer bytes still decode, for
the batch trailer v1/v2, the selected-rows codec, the aggregate trailer
and the process codec.
- **Static checks:** `go vet ./pkg/...` is clean, including `-tags
integration` for the planner, and golangci-lint reports 0 issues.
- **Not yet done:**
  - A full BVT run is in progress. Results will be posted here.
  - A binary-protocol BLOB parameter is covered by unit tests only.

🤖 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 to fengttt/matrixone that referenced this pull request Nov 21, 2026
main now carries the squashed forms of the PRs this branch was stacked on
(matrixorigin#33011, matrixorigin#33017, matrixorigin#33024). Resolution keeps main's semantics for those and
this branch's DICTIONARY / row-selection changes: the merged tree equals
replaying this branch's own commits (d39b12c..4de8e4e) onto main.

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

## 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 #33021 (subtask of #33004)

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

**Stacked on #33024 (→ #33017 → #33011).** Until those merge, the diff
also contains their commits. This PR is the last two commits:

- `refactor(vector): remove the DICTIONARY vector class (#33021, phase
A)`
- `feat(batch): batch-level row selection for the filter chain (#33021,
phase B)`

### Phase A: remove the DICTIONARY vector class

DICTIONARY was a lazy row-selection view. A dictionary vector's rows
indexed an immutable, reference-counted base vector. Supporting it took:

- read views;
- freeze/reclaim workspace leases installed into ordinary source
vectors;
- selection scopes and scan publication slots;
- a dictionary fast path or normalization edge in every consumer.

All of it is removed:

- **vector:**
- Removed: the dictionary files (views, bases, row selections,
freeze/reclaim, scopes, workspaces, read views), the dictionary
function-parameter wrappers,
`IsDictionary`/`EnsureFlat`/`EnsureWritable`, and every dictionary
branch.
  - Kept:
- Class 2 stays as a retired wire value (`LegacyRowBufferClass`) and
still decodes as FLAT.
- `RetainBorrowedBufferInto` (cache-borrowed scan vectors) stays,
without the dictionary payload wrapper.
- **vm:** the DictionaryProducer/Consumer edge negotiation.
- **colexec:** the dictionary filter path, the dictionary input frame,
and the evaluator's dictionary normalization.
- **functions, hashmap/keycodec, aggexec:** the dictionary fast paths
and the per-overload dictionary capability.
- **operators:** filter, projection, table_scan, shuffle, hashjoin,
hashbuild and group lose their dictionary code. Each uses the flat path
it already used when dictionary output was not admitted.
- **engine/blockio:** selected publication gathers rows in place. The
membership stage evaluates staged predicates on flat, account-charged
copies of the member rows.

### Phase B: row selection on Batch (filter chain)

A Batch may carry a row selection shared by all its columns. The vectors
keep their physical rows, logical row `i` is physical row
`Selection()[i]`, and `RowCount()` is the selected count.

- **batch:**
`SetSelection`/`ClearSelection`/`Selection`/`PhysicalRowCount`,
`PhysicalView` (an unselected header for evaluating on physical rows),
`SelectionMask` and `CompactInto`.
  - Marshal refuses a selected batch.
  - `SetRowCount`/`Clean`/`CleanOnlyData` drop the selection.
- **vm:** `SelectionConsumer`/`SelectionProducer` edge negotiation,
configured in `Prepare` and for individually prepared kernels.
Undeclared edges, the pipeline root, codecs and remote boundaries get
compacted rows.
- **filter:**
- Evaluates each predicate on the input's physical rows, masked to the
current survivors. Filtered-out rows are not evaluated, as before.
- When the parent accepts it, publishes the input's vectors with the
selection; otherwise compacts.
  - Accepts a selected input.
- **projection:** accepts a selected input and evaluates its expressions
masked to the selection. Column references pass through without a copy.
It either keeps the selection or compacts only the projected columns.

A selected output borrows the input's vectors and the producer's row
list, so it is valid until the producer's next `Call`, like any operator
output. No reference counting is needed.

### Behaviour and performance
- **Results:** unchanged.
- **Accounting:** Projection no longer charges its outputs to the
statement allocation account; that existed only for dictionary handling.
- **Still copying until follow-ups:**
- Shuffle partitions and hashjoin probe forwarding now copy where
dictionary views avoided it.
  - The hash key paths (join/build/group) compact at their input.
  - The reader-side BETWEEN selection fast path is gone.
- **Follow-ups:** move shuffle and the hash key paths onto the batch
selection.

## Testing
- **Unit tests:** pass for `pkg/container/...`, `pkg/vm/...`,
`pkg/sql/colexec/...`, `pkg/sql/plan/...`, `pkg/sql/compile/...`,
`pkg/frontend/...`, `pkg/objectio/...`, `pkg/common/hashmap/...`,
`pkg/sql/internal/...` and `pkg/compare/...`.
- **Static checks:** `go vet ./pkg/...` is clean. golangci-lint reports
0 issues on every package touched by the diff.
- **New tests:**
  - batch selection API, including the marshal guard and compaction;
- filter selected output matches its compacted output on the existing
cases;
  - filter with a selected input, in both output modes;
  - edge configuration via `vm.Prepare`/`ConfigureSelectionEdges`;
- projection with a selected input: computed expressions, column
pass-through, and compaction.
- **Regressions found and fixed on the way:**
  - `Vector.Copy` had lost its data copy.
- The blockio membership stage would have permanently bypassed
local-domain pruning.
- **BVT:** a full run is in progress; results will be posted here.

🤖 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 to fengttt/matrixone that referenced this pull request Nov 21, 2026
The squash merges of matrixorigin#33011, matrixorigin#33017 and matrixorigin#33024 included commits made on
those PR branches after this branch forked from them. Their production
changes merged in from upstream, but resolving three conflicted plan tests
to this branch's side dropped their test updates (28b2c6c, 113d208).
Also fix the saved-result zonemap test for the per-operator output pool:
the accounted account fits the first column but not the second, and the
batch is freed with the output pool.

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

## What type of PR is this?

- [x] Code Refactoring
- [x] BUG

## Which issue(s) this PR fixes:

issue #33019

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

A `Vector` now has exactly one owner pool, and nothing else about
memory. `offHeap`, `cantFreeData` and `cantFreeArea` are gone, replaced
by one `mp *mpool.MPool` set when the vector is created.

**Stacked on #33034 and #33033.** Review commit `90b459f68c` (the
change), the merge commit `d6fc6630fc` (upstream sync) and the
follow-ups `95155a83ad`, `83a5ef6377`, `af929a9ece`, `3aa882ce19`,
`a6e0d0e4e3`, `24c5d57fbb`, `4773ebe65d` and `53b867de02`. Everything
below `90b459f68c` belongs to the earlier PRs.

### The memory model

The model is written down in `docs/ai-skills/sql-engine.md` ("Vector
内存管理模型"):

- **One pool per vector.** Every vector comes from a pool and is freed
with it. All vector memory is off-heap, so a vector that is never freed
is a leak.
- **Strict pool check.** A call that passes `mp` must pass exactly the
vector's own pool. A view of the same pool doesn't count. A mismatch is
an error, and a panic in `Free`.
- **Read-only vectors.** A nil pool means a read-only reference to
memory the vector does not own, such as FileService cache entries or
Arrow buffers. Allocating into it or mutating it fails. `Free` only
drops its references.
- **Operator pools.** Operators that buffer a lot of data own a pool
from `colexec.NewOperatorMPool`: order, top, mergetop, group, window and
hash build, plus the table scan. Other operators use `proc.Mp()`.
- **Batch lifetime.** A batch is valid until the next `Next`. Moving an
input vector into the output is fine. Modifying an input vector is not:
the operator must write into a vector it owns.
- **No new `Vector` fields** without human review.

### Main changes

- **Window and decode.**
- `Window` returns a read-only reference; `CloneWindow`/`CloneWindowTo`
copy.
- Decoding into a vector that has a pool copies into that pool; decoding
into a read-only vector keeps references.
- A read-only vector's null bitmap is always private, so writes through
`GetNulls()` can never reach cache memory.
- **Table scan.** The scan owns its output pool, so later operators
cannot modify scanned rows.
- **Transaction workspace.** It copies caller batches into its own pool
and never takes them over. Each caller frees its own batch.
- **Read-only checks.** In-place setters (`SetFixedAt*`, `SetNull`,
`UnsetNull`) reject read-only vectors.
- **Freeing.** Decode receivers that belong to another pool are
rejected. tae `Vectors.Free` is strict. Most `vec.Free(vec.MPool())`
call sites now free with the owner's pool; a few holders of several
pools still free each vector with its own pool. `batch.CleanOwned` is
only for tests.

- **Filtered scans publish a batch selection.** When the scan's parent
reads selected batches (filter, projection), a filtered block without
deletes keeps every column as a read-only reference to the cache, pinned
by the output batch until the next `Next`, and the kept rows become the
batch selection (#33021). Otherwise the reader still compacts while its
cache entries are pinned: publishing and compacting later made SF100
TPC-H, whose scans all feed joins or aggregations, about 10% slower.
- **Faster selection conversions.** Bitmap to row list, bitmap to bool
mask and row list to bitmap now work a word at a time, size their output
once and reuse storage; `CompactInto` takes a reusable row list. Per
8192-row block: rows 11.4 → 1.8 µs at 50% and 21.7 → 2.8 µs at 100%;
mask 11.7 → 4.5 µs and 22.5 → 1.8 µs.

### Bugs fixed along the way

- **INSERT/LOAD IGNORE.** The NOT NULL fill wrote implicit defaults into
the child's vectors in place. For a scan's read-only vectors that meant
cache memory. A NULL varchar into a NOT NULL column also failed the pool
check.
- Now `colexec.IgnoreFill` adjusts a copy it owns, one reusable vector
per column. PreInsert, the external insert and multi_update use it.
- multi_update's main-table leg publishes the adjusted batch to the
index legs, so index rows see the same values.
- **Lock op.** Refresh timestamps were appended to the child's vector.
Lock op now fills its own vector and publishes it through a view.
- **Arrow external reader.** It swapped its vectors into the operator's
batch, so two owners shared one batch. Now the reader owns the batch it
publishes (`BatchPublisher`).
- **C null-map over-read.**
- A null bitmap ends at its highest null, but the docfilter and
cbloomfilter C kernels test every row's bit, so they read past it.
- Before this change, read-only decodes shared the bitmap with the
encoded buffer, which hid the over-read.
  - Fix: callers now pass `Bitmap.WordsCovering(n)`.
- **SET descriptor cache.** It kept zero-copy strings over vector
memory, which are now reused off-heap memory. It now clones them first.
- **Low-precision float sort.** Sort-and-compact for BF16 and the other
low-precision floats appended without a pool.
- **Sort rollup.** It unioned aggregate results through the wrong pool.
- **HNSW sync writer.** The ISCP writer kept zero-copy views of
change-batch vectors in its CDC buffer across batches. After a copy
ALTER or TRUNCATE, an int8/uint8 index trained its range from freed
memory and returned wrong neighbours. It now copies the vectors
(`af929a9ece`).
- **`fault_inject`.** It handed zero-copy argument strings to the local
CN's fault map, so the CN running the statement stored a garbage point
name and every fault-injection BVT case on that CN failed. It now copies
them (`3aa882ce19`).
- **Collation test.** The cherry-picked `95155a83ad` carried a copy of
`collation_metadata_test.go` older than `main`'s that did not compile;
`a6e0d0e4e3` takes `main`'s file and adapts it.
- **Pool mismatches.** hashbuild runtime-filter runs and `Expr_Vec`
literals were freed through the wrong pool.

### Behavior changes

- **Copying.** Scan rows read from objects with deletes or selections
are copied into the scan's pool. Raw workspace input is copied and
charged to the workspace account.
- **No spill recovery class.** The buffered data of Order, Top and Group
no longer switches to the recovery capacity class.
- **Removed tests.** Tests of the old borrow/copy-on-write contract are
removed.

### Tests

- `go build ./...` and `go vet ./pkg/... ./cmd/...` are clean.
- **Unit tests on the merged tree:**
- 412 packages pass; the four packages that failed only because of the
merge were fixed in `83a5ef6377` and now pass.
- The squash merges of #33011, #33017 and #33024 included commits pushed
to those PR branches after this branch forked from them. Their
production changes came in through the merge. Three plan tests had been
resolved to this branch's side, so `83a5ef6377` restores their updates.
`95155a83ad` is one of those commits, cherry-picked.
- `tests/service` `TestTaskSchedulerExpiresLostRunnerWithoutReplay` is
flaky: 2 of 4 runs fail on plain upstream `main` too.
- `tests/txn` `TestWriteSkewIsAllowed` failed in the full run and passes
when run alone.
- `util/metric/mometric` fails while a local cluster holds port 7001.
`util/metric/v2/dashboard` needs Grafana.
- **BVT on a two-CN `make dev-up` cluster built from this branch:**
- `load_data` passes 99%; the only failures are `into outfile`
permission errors from the environment.
- `dml` passes 98%; the failures need `AUTO_ID_CACHE`, a CDC loopback to
6001, or ETL data.
- The full run found the sort-rollup, HNSW and `fault_inject` bugs
above, all fixed. The fault-injection and clone cases were compared
against an upstream `main` image on the same cluster and now pass.
- The remaining failures also fail on the `main` image or need what the
dev cluster lacks: `AUTO_ID_CACHE`, statement tracing (`disableTrace =
true`), `into outfile` permissions, external servers. Optimistic cases
are excluded, as in CI.
- **Manual INSERT IGNORE check.** `INSERT IGNORE ... SELECT` from a
flushed table turns NULLs into implicit defaults, with one warning per
cell. The source still reads its NULLs with a cold and a warm cache.

🤖 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 23, 2026
…ecution (#33076) (#33081)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] 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
- **Separate PR:** pointer storage for the planner's `paramVals`
(`[]any` of `plan.ParamValue`), so building them no longer boxes each
value per execution.
- **#33082:** redesign so the planner reads the typed parameter batch
and the `ParamValue` string-conversion machinery goes away.

## 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](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 previously deployed

1 inactive deployment
ci — 23310b07 Deployed Nov 20, 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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants