Skip to content

refactor(vector): remove binary/text string domain from Vector (#33016) - #33024

Merged
fengttt merged 25 commits into
matrixorigin:mainfrom
fengttt:vector-binarystring-out
Nov 21, 2026
Merged

fengttt merged 25 commits into
matrixorigin:mainfrom
fengttt:vector-binarystring-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 #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 ([Bug]: LIKE and REGEXP ignore effective collation on literals and columns #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

fengttt and others added 14 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
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]>
…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]>
…xorigin#33016)

Vector carried a per-row runtime string domain (binaryString,
binaryStringRows, textStringRows, binaryStringRowsActive) that let a
vector's rows override its static type's binary/text semantics. Every
append, union, shrink, shuffle, sort, window, codec and operator
maintained it, and functions consulted it per row.

The static type is now the only carrier of binary-vs-text semantics
(types.StaticStringDomain: binary charset, or the legacy zero charset on
BINARY/VARBINARY/BLOB).

- Vector: remove the four fields and every accessor, preflight,
  propagation, remap, rollback and accounting path.
- Functions: read the static type (isBinaryStringVector); no per-row
  branch and no result-domain publication.
- Evaluator: literals, parameters, variables and IF/CASE/COALESCE no
  longer stamp a domain. aggexec no longer merges or restores one.
- Planner: COALESCE over binary and CHAR/VARCHAR arms is typed binary,
  as IF and CASE already were (MySQL). Collation normalization leaves a
  binary literal (hex, bit, _binary) unconverted where its byte domain
  used to survive at runtime (a tie, or a case-sensitive selection).
- Process/frontend: prepared parameters carry no binary-string flags;
  BLOB COM_STMT parameters and binary user variables are typed binary by
  their bindings. The user-variable domain resolver stays on Process for
  SQL EXECUTE's source typing.
- Wire compatibility: writers no longer emit the batch metadata trailer,
  the selected-rows codec binary field and per-row flags, the aggregate
  binary-string state trailer, or the prepared-parameter IsBinaryString /
  RuntimeStringDomains fields. Readers still accept, validate and drop
  them from older peers. Spill writers use the stable batch encoding.

SQL-visible: REVERSE/LENGTH-style functions over an IF/CASE/COALESCE
with a binary arm now act on bytes for every row, matching MySQL.

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.

… expressions

binary_string_function_semantics.test compares result-set metadata
(@metacmp). Earlier commits on this branch type COALESCE over character and
byte strings as binary, and relabel a COERCIBLE binary literal branch to the
winning text type. Both change the declared type and width of HEX/LEFT/
REVERSE results over those expressions: e.g. hex(coalesce(txt, bin)) is now
varchar(128) instead of text, and hex(left(if(txt is not null, txt,
_binary ''), 1)) narrows to varchar(8). The re-recorded values were already
correct; only the column metadata headers were stale.

Regenerated with mo-tester against a build of this branch; only metadata
header lines change.

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

XuPeng-SH commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 43efffc526929faff017f85710f2dd3bbde395d5

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: 43efffc526929faff017f85710f2dd3bbde395d5

Assessment: request_changes

Removing per-row string metadata simplifies vector operations and transport. The replacement planner rewrite applies the selected-value charset inconsistently. SQL checks reproduced incorrect stored generated values and incorrect character counts in several query paths.

