Repository navigation
refactor(vector): one owner mpool per vector, no borrow semantics (#33019) - #33052
Merged
Merged
Conversation
…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]>
…ctor-prepareparam-out
…-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]>
…lized tests (matrixorigin#33007) Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # pkg/objectio/ioutil/sinker_bounded_lifecycle_test.go
…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]>
, phase A) DICTIONARY was a lazy row-selection view: a vector whose rows indexed an immutable, reference-counted base vector, with read views, freeze/reclaim workspace leases installed into ordinary source vectors, selection scopes and scan publication slots. Every consumer needed a dictionary fast path or a normalization edge. Remove the class and all of its machinery: - vector: the dictionary files (views, bases, row selections, freeze and reclaim, scopes, workspaces, read views), the dictionary function parameter wrappers, IsDictionary/EnsureFlat/EnsureWritable and every dictionary branch. Class 2 stays a retired wire value (LegacyRowBufferClass) that still decodes as FLAT. RetainBorrowedBufferInto (cache-borrowed scan vectors) is kept, 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: dictionary fast paths and the per-overload dictionary capability. - operators: filter, projection, table_scan, shuffle, hashjoin, hashbuild and group lose their dictionary producer/consumer code and use the flat paths they 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. Behaviour is unchanged; performance changes where views avoided copies (filter output, shuffle partitions, hashjoin probe forwarding). A batch-level row selection replaces the shared-selection benefit in a follow-up. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…igin#33021, phase B) A Batch may now carry a row selection shared by all of its columns: the vectors keep their physical rows, logical row i is physical row Selection()[i], and RowCount() is the selected count. This replaces the per-vector DICTIONARY views with one selection per batch. - batch: SetSelection/ClearSelection/Selection/PhysicalRowCount, PhysicalView (an unselected header for evaluating expressions on the 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 receive compacted rows. - filter: evaluates each predicate on the input's physical rows masked to the current survivors, then publishes the input's vectors with the selection when its parent accepts it, and compacts otherwise. It also accepts a selected input. - projection: accepts a selected input, evaluates its expressions masked to the selection, passes column references through, and 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 lives until the producer's next Call, like any operator output. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n#33021) The batch row selection was a list of physical row numbers whose order and uniqueness were a documented contract that nothing enforced: an out-of-order list would reorder rows silently and leave the vectors' sorted flags wrong, and duplicates could not survive masked evaluation. Store the selection as a bitmap over the physical rows instead. It can only describe an ascending subset with no repeats, so the contract holds by construction. The logical row count is the bitmap's popcount, cached when the selection is set. SelectionRows materializes the row numbers for gathers (and, later, for row-number kernels); SelectionMask expands it for masked expression evaluation. Filter builds the bitmap from its first predicate and clears the rows that fail each later one, instead of rebuilding an integer list per predicate. Projection passes the bitmap through unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…trixorigin#33021) reuse.go registered a reuse pool for Vector that nothing allocated from: NewVecFromReuse returned new(Vector) and the pool calls were commented out. Remove the pool, NewVecFromReuse (callers use new(Vector)) and the TypeName method that only served the pool. GetSels/PutSels kept a sync.Pool of []int64 row-number scratch. Put stored a pointer to its own parameter, allocating on every put, and the pooled slices carried whatever capacity their last user grew them to. Operators that compact per batch (filter, table_scan, offset) now keep their own scratch slice; the remaining callers (block reads with deletes or filters, DML utilities, transactions, the frontend) use local slices. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ow list (matrixorigin#33021) blockDataReadWithFilter maps residual-filter survivors back to block offsets. That list must be built in its own slice: a version that reused the storage row list's backing array overwrote the caller's rows in place (1, 4, 7 became 4, 7, 7) while still returning correct values. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng it (matrixorigin#33018) Vector kept an areaDisjoint proof bit that every append, union, shrink, shuffle, sort, window and codec path had to maintain or clear. VarlenaAreaIsDisjoint now computes the same property from the descriptors: every live non-inline descriptor lies inside the area and no two share bytes. Append-built layouts are checked in one pass; other layouts sort the live ranges. Const and dictionary vectors never report it. UnionBatch's contiguous-range fast path already scans the selected descriptors, so the whole-area shortcut (CanCopyWholeVarlenaArea) and the join pre-sizing workaround for it are removed. UnionOne still clears a reused stale descriptor under a new NULL row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An MPool value is now the pool or an accounted view of it. The pool's state moves into an embedded poolCore, so a view is a small value that shares it and differs only in how fresh off-heap allocations are charged: to an allocation account (WithAccount) or through a transient physical admission (WithAdmission). Growth and release of an existing allocation follow the allocation's own metadata, so any MPool value of the same pool can grow or free it. Deleting a view is a no-op. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r account (matrixorigin#33018) A Vector no longer carries an allocation account. Code that attached a vector.AllocationAccountSelection to vectors or batches now builds an accounted MPool view (mp.WithAccount / mp.WithAdmission) and passes it as the mp wherever those vectors allocate. Fresh off-heap allocations through a view are charged to its account; growth and free follow the allocation's own metadata, so any view of the pool can grow or free it. - vector/batch/pSpool/arrowbridge: drop AllocationAccountSelection and the *WithAllocation / *WithAllocationAccount variants; allocation through a view is always off-heap. - objectio, blockio, disttae, materialized, sql/util: request and reader allocation fields are views. - function, aggexec, colexec executors and every operator that binds an account build their views from it (mpool.AccountBinding when the pool is only known after binding). - connector/dispatch build their spool on a view of the bound account. Charges that used to follow a vector into later code now land only where the caller passes a view: disttae Delete copy-on-write, raw INSERT rowid copies, limit/offset/partition copies of accounted input, and non-owned shuffle pools are no longer accounted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ckings (matrixorigin#33018) A Vector no longer holds or releases a BufferLease. A borrowed backing is a plain alias (cantFreeData/cantFreeArea); the lender keeps the lease. - bufferlease: Holder (Hold/Release/Len) and the Keeper interface. - batch: an unexported lease holder (HoldLease/HeldLeases/ReleaseLeases/ MoveLeasesFrom), released in Clean, CleanOnlyData, FreeColumns and the decode-into-batch paths. The scan reuses its batch through CleanOnlyData, so cache pins stay bounded to one block (TableScan.Reset now releases). - objectio/ioutil/blockio: TryBorrowCachedVector hands the cache pin and its pinned-capacity reservation to the output batch; zero-copy stays. - arrowbridge, external Arrow reader, Sirius results: the output batch holds the native buffers; leases move with vectors on batch replacement. - pSpool and retained views copy aliased backings instead of sharing them; CopyWithReadonlyArea and RetainedReadonlyView* are gone. - Aliased vectors (borrowed, windows, decoded) copy before any mutation; SetFixedAt on an aliased data backing errors. Also renames two typeswitch baseline entries whose switches moved into the pool-taking helpers in the previous commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 it, not about the vector holding it. Drop Vector.isBin, GetIsBin/SetIsBin and CopyExpressionMetadataTo. The producer now owns the fact: - FixedVectorExpressionExecutor, ParamExpressionExecutor and VarExpressionExecutor record it for the vector they return. - FunctionExpressionExecutor resolves, per argument, whether the result it received is such a leaf (isBinaryLiteralResult, which sees through memo and dependent wrappers and rejects substituted placeholders) and publishes the flags to the kernel through the result wrapper (FunctionResultWrapper.SetArgumentIsBin / ArgumentIsBin). - IFF condition truthiness takes the flag as an argument. - The frontend derives it from the bound plan expression (colexec.ExprIsBinLiteral) for prepared SET and SELECT ... INTO @var. Copy/selection/scan paths that only forwarded the flag drop it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…matrixorigin#33019) Vector holds a single mp *mpool.MPool replacing offHeap, cantFreeData and cantFreeArea. Every allocation comes from that pool and is off-heap; a nil pool marks a read-only reference vector. A pool passed to a vector call must be exactly the vector's pool. - Window returns a read-only reference; CloneWindow(To) copies. - Buffering operators (order, top, mergetop, group, window, hash build) and the table scan own their pools. - The transaction workspace copies caller batches and never takes them over. - INSERT/LOAD IGNORE NOT NULL fill is copy-on-adjust (colexec.IgnoreFill); lockop publishes refresh timestamps through its own vectors; the Arrow reader owns the batches it publishes. - In-place setters reject read-only vectors; read-only decodes keep a private null bitmap; C callers get null bitmaps covering every row. - Memory model documented in docs/ai-skills/sql-engine.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts with the squash merges of matrixorigin#33004, matrixorigin#33007, matrixorigin#33016 and matrixorigin#33021 (whose branches this branch already contains) keep this branch's side. Upstream fixes merged by hand: Top/MergeTop first ordering key (matrixorigin#33042), catalog replay carry (matrixorigin#32948), deleteTable error-only return, saved result scan projections (matrixorigin#33045, output vectors use the operator's output pool), JSON comparison parameters (matrixorigin#33014). New upstream tests are converted to NewVec(typ, mp). Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt
requested review from
LeftHandCold,
XuPeng-SH,
aptend,
aunjgr,
cpegeric,
gouhongshen,
iamlinjunhong and
jiangxinmeng1
as code owners
November 21, 2026 23:05
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
Resolve conflicts with upstream's Decimal128 integer SUM and Decimal256 median results: keep upstream assertions, free results with their owner pool, and pass the owner mpool to vector.NewVec / aggexec.NewVectors in the newly added tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…atorLimit growOwned lost the GrowCapacity pre-check when the allocation-account wrappers were removed, so a grow past the allocator limit surfaced as mpool's plain internal error and merge top no longer converted it to a controlled OOM (TestAccountedMergeTopHardVectorCapacityFailureIsControlled). Restore the check, matching upstream. Co-Authored-By: Claude Opus 5.5 <[email protected]>
cpegeric
added a commit
to cpegeric/matrixone
that referenced
this pull request
Nov 23, 2026
matrixorigin#33052 changed createResultBatch to take the owning mpool and updated the CPU callers only; cagra_create_gpu.go and ivfpq_create_gpu.go (gpu build tag) no longer compiled. Pass proc.Mp(), the pool the batch is cleaned with. Co-Authored-By: Claude Opus 5.5 <[email protected]>
3 of 7 tasks
mergify Bot
pushed a commit
that referenced
this pull request
Nov 23, 2026
…ML planner (#33110) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [x] Feature - [ ] Test and CI - [x] Code Refactoring ## Which issue(s) this PR fixes: issue #21790 #21791 #33108 ## What this PR does / why we need it: Design: [docs/design/20261123-new-dml-irregular-index-maintenance.md](https://github.com/matrixorigin/matrixone/blob/dd1b67fe7b/docs/design/20261123-new-dml-irregular-index-maintenance.md), design revision 2 / contract R1 (review required). It records the index classes, the maintenance invariant, row-stream ownership per planner route, ordering of queued maintenance, transaction and CDC semantics, and the supported shapes. DELETE and primary-key UPDATE on tables with FULLTEXT or vector indexes now run on the new DML planner (bind_* + MULTI_UPDATE) for every index type, and foreign key actions keep the child tables' indexes exact. - **DELETE:** tables with async indexes (HNSW, CAGRA, IVF-PQ, fulltext2, ASYNC ivfflat/fulltext) and tables with sync IVF_FLAT, FULLTEXT or MASTER indexes are planned by the new binder; sync indexes are maintained by delete-by-key sub-plans. 500k-row delete on a 1M-row table with ivfflat(128-d) + master + fulltext: 0.96 s vs 1.33 s on the legacy path. - **Primary-key UPDATE:** allowed on sync IVF_FLAT and FULLTEXT tables (previously rejected, #25617), including RETURNING; entries are re-keyed in the same statement. - **Legacy-planned DELETE** (foreign keys, multi-table DELETE) maintains the same indexes with the new planner's sub-plans; the legacy per-algorithm delete code is removed (about 900 lines). - **Foreign key actions** (#33108): UPDATE on a parent maintains the child's indexes instead of rejecting; REPLACE on a parent no longer panics; CASCADE + SET NULL from the same parent row no longer drops the index entries of the nulled rows (regular secondary indexes included); self-referencing tables rebuild the indexes the cascade changes. - **reduceSinkSinkScanNodes** folds sinks in step order; map order could fold a consumer before its producer and leave a dangling sink scan (`no data receiver for sink node`). - Delete-by-key joins on hidden index tables push an exact runtime filter into the hidden-table scan. Validation: BVT `dml/delete/delete_irregular_index_sync`, `pessimistic_transaction/vector/delete_async_irregular_index` and `foreign_key/fk_irregular_index` check after each statement that every hidden table has no orphan and no missing key; the dml, foreign_key, fulltext, vector, array, ddl and pessimistic_transaction suites pass; `pkg/sql/plan` and `pkg/sql/compile` unit tests pass. GPU: `gpu_cases/pessimistic_transaction/vector/vector_cagra_dml_irregular` and `vector_ivfpq_dml_irregular` run the same DELETE, PK UPDATE and FK-action paths on CAGRA and IVF-PQ; both pass on GPU, as do the existing GPU async/delete cases ([logs](#33110 (comment))). The GPU build also needed `createResultBatch(proc.Mp())` in `cagra_create_gpu.go` / `ivfpq_create_gpu.go`, which #33052 missed on main. Limits: #33109 (REPLACE with a SET NULL grandchild) fails without any index and is not addressed here. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Approved-by: XuPeng-SH <[email protected]>
This was referenced Nov 24, 2026
XuPeng-SH
pushed a commit
that referenced
this pull request
Nov 24, 2026
## What type of PR is this? - [x] BUG ## Which issue(s) this PR fixes Fixes #33118. Regression introduced by #33052. ## What changed Insert replay passed the engine mpool to protobuf decoding. This copied column data/area into native vectors, but retiring a row removes the row and index entries without owning the last reference to that batch. Multiple partition snapshots may still read it. Consequently, freeing on row removal would be unsafe; leaving the copy as-is leaks it. Use a read-only view of the received logtail instead: the client unmarshals each response into fresh Go buffers, and a snapshot keeps exactly the referenced buffers alive. Direct/local insert callers (notably catalog bootstrap) can supply a protobuf view over mutable engine vectors, so detach those inputs on the Go heap when retaining row data. Both entry points use the same replay implementation. No per-row release, finalizer, background task, or wire/SQL format change. ## Validation - Same test on unchanged main `07d7baa32a`: after actual object retirement the replay pool retained 67 B (received), 67 B (local), and 103 B (keys-only). The fix returns all three to zero and an older snapshot still returns the original key and out-of-line varchar. - Negative control: merely changing the original decoder argument to nil clears the pool but makes the local snapshot return key 0 after its source is overwritten (expected 42). - Full logtailreplay package passes both normal and race builds. The exact regression test also passes 100 consecutive repetitions under `-race`. Real TAE `TestClusterByRealLogtailIntegration` passes; its allocator ends at its initial balance. Package vet and the configured incremental SCA (molint and golangci-lint) pass. - Live-entry microbenchmark, same base/fix entry point, 5,000 iterations: 16 → 13 Go allocs/op. This is not an end-to-end throughput claim. The historical TKE run is the operational witness, not a run of this patch. A post-merge Weekly should check the native replay stack and the AP restart count during no-PK bulk insert. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What type of PR is this?
Which issue(s) this PR fixes:
issue #33019
What this PR does / why we need it:
A
Vectornow has exactly one owner pool, and nothing else about memory.offHeap,cantFreeDataandcantFreeAreaare gone, replaced by onemp *mpool.MPoolset when the vector is created.Stacked on #33034 and #33033. Review commit
90b459f68c(the change), the merge commitd6fc6630fc(upstream sync) and the follow-ups95155a83ad,83a5ef6377,af929a9ece,3aa882ce19,a6e0d0e4e3,24c5d57fbb,4773ebe65dand53b867de02. Everything below90b459f68cbelongs to the earlier PRs.The memory model
The model is written down in
docs/ai-skills/sql-engine.md("Vector 内存管理模型"):mpmust pass exactly the vector's own pool. A view of the same pool doesn't count. A mismatch is an error, and a panic inFree.Freeonly drops its references.colexec.NewOperatorMPool: order, top, mergetop, group, window and hash build, plus the table scan. Other operators useproc.Mp().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.Vectorfields without human review.Main changes
Window and decode.
Windowreturns a read-only reference;CloneWindow/CloneWindowTocopy.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.Freeis strict. Mostvec.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.CleanOwnedis 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 ([Subtask]: Remove dictionary stuff #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;
CompactIntotakes 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
colexec.IgnoreFilladjusts a copy it owns, one reusable vector per column. PreInsert, the external insert and multi_update use it.BatchPublisher).Bitmap.WordsCovering(n).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).95155a83adcarried a copy ofcollation_metadata_test.goolder thanmain's that did not compile;a6e0d0e4e3takesmain's file and adapts it.Expr_Vecliterals were freed through the wrong pool.Behavior changes
Tests
go build ./...andgo vet ./pkg/... ./cmd/...are clean.83a5ef6377and now pass.83a5ef6377restores their updates.95155a83adis one of those commits, cherry-picked.tests/serviceTestTaskSchedulerExpiresLostRunnerWithoutReplayis flaky: 2 of 4 runs fail on plain upstreammaintoo.tests/txnTestWriteSkewIsAllowedfailed in the full run and passes when run alone.util/metric/mometricfails while a local cluster holds port 7001.util/metric/v2/dashboardneeds Grafana.make dev-upcluster built from this branch:load_datapasses 99%; the only failures areinto outfilepermission errors from the environment.dmlpasses 98%; the failures needAUTO_ID_CACHE, a CDC loopback to 6001, or ETL data.fault_injectbugs above, all fixed. The fault-injection and clone cases were compared against an upstreammainimage on the same cluster and now pass.mainimage or need what the dev cluster lacks:AUTO_ID_CACHE, statement tracing (disableTrace = true),into outfilepermissions, external servers. Optimistic cases are excluded, as in CI.INSERT IGNORE ... SELECTfrom 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