Skip to content

refactor(vector): remove string-source provenance from Vector (#33004) - #33017

Merged
fengttt merged 15 commits into
matrixorigin:mainfrom
fengttt:vector-stringsource-out
Nov 20, 2026
Merged

fengttt merged 15 commits into
matrixorigin:mainfrom
fengttt:vector-stringsource-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 #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

fengttt and others added 8 commits November 20, 2026 10:04
…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]>
…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]>
…-out

# Conflicts:
#	pkg/container/vector/vector.go
…origin#33004)

Vector carried a per-row "string source" (Expression / Literal / User
variable / SQL PREPARE / COM_STMT) in stringSource, stringSources and
stringSourcesMP, maintained by every append, union, shuffle, shrink,
window, sort, codec and operator. Its only semantic consumer is the
planner, which reads the source on plan literals; the vector copy existed
so that constant folding could read it back off the evaluated vector.

- Vector: remove the three fields and every accessor, preflight,
  propagation, remap, normalize and copy path. Union/append helpers lose
  their source and override parameters.
- Planner: constant folding derives a folded literal's source from the
  plan expression (rule.ExprStringSource / ListStringSource), with the
  rules the executor used to apply: a literal keeps its source, a variable
  is a user variable, a parameter has its execution's source, an implicit
  cast keeps its argument's, COALESCE takes its first non-NULL-literal arm,
  anything else is an expression. GetConstantValue takes the source
  explicitly. Frontend SET evaluation derives it from the syntax tree.
- Process: a parameter's source is per execution
  (SetPrepareParamsStringSource); the remote codec keeps its per-parameter
  wire field.
- Executors and operators (expression evaluator, aggexec, group, timewin,
  window, dispatch, pSpool) no longer stamp or propagate sources.
- Wire compatibility: the batch trailer is written as v1 (no source
  section), the selected-rows codec and the aggregate-state trailer no
  longer write source bits; all readers still accept, validate and drop
  source data from older writers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	pkg/objectio/ioutil/sinker_bounded_lifecycle_test.go
@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 20, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

fengttt and others added 2 commits November 20, 2026 11:40
checkunsafe forbids importing unsafe in collation_metadata_test.go. Find
CollationVersion's byte in the encoded type by flipping only that field
on a probe and diffing the two encodings instead of unsafe.Offsetof.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt and others added 2 commits November 20, 2026 12:31
…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]>
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/XXL Denotes a PR that changes 2000+ lines labels Nov 20, 2026
@fengttt
fengttt merged commit b9210f6 into matrixorigin:main Nov 20, 2026
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>

This branch was previously deployed

1 inactive deployment
ci — 92690c9b 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