Model: gpt-6.2-sol / xhigh

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

  • P2 pkg/sql/plan/base_binder.go:4599: Store a generated column defined as CHAR_LENGTH(COALESCE(txt, bin)) and insert a row whose selected text value is '你a'.
    Impact: The generated column persists 4 while the same expression in a SELECT returns 2 for that row.
    Evidence: The generated-column binder has no QueryBuilder, so the flag that activates the rewrite is never set. INSERT copies the catalog expression without rebinding the conditional at pkg/sql/plan/bind_insert.go:6080. The generated-column check in recovered-validation.log confirmed the mismatch. Apply the same expression semantics when binding catalog expressions.

  • P2 pkg/sql/plan/query_builder.go:4504: Use CHAR_LENGTH(COALESCE(txt, bin)) as a window aggregate input or project it alongside a dependent scalar subquery.
    Impact: With the same input rows, SUM over the window returns 12 instead of 8. Adding the dependent subquery changes the projected length of '你a' from 2 to 4.
    Evidence: The dependent-query return at line 4450 bypasses the rewrite. The rewrite's expression list at pkg/sql/plan/coalesce_text_domain.go:507 omits WinSpecList, which the window compiler reads directly. Both failures and the plain projection control appear in recovered-validation.log. Apply the rewrite on both query routes and reuse the existing window expression traversal.

  • P2 pkg/sql/plan/coalesce_text_domain.go:209: Evaluate CHAR_LENGTH(COALESCE(txt, CAST(UUID() AS VARBINARY))) on a row where txt is non-NULL and contains '你a'.
    Impact: Adding an unselected fallback changes the result from 2 characters to 4 bytes.
    Evidence: The volatile-function guard skips the entire rewrite even when COALESCE selects the first argument. The SQL check in recovered-validation.log returned 4. Preserve the selected argument's charset while keeping each argument lazy and avoiding duplicate evaluation.

  • P2 pkg/sql/plan/coalesce_text_domain.go:378: Apply CHAR_LENGTH to a scalar subquery returning COALESCE(COALESCE(txt, bin), bin), where the inner COALESCE selects '你a'.
    Impact: The scalar subquery form returns 4. The direct nested expression and the scalar subquery with a single COALESCE both return 2.
    Evidence: The mixed-domain recognizer accepts a nested COALESCE as a source of text, but textOnlyCoalesce substitutes NULL for that same arm because its static type is binary. All three cases ran in recovered-validation.log. Preserve the selected text arm recursively when constructing the scalar projection.

  • P3 pkg/sql/plan/coalesce_text_domain.go:44: Call LENGTHUTF8 and CHAR_LENGTH on the same mixed COALESCE value.
    Impact: The aliases return 4 and 2 respectively on the same text row.
    Evidence: Both names resolve to LENGTH_UTF8 at pkg/sql/plan/function/function_id.go:1218. The rewrite matches SQL names and omits LENGTHUTF8. The alias check in alias-comparison-check.log confirmed the discrepancy. Classify the consumer by its bound function identity.

  • P3 pkg/sql/plan/base_binder.go:4789: Bind a CASE or COALESCE with many arguments, including one with only numeric arguments.
    Impact: Binding performs quadratic index construction and allocation before checking whether any argument is a binary literal.
    Evidence: The per-argument loop rebuilds the full conditional value-index slice through pkg/sql/plan/collation_expression.go:684. Test whether the current argument is a value slot directly so this check stays linear in the argument count.

Validation:

  • Verified the assigned head, merge base, clean source, whitespace, and frozen patch against source-check.log and patch-check.log. Receipts are checks/1795239428960737904-2.json and checks/1795239613538946749-2.json.

  • Focused batch, vector, process, aggregate, collation, and planner tests passed after dependency recovery. See recovered-codec-tests.log and recovered-focused-tests.log with receipts checks/1795239752527543428-2.json and checks/1795239825889703968-2.json.

  • The existing TestConditionalStringDomain passed. Additional tests through the embedded MySQL endpoint reproduced the reported SQL mismatches. See recovered-validation.log and alias-comparison-check.log with receipts checks/1795239879219758597-2.json and checks/1795239887017178587-2.json.

  • The frozen CI snapshot records successful x86 unit tests, arm64 static checks, and two multi-CN BVT jobs.

Limitations:

  • Local SQL probes covered the candidate head through an embedded deployment. Upgrade jobs were skipped in the frozen CI snapshot.

  • The planner allocation finding is based on source analysis. Planning time was unmeasured.

@iamlinjunhong iamlinjunhong 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.

Reviewed 43efffc526929faff017f85710f2dd3bbde395d5 against a5140aa85f63573f20ab3f20c69d3dfc783ad042. The planner replacement for per-row string domains changes SQL results on the paths below, including values written to stored generated columns.

  • [P1] Preserve character counts in stored generated columns. pkg/sql/plan/base_binder.go:4599. A table with txt VARCHAR(16), bin VARBINARY(16) and n INT GENERATED ALWAYS AS (CHAR_LENGTH(COALESCE(txt, bin))) STORED stores 4 in n for an inserted ('你a', NULL), while the same expression in a plain SELECT returns 2. NewGeneratedColBinder has no query builder to activate the rewrite. INSERT copies the catalog expression at pkg/sql/plan/bind_insert.go:6080, so it executes binary COALESCE without the selected text semantics.

  • [P1] Apply the rewrite to window expressions and dependent queries. pkg/sql/plan/query_builder.go:4504. For rows ('你a', NULL), (NULL, X'e4bda061'), and ('你a', X'e4bda061'), SUM(CHAR_LENGTH(COALESCE(txt, bin))) OVER () returns 12 instead of 8. The rewrite omits WinSpecList, which the window compiler reads directly. createQuery also returns through createDependentQuery before reaching this call, so adding a dependent scalar subquery as a sibling projection can change the plain character count from 2 to 4.

  • [P1] Preserve the selected arm's domain when a fallback is volatile. pkg/sql/plan/coalesce_text_domain.go:209. With txt = '你a', CHAR_LENGTH(COALESCE(txt, CAST(UUID() AS VARBINARY))) returns 4 instead of 2. The volatile-function guard skips the whole rewrite even for rows that select txt and never need the UUID. Preserve the selected value's domain without evaluating the fallback or evaluating a selected argument twice.

  • [P1] Retain nested text values through scalar projections. pkg/sql/plan/coalesce_text_domain.go:378. For a row with txt = '你a', CHAR_LENGTH((SELECT COALESCE(COALESCE(txt, bin), bin) FROM sd WHERE id = 1 LIMIT 1)) returns 4, while the direct nested expression and the scalar form with a single COALESCE return 2. carriesTextValue recognizes the inner COALESCE as a text source, but textOnlyCoalesce replaces that selected arm with NULL because its static type is binary. The outer consumer then takes the binary branch.

  • [P1] Limit the substitution to the operand that forwards the selected value. pkg/sql/plan/coalesce_text_domain.go:409. For txt = '你a' and bin VARBINARY(16), LEFT(COALESCE(txt, bin), LOCATE('a', COALESCE(txt, bin)) - 1) should keep the byte-wise LOCATE result of 4, so LEFT receives a length of 3 and returns 你a. The substitution walks every argument and also rebinds the identical COALESCE inside LOCATE to txt. That changes the position to 2, makes the requested length 1, and returns 你. The exact-head SQL fixture independently specifies byte-wise LOCATE over this mixed COALESCE.

  • [P1] Rewrite all aliases of the character-length function. pkg/sql/plan/coalesce_text_domain.go:44. LENGTHUTF8(COALESCE(txt, bin)) returns 4 while CHAR_LENGTH(COALESCE(txt, bin)) returns 2 on the same row with txt = '你a' and bin VARBINARY(16). Both aliases bind to LENGTH_UTF8, but the rewrite switches on the SQL name and omits lengthutf8. Use the bound function ID so these aliases retain identical behavior.

  • [P3] Keep conditional binding linear in the number of arguments. pkg/sql/plan/base_binder.go:4789. Binding an N-argument COALESCE builds the entire N-entry value-index slice once per argument, even for an all-numeric expression. This adds quadratic work and allocation before the literal check. Use the current argument index to check whether it is a value slot.

The earlier exact-head review reported SQL probe results for the generated column, window and dependent queries, volatile fallback, nested scalar projection, and alias. I rechecked those paths and the remaining findings in the source. The captured discussion contains no author response to that review. I did not rerun tests locally because the exact-head evidence and source trace were sufficient for the decision.

The captured CI run and associated checks record 14 successful, 14 skipped, and 2 neutral checks out of 30. The skipped checks include upgrade compatibility jobs.


func (b *baseBinder) bindFuncExprImplByAstExpr(name string, astArgs []tree.Expr, depth int32) (*plan.Expr, error) {
expr, err := b.bindFuncExprImplByAstExprInner(name, astArgs, depth)
if err == nil && name == "coalesce" && b.builder != nil && isMixedDomainCoalesce(expr) {

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.

[P1] Preserve character counts in stored generated columns. A table with txt VARCHAR(16), bin VARBINARY(16) and n INT GENERATED ALWAYS AS (CHAR_LENGTH(COALESCE(txt, bin))) STORED stores 4 in n for an inserted ('你a', NULL), while the same expression in a plain SELECT returns 2. NewGeneratedColBinder has no query builder to activate the rewrite. INSERT copies the catalog expression at pkg/sql/plan/bind_insert.go:6080, so it executes binary COALESCE without the selected text semantics.

builder.countColRefs(rootID, colRefCnt)
builder.removeSimpleProjections(rootID, plan.Node_UNKNOWN, false, colRefCnt)
builder.removeUnobservedCountSorts(rootID)
if err = builder.distributeTextDomainInQuery(); err != nil {

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.

[P1] Apply the rewrite to window expressions and dependent queries. For rows ('你a', NULL), (NULL, X'e4bda061'), and ('你a', X'e4bda061'), SUM(CHAR_LENGTH(COALESCE(txt, bin))) OVER () returns 12 instead of 8. The rewrite omits WinSpecList, which the window compiler reads directly. createQuery also returns through createDependentQuery before reaching this call, so adding a dependent scalar subquery as a sibling projection can change the plain character count from 2 to 4.

}
if textDomainConsumers[funcName(expr)] && len(expr.GetF().Args) > 0 {
if target := reachMixedDomainCoalesce(expr.GetF().Args[0]); target != nil {
if !containsVolatileFunction(target) {

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.

[P1] Preserve the selected arm's domain when a fallback is volatile. With txt = '你a', CHAR_LENGTH(COALESCE(txt, CAST(UUID() AS VARBINARY))) returns 4 instead of 2. The volatile-function guard skips the whole rewrite even for rows that select txt and never need the UUID. Preserve the selected value's domain without evaluating the fallback or evaluating a selected argument twice.

caseArgs := make([]*Expr, 0, 2*len(args)-1)
for i, arg := range args {
value := implicitStringSource(arg)
if isStaticTextString(value) {

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.

[P1] Retain nested text values through scalar projections. For a row with txt = '你a', CHAR_LENGTH((SELECT COALESCE(COALESCE(txt, bin), bin) FROM sd WHERE id = 1 LIMIT 1)) returns 4, while the direct nested expression and the scalar form with a single COALESCE return 2. carriesTextValue recognizes the inner COALESCE as a text source, but textOnlyCoalesce replaces that selected arm with NULL because its static type is binary. The outer consumer then takes the binary branch.

changed := false
args := make([]*Expr, len(fn.Args))
for i, arg := range fn.Args {
rewritten, err := substituteAndRebind(ctx, arg, target, value)

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.

[P1] Limit the substitution to the operand that forwards the selected value. For txt = '你a' and bin VARBINARY(16), LEFT(COALESCE(txt, bin), LOCATE('a', COALESCE(txt, bin)) - 1) should keep the byte-wise LOCATE result of 4, so LEFT receives a length of 3 and returns 你a. The substitution walks every argument and also rebinds the identical COALESCE inside LOCATE to txt. That changes the position to 2, makes the requested length 1, and returns 你. The exact-head SQL fixture independently specifies byte-wise LOCATE over this mixed COALESCE.


// textDomainConsumers see the text charset of a value.
var textDomainConsumers = map[string]bool{
"char_length": true, "character_length": true,

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.

[P1] Rewrite all aliases of the character-length function. LENGTHUTF8(COALESCE(txt, bin)) returns 4 while CHAR_LENGTH(COALESCE(txt, bin)) returns 2 on the same row with txt = '你a' and bin VARBINARY(16). Both aliases bind to LENGTH_UTF8, but the rewrite switches on the SQL name and omits lengthutf8. Use the bound function ID so these aliases retain identical behavior.

b.suppressDefaultValueBindType = true
b.inetNtoaNumericLiteralContext = true
}
if conditionalValueIndexes(name, len(astArgs)) != nil && isBinaryLiteralAst(arg) {

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.

[P3] Keep conditional binding linear in the number of arguments. Binding an N-argument COALESCE builds the entire N-entry value-index slice once per argument, even for an all-numeric expression. This adds quadratic work and allocation before the literal check. Use the current argument index to check whether it is a value slot.

@XuPeng-SH

XuPeng-SH commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 43efffc526929faff017f85710f2dd3bbde395d5

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: 43efffc526929faff017f85710f2dd3bbde395d5

Assessment: request_changes

The six findings from review 6003259268 remain open. The later review adds a distinct correctness finding: the planner can rewrite a separate COALESCE inside a consumer’s length argument and change its byte-oriented semantics. Removing per-row string metadata simplifies vector operations and transport, but the replacement rewrite still changes SQL results across several binding and execution paths.

Model: gpt-6.2-sol / xhigh

Session: 01a1ee80-0d82-7030-a965-b51f496c3054 · slot 2 · generation 1

  • P2 pkg/sql/plan/coalesce_text_domain.go:409: Evaluate LEFT(COALESCE(txt, bin), LOCATE('a', COALESCE(txt, bin)) - 1) when txt is '你a' and bin is VARBINARY.
    Impact: The rewrite changes LOCATE from byte position 4 to character position 2. LEFT then takes one character and yields '你' instead of '你a'.
    Evidence: Discovery follows LEFT’s value operand, but substitution searches every argument for a structurally equal expression and rebinds the separate occurrence inside LOCATE. The exact-head SQL fixture at pkg/tests/issues/conditional_string_domain_test.go:76 specifies byte position 4 for that lookup. Restrict substitution to the operand path that forwards the selected value.

  • P2 pkg/sql/plan/base_binder.go:4599: Insert a row with txt = '你a' into a table with a stored generated column defined as CHAR_LENGTH(COALESCE(txt, bin)).
    Impact: The generated column stores 4 while direct evaluation on the same row returns 2.
    Evidence: The generated-column binder has no QueryBuilder to activate the rewrite. INSERT copies the catalog expression at pkg/sql/plan/bind_insert.go:6080. The prior exact-head SQL probe confirmed the mismatch. Apply the same selected-value semantics when binding catalog expressions.

  • P2 pkg/sql/plan/query_builder.go:4504: Use CHAR_LENGTH(COALESCE(txt, bin)) as a window aggregate input or project it beside a dependent scalar subquery.
    Impact: The tested window sum is 12 instead of 8. Adding a dependent scalar projection changes the length of '你a' from 2 to 4.
    Evidence: The dependent-query return at line 4451 bypasses the rewrite, and the expression walker omits WinSpecList. Both cases failed in the prior exact-head SQL probe. Apply the rule on both query routes and reuse the existing window expression traversal.

  • P2 pkg/sql/plan/coalesce_text_domain.go:209: Evaluate CHAR_LENGTH(COALESCE(txt, CAST(UUID() AS VARBINARY))) when txt is '你a'.
    Impact: Adding an unused fallback changes the result from 2 characters to 4 bytes.
    Evidence: The volatile-function guard skips the entire rewrite. The prior SQL probe confirmed the byte count. Preserve the selected value’s domain without evaluating unused arms or evaluating the selected argument twice.

  • P2 pkg/sql/plan/coalesce_text_domain.go:378: Apply CHAR_LENGTH to a scalar subquery returning COALESCE(COALESCE(txt, bin), bin) when the inner expression selects '你a'.
    Impact: The scalar subquery form returns 4. Both the direct nested expression and the scalar form with a single COALESCE return 2.
    Evidence: The recognizer accepts the inner COALESCE as a possible text source, but textOnlyCoalesce replaces that arm with NULL because its static type is binary. The prior SQL probe confirmed the discrepancy. Preserve nested selected text when constructing the scalar projection.

  • P3 pkg/sql/plan/coalesce_text_domain.go:44: Call LENGTHUTF8 and CHAR_LENGTH on the same mixed COALESCE that selects '你a'.
    Impact: The aliases return 4 and 2 respectively.
    Evidence: Both names resolve to LENGTH_UTF8, but the rewrite matches SQL names and omits LENGTHUTF8. The prior alias SQL probe confirmed the discrepancy. Match the bound function identity.

  • P3 pkg/sql/plan/base_binder.go:4789: Bind a CASE or COALESCE with many arguments, including an all-numeric expression.
    Impact: The binder adds quadratic index construction and allocation before the binary-literal check.
    Evidence: The per-argument loop rebuilds the full value-index slice through pkg/sql/plan/collation_expression.go:684. Check the current argument’s role directly to keep the work linear.

Validation:

  • Verified the frozen head, merge base, full patch, pinned policy, clean source and all 13 discussion entries. Receipt checks/1795242923386642464-2.json exited 0. Output is retained in review-evidence.log.

  • Reconciled six receipts and logs from the authenticated exact-head review in validation-reconciliation.json. The focused codec, process, aggregate and planner tests passed. The embedded SQL probes reproduced the earlier findings and passed their unaffected controls.

  • Traced the newly reported substitution through LEFT and LOCATE using the candidate source and its SQL fixture. The frozen CI snapshot records successful x86 unit tests, arm64 static analysis and two multi-CN BVT jobs.

Limitations:

  • The new LEFT and LOCATE composition was verified by source analysis. Its exact SQL expression was not rerun in this follow-up.

  • The binder allocation finding is source-based. Planning latency was unmeasured, and the frozen CI upgrade jobs were skipped.

@fengttt
fengttt merged commit dcbb839 into matrixorigin:main Nov 21, 2026
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 22, 2026
…from Vector (#33018) (#33033)

## What type of PR is this?

- [x] Code Refactoring

## Which issue(s) this PR fixes:

issue #33018

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

Removes `allocationAccount`, `areaDisjoint`, `dataLease` and `areaLease`
from `Vector`, so a Vector is a plain container again.

**Stacked on #33027 (and #33024).** Review only the last four commits:
`02c0ca4abc..1cc5610`.

1. **`areaDisjoint` is computed, not tracked** (02c0ca4).
`VarlenaAreaIsDisjoint` checks the live descriptors on demand: one pass
for monotone layouts, a sort otherwise.
2. **Accounted MPool views** (7b5cb06). `mp.WithAccount(account,
owner, site, class)` and `mp.WithAdmission(admit)` return a view of the
pool. Fresh off-heap allocations through the view are charged to its
account. Growth and free follow each allocation's own metadata, so any
view of the pool can grow or free it. Deleting a view is a no-op.
3. **The Vector carries no account** (1319afe). Code that attached a
`vector.AllocationAccountSelection` to vectors or batches now builds a
view once and passes it as the `mp` wherever those vectors allocate.
Operators that bind an account at compile time build their views lazily,
through `mpool.AccountBinding`. Allocation through a view is always
off-heap.
4. **The Vector holds no leases** (1cc5610). A borrowed backing is a
plain alias; the lender keeps the lease.
- Scan output, Arrow and Sirius results: the output batch holds the
lease (`batch.HoldLease`, `bufferlease.Holder`).
- The batch releases it in `Clean`, `CleanOnlyData` and `FreeColumns`,
so cache pins stay bounded to one block
(`TestReaderBorrowedPinsStayBoundedAcrossBlocks`).
   - pSpool and the retained views copy aliased data.
   - Cache-backed scans stay zero-copy.

### Behaviour changes
- **Charges that no longer follow a vector into later code.** These
copies are now unaccounted:
- disttae `Delete` copy-on-write and raw-INSERT row-id copies (restoring
them needs an engine API change);
  - limit, offset and partition copies of accounted input;
  - non-owned shuffle pools;
  - group sort-rollup window copies.
- **Connector/dispatch spools** are charged to the bound statement
account, under a generic owner and site.
- **Block reads with an output account, and accounted aggregates,** now
also charge their temporary buffers.
- **Aliased vectors** (borrowed, windows, decoded) are copied before any
mutation. `SetFixedAt` on an aliased data backing returns an error.

### Tests
- `go build ./pkg/... ./cmd/...`, `go vet ./pkg/...` and `make
static-check` are clean.
- `go test ./pkg/...` is green except:
  - `TestMoCtlUseSnapshot`: also fails on main.
  - Grafana dashboard tests: need a local Grafana server.
-
`TestIssue27529…/null-safe_equality_boolean_coerces_to_string_parameter`:
regressed in #33007 (c272e7a), not here.
-
`TestIssue28397…/issue_29378_prepared_bool_aggregate_keeps_numeric_adapter`:
regressed in #33024 (d39b12c), not here.
- Deleted tests cover only removed APIs: shuffle provenance-lane
sealing, `CopyWithReadonlyArea`, `RetainedReadonlyView*`, and
vector-held lease refcounts.
- New regression tests cover bounded pins, a moved aliased vector being
copied before release, pSpool copying aliased fixed and varlen data, and
`mpool.AccountBinding`.

### TPC-H SF20 (2-CN dev cluster, warm, best of 2)
| | main | #33027 | this PR |
|---|---|---|---|
| Total, 22 queries | 18,945 ms | 18,785 ms | 18,479 ms (−2.5% vs main)
|

All 22 results match main. q12 is +5.6% vs main, the same as on #33027.

🤖 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 22, 2026
## What type of PR is this?

- [x] Code Refactoring

## Which issue(s) this PR fixes:

issue #33025

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

Removes `isBin` from `Vector`. Whether a value was spelled as a hex/bit
literal, or comes from a binary-flagged prepared parameter or user
variable, is a fact about the expression that produced the value. It is
not a property of the vector that holds it.

**Stacked on #33033 (and #33027, #33024).** Review only the last commit:
`d46b67a5ec`.

- **Removed from `Vector`:** the `isBin` field, `GetIsBin`/`SetIsBin`
and `CopyExpressionMetadataTo`.
- **The producer owns the fact.**
- `FixedVectorExpressionExecutor`, `ParamExpressionExecutor` and
`VarExpressionExecutor` record the flag for the vector they return.
- `FunctionExpressionExecutor` works out, for each argument, whether the
result it received is one of those leaves (`isBinaryLiteralResult`). The
check looks through memo and dependent wrappers. It rejects placeholders
the executor substitutes, such as NULLs for skipped branches or masked
results.
- The executor passes the flags to the kernel through the result wrapper
(`FunctionResultWrapper.SetArgumentIsBin` / `ArgumentIsBin`). Kernels
that read `ivecs[i].GetIsBin()` now call `result.ArgumentIsBin(i)`.
  - `IffConditionTruthyAt` takes the flag as an argument.
- **Frontend:** prepared `SET` and `SELECT ... INTO @var` get the flag
from the bound plan expression (`colexec.ExprIsBinLiteral`), not from
the result vector.
- **Copy, selection and scan paths** (batch compaction, pSpool, borrowed
views, blockio membership reads, table_scan gather) only passed the flag
along, so they no longer touch it.

### Tests
- `go build ./...` and `go vet` are clean on the touched packages.
- Unit tests pass: `container/{vector,batch,pSpool}`, `sql/colexec/...`,
`sql/plan/...`, `frontend`, `sql/compile`, `tae/blockio`.
- New tests: `colexec/binary_literal_test.go` and
`plan/binary_literal_argument_test.go`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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 successfully deployed

No deployments
ci — f83cdf20 Deployed Nov 21, 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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants