Repository navigation
Description
Why do you want to refactor this code?
Systematically simplify the current MatrixOne design and implementation: consolidate responsibilities and authoritative state, remove unnecessary intermediate states, repeated execution/validation, resident maintenance, and obsolete compatibility surfaces, and fix verified lifecycle and task-correctness defects.
This optimization Task has concrete subtasks. The scope includes the current architecture itself. The 4.2 branch is a provenance baseline, not a standard of design correctness: some problems were introduced on main, while others already exist in the baseline.
Owner: @XuPeng-SH. Newly created subtasks are assigned to the same owner. View work reuses #29433, preserving @ck89119 and the existing subtask tree rather than starting a parallel implementation. Related long-running engineering-quality tracker: #29249.
Describe the solution you'd like
Provenance categories and work packages
- A (12 items): introduced by 4.2-to-main evolution or incomplete retirement on main. This class describes provenance: it includes reproduced regressions and mechanisms whose benefits still need evaluation, rather than declaring every change a regression.
- B (12 items): pre-existing in the 4.2 baseline and retained on main. Evaluate whether fixes should be backported to 4.2-dev; do not attribute these problems to main introduction.
- C (2 items): baseline design debt expanded or amplified on main. Identify both the original weakness and the added consumers or cost.
| ID | Origin | Subtask | Evidence |
|---|---|---|---|
| D01 | B | #32279 - Separate SQL task duration from execution-owner failure detection | Reproduced behavioral defect |
| D02 | B | #32280 - Use the same execution identity for SQL task repair and normal completion | Reproduced behavioral defect |
| D03 | B | #32281 - Make SQL task async/run completion consistent and resumable after partial failure | Reproduced behavioral defect |
| D04 | B | #32282 - Give taskRunner complete ownership of contexts on rejection and terminal completion | Reproduced resource retention |
| D05 | B | #32283 - Close the taskRunner shutdown dependency between result producers and consumers | Reproduced shutdown hang |
| D06 | A | #32284 - Separate authorization snapshot reads from transaction-creation rate admission | Regression reproduced with real local-cluster A/B runs |
| D07 | B | #32285 - Reuse the existing cron engine instead of a resident scheduler per SQL task | Duplicate cost measured; no end-to-end regression claimed |
| D08 | B | #32286 - Use actual storage results for refresh instead of a Ping before each operation | Additional network work confirmed by a probe |
| D09 | B | #32287 - Coordinate process-wide RSS pressure actions while retaining component reservations | Duplicate actions confirmed by source and a synthetic probe |
| D10 | A | #32288 - Give post-upgrade tenant maintenance an explicit owner instead of repeating it on every CN | Evolution cost confirmed in source; scale benefit remains to be measured |
| D11 | B | #32289 - Define SQL task history retention and bounded default history reads | Capacity and operational design gap confirmed in source |
| D12 | C | #32290 - Represent catalog identity and scope explicitly instead of deriving semantics from DDL text | Fragile ownership representation and propagation confirmed in source |
| D13 | C | #32291 - Reduce internal protocol gates, fallbacks, and repeated plan scans to supported compatibility needs | Complexity/work confirmed by source and microbenchmarks; validate each benefit |
| D14 | A | #29433 - Reuse the existing on-demand View refactor and retire refresh-only startup/maintenance coupling | Existing refactor; current coupling confirmed by source and startup observation |
| D15 | A | #32292 - Simplify unpublished-object ownership and intermediate sinker/transaction/engine ledgers | New reliability mechanism; evaluate its complete complexity and cost |
| D16 | A | #32293 - Make index-file cache enablement, disk budgets, and embedded defaults explicit | Local initialization behavior change reproduced |
| D17 | B | #32294 - Evaluate per-tenant optional-feature catalog cost and simplify initialization ownership | Eager initialization confirmed; benefit/cost decision remains open |
| D18 | B | #32295 - Define statistics freshness and cost semantics instead of exposing implementation history | Implementation history exposed in the API; semantic differences require analysis |
| D19 | B | #32296 - Reduce disabled-statistics scheduling and logging cost while preserving dynamic resume | Disabled-state cost confirmed in source |
| D20 | A | #32297 - Complete transaction-trace retirement at the supported catalog compatibility boundary | Incomplete retirement on main; confirm the supported compatibility window |
| D21 | A | #32298 - Simplify operator steps for 4.2-to-main upgrades with preflight and resumable migration | Added operational burden confirmed in source/documentation; workflow optimization |
| D22 | A | #32924 - Preserve persisted floating BIT_COUNT semantics across upgrades | Reproduced with the official 4.2.8 binary and the same data directory |
| D23 | A | #33036 - Restore v4.2.8 v1 table dumps with floating BIT_COUNT generated columns | Official v4.2.8 physical archive rejected by the main-target reader. Verify schema fingerprints and binding provenance. |
| D24 | A | #33558 - Preserve SQL compression contracts across the next major upgrade | Reproduced missing compressed-key lookup and accepted duplicate after reopening v4.2.9 data on main. Carry forward the V2 SQL functions. |
| D25 | A | #33560 - Preserve SQL Unicode semantics across the next major upgrade | Reopened v4.2.9 data on main. Previously distinct columns became ambiguous, and the recomputed generated key missed the stored row. |
| D26 | A | #33700 - Resolve existing planner function ID divergence | Ten numeric slot conflicts and six same-name ID changes confirmed in source. Validate supported upgrade and restore paths. |
Suggested execution order
- Execution identity, terminal state, and release boundaries: D01-D06. Review the shared task/run owner for D01/D02/D03, and runner resource/shutdown ownership for D04/D05. Close the complete lifecycle rather than adding another inconsistent repair path.
- Normal-operation and disabled-feature fixed cost: D07-D11 and D18-D19. Preserve product semantics while consolidating scheduling, network preflights, process-wide actions, and unbudgeted history.
- Public workflows and intermediate compatibility added on main: D10, D13-D16, and D20-D21. Coordinate upgrade, recovery, and retirement with [Refactoring]: Make on-demand derivation the authority for ordinary View metadata #29433 and [Bug]: Consolidate catalog upgrade to 4.0.7 for 4.1 and 4.2 #31490.
- Catalog representation and tenant cost: D12 and D17. Find existing declaration/lifecycle owners before choosing minimal explicit representation and initialization policy.
Subtasks define independently verifiable contracts, not mandatory PR boundaries. Shared-root-cause or non-orthogonal implementation work may be combined; distinct lifecycles and product contracts still need separate acceptance.
Required content for each subtask
- Provenance: baseline debt, main introduction, or baseline debt amplified on main, with both source snapshots and the supported contract.
- Reason to change: real consumers, authoritative state, state production/consumption/release, normal cost, and reachable failure paths.
- Consolidation: reuse existing responsibilities and remove superseded state, validation, storage, execution paths, and unused abstractions.
- Acceptance: user-visible behavior, boundaries/unhappy paths, and relevant performance. Evaluate implementation, test, and documentation changes separately.
Shared completion criteria
- Verified correctness, retention, and shutdown problems have minimal maintained regressions using deterministic barriers/fake clocks, without real long waits, repeated cluster setup, or implementation-mirroring assertions.
- Normal paths have no unjustified per-SQL probes, synchronous I/O, or default resident work. Performance claims use reusable targeted measurements; call counts are not presented as end-to-end speedups.
- Consolidated paths remove superseded code, state, configuration, compatibility branches, and redundant tests. Deleted lines or test volume are not success metrics.
- Necessary persisted-data, backup/restore, and external-interface contracts are validated. Disabled/future features justify their default costs with actual benefits.
- If investigation shows the existing mechanism is the better design, a short consumer/benefit rationale can close that decision item. Do not force a refactor solely to complete the list.
Catalog upgrade baseline for coordinated releases
- Validate each
4.2.xpatch candidate from the latest generally available4.2.xrelease that precedes it. For a new release line cut frommain, such as5.0, use the latest generally available4.2.xat target release time. Pin the official source artifact, commit and persisted catalog identity for each validation run. Repeat the check if a newer4.2.xships before the target. - Freeze the catalog migration definitions and
(Version, VersionOffset)when they ship. The two release lines share one version history. A patch that preserves the catalog can reuse its identity. Additional required migrations belong to a new catalogVersion, with its own offset. When cutting a new line, carry forward the published predecessor and put unpublished migrations in a successor. For example,4.0.6/5 → 4.0.7/1is a valid route when the successor has one migration entry. - Use the existing catalog and tenant upgrade framework. The release check must start with data written by the official source artifact, stop it, and migrate the same data with the release candidate. Verify the final
READYcatalog, existing data and routines, and recovery after interruption and restart.
Related evidence from #33548. The offset mismatch was reproduced between development snapshots. A local stopped upgrade from the official v4.2.9 release to main at 38c68d02ca completed 4.0.6/5 → 4.0.7/53 and reopened the migrated data after restart.
Describe alternatives you've considered
Continuing to add scanners, repair branches, fallbacks, and independent caches for individual incidents spreads ownership and state further. A whole-system rewrite or a large unified framework would also expand risk. Prefer complete, narrowly scoped consolidation around existing owners while preserving real functionality and necessary recovery.
Additional information
Investigation baselines and validation limits
- Main investigation snapshot:
a78ee266877c9a0188bf64a3426e5976ec3d9ff7. Some earlier A/B runs used57e7871e500e6e3d35fd352a092ee41b03a979fc; the relevant paths were unchanged afterward. - 4.2-dev comparison snapshot:
ebf03dc42bf25ba00018da019783e1037299d1ae. The baseline is a branch snapshot, not an assertion that its overall design is correct or a substitution of git merge-base for the product baseline. - Before initial publication, remote main was checked at
d5497dff0001d512f0a817c9355e6cd9c90e254a, adding only an HNSW BVT commit after the investigation snapshot. Remote 4.2-dev wasf3c72c6bf90c402e147197991fc8fd29c8c3c056, adding point-update/CI fixes without changing the listed task-lifecycle provenance. Subtasks retain immutable source links; recheck the implementation head before changing code. - D01-D05: Linux amd64, Go 1.27.1, real production state transitions and memory task storage, with controlled SQL dependencies or selected storage errors. Normal runs and 100 focused race repetitions per exact probe confirm the counterexamples. This is not complete multi-CN or real-storage-failure acceptance.
- D06: isolated real single-CN A/B runs, limited/unlimited controls, and the business connection's wait stack. The default is unlimited; the result is not generalized to all queries.
- Other probes, source-level structure, and open benefit/cost questions are distinguished in the subtasks. A passing diagnostic means the current counterexample/cost was observed; it does not mean the defect has been fixed.
- Raw investigation files remain local. GitHub descriptions contain key results, reproducible validation steps, and source references. Reuse valid evidence; raw uploads, temporary evidence commits, and a separate RFC for ordinary cleanup are not required.
Reuse and duplicate review
Existing open and closed issues were searched. D14 reuses #29433, including its existing nine subtasks. #25604 protects normal CompleteSQLTaskRun against stale-runner writes; D02 concerns a repair bypass losing same-CN execution identity. #29371 addresses blocked cron registration; D05 concerns completion-channel shutdown waiting. These do not reopen the same resolved defect unchanged. Other related work is linked in each subtask.
Additional provenance for reused D14
Main adds persistent View dependency/refresh catalogs and startup/generation admission that are absent from this baseline refresh architecture. Main's refresh gate is fixed false, but some View-named paths serve active persisted-expression responsibilities.
main comparison: pkg/sql/compile/view_metadata.go:83; pkg/sql/compile/view_metadata_recovery.go:70; pkg/cnservice/server_view_metadata_admission.go:38
D14 follows the existing roadmap's acceptance while checking the boundary between refresh-only and shared persisted-expression responsibilities. Preserve the existing owner and subtask tree.
Activity
15 remaining items
XuPeng-SH commentedon Nov 18, 2026
Focused main/v4.2.8 drift campaign: 29 concrete optimization candidates
Snapshots:
main@87c44445f83e308ef12dd7ca0e570cec1e6690d9,v4.2.8@10d204b8763f19b2b37ba2147d1d4c1a7828d6d4, merge-base2758eb1d3f812759c03c7c8a7463e2757dacb633.This is a candidate catalog, not 29 confirmed bugs and not a backport list. IDs C01-C29 are investigation IDs; they are not automatically new top-level Dxx work packages. Each counted item has a distinct reachable mechanism, source location, a smallest-change direction and independent acceptance. File-count and two-head snapshot differences were not counted as defects.
Evidence labels:
Seven focused source explorations completed. Root validation added the C01 planner reproduction, the C03 throttler/scheduler chain, and the C15 comparative benchmark. The remaining entries are source-backed candidates, not measured regressions.
1. Merge memory admission: a deeper caller/contract break
C03 [B, S] Merge execution ignores
Acquire's denial and can release a reservation it never acquiredMain:
pkg/vm/engine/tae/db/merge/scheduler.go:1273-1278callsExecuteFor, then callsrc.Acquire(eSize)but ignores both return values, and always executesAddTask/Admitafter executor acceptance.pkg/common/rscthrottler/resource_throttler.go:600-620returnsgranted=falsewithout incrementingreservedwhenavail < ask.pkg/vm/engine/tae/db/merge/scheduler.go:216-224releaseseSizewhen the task completes.v4.2.8 has the same ignored result at
scheduler.go:1267-1272and denial path atresource_throttler.go:602-617.A source-derived counterexample is:
Acquirereturns false and leaves A's 60 reserved.reservedbecomes zero even though A is still running.This is more precise than the initial "one batch merely over-reserves" hypothesis: the default controller can reject, but this caller ignores the rejection. It also creates a possible ungranted release erasing another live task's reservation. This event sequence is source-proven; it has not been executed as a scheduler integration test.
The single-object path compounds the same ownership problem:
controlTaskMemInPlacestops shrinking at one object andtrigger.assignsretains it, but the later scheduler still does not establish whether the reservation was actually granted.Smallest change: acquire before executor admission; defer on
granted=false; if executor admission then fails, release that successful acquisition. Only a granted task may release through its completion observer. If permanent-oversize work must run, make it an explicit single-flight exception rather than silently treating denial as success.Acceptance: a denying throttler with two tasks (one granted A, one denied B) must show B not executed and A's reservation unchanged after B's lifecycle. Cover executor rejection after a successful acquire, temporary shortage versus permanent oversize, completion before
Admit, and legacyOnMergeDonepaths. Then test the 100-available/three-60-estimate batch without assuming everyAcquiresucceeds.C04 [B, S] Merge estimation is disconnected from actual block capacity
pkg/vm/engine/tae/mergesort/task.go:524-541hard-codes 8192 rows and mixes input, transfer and GC margins. Actual buffers useschema.Extra.BlockMaxRows(tables/jobs/mergeobjects.go:192-194,mergesort/task.go:266-279). v4.2.8 has the same formula attask.go:547-564.For
BlockMaxRows=16384, the estimate's main byte terms can be approximately1.75*S + 30*R, while one input plus one output block is approximately2*S, before the write arena. This is a formula mismatch, not a measured high-water result.Pass the real block-row capacity into the estimator and separate input blocks, output block, transfer state and arena/margin. Validate default 8192 behavior, 16384-row blocks, skewed block rows and wide rows against measured merge high water; do not merely multiply the current constant.
C05 [B, S] Ordinary sparse range reads still materialize the whole envelope
Main
pkg/fileservice/s3_fs.go:1135-1152,1201-1216,1242-1250checksexpensiveMinimalRangeReadonly on the full-object streaming fallback. The ordinary non-full-object range path goes directly fromreadRangeto onegetContent/io.ReadAllover[minOffset,maxEnd). The range calculation is atpkg/fileservice/io_vector.go:131-163; v4.2.8 has the corresponding path.Two distant 4 KiB entries can therefore produce a roughly 100 MiB network read and live
contentBytes, not an 8 KiB read. This is an explicit range-policy candidate, not a leak claim.Reuse the existing 8 MiB/8x guard before the first ordinary range read and fall back to individual or locality-grouped reads. Fake storage must assert actual requested ranges for distant and adjacent entries, partial cache hits,
Data,WriterForReadandReadCloserForRead, with identical returned bytes.C06 [B, S]
S3ReadSizedoes not measure physical S3 bytesMain
pkg/fileservice/s3_fs.go:1044-1066accumulates requested entry sizes; actual transport bytes are already counted at:1171-1193, but only sent toS3ReadIOBytesHistogram. Sparse envelopes, full-object reads, unknown lengths and short reads make the values diverge. v4.2.8 has the same split.Keep requested-bytes and physical-bytes as separate explicitly named metrics; do not add a second accumulation of the same counter. Validate sparse, full-object, retry, short-read and partially drained-reader cases. This also prevents merge memory/read-amplification investigations from using the wrong metric as evidence.
2. A measured scaling candidate, including the tradeoff
C15 [B, M]
appendPrepareSchemasis quadratic, but an unconditional high-allocation index is not the right fixMain
pkg/sql/plan/build_dcl.go:663-688; v4.2.8build_dcl.go:415-440. Every new dependency scans all retained dependencies and performs snapshotproto.Equalchecks.A local diagnostic overlay compared the baseline with two semantics-preserving indexed alternatives. The tests covered ID-OR-name matching, publisher tenant, subscription, snapshots, zero IDs, duplicates and existing prefixes; both alternative tests passed. Environment: Go 1.27.1, darwin/arm64, Apple M4, controlled CGo wrapper,
-benchtime=100ms.The large-D CPU opportunity is real in this microbenchmark, but the naïve index creates a severe allocation tradeoff. The compact variant removes per-entry bucket-slice allocations, not the larger map footprint. This does not justify indexing every small plan.
Candidate direction: retain the simple loop below a measured threshold and use a compact ID/name index only for large dependency sets, preserving
proto.Equaland result order. Benchmark actual plan shapes and set an allocation ceiling. These overlay alternatives are provisional diagnostics, not committed implementations.3. Planner, authorization and prepared-plan ownership
C01 [A, R] Dependent finalization loses validation-only privilege carriers
Already detailed in the preceding #32278 comment. The focused
LIMIT 1probe passed for an ordinary plan and failed for a dependent plan:CatalogDependenciesretainedcustomerin both, but the privilege carrier survived only the ordinary path.customerremained non-executable. The source consumer isQuery.Nodes-basedextractPrivilegeTipsFromPlan.Relevant main files:
pkg/sql/plan/query_builder.go:4450-4452,4746-4752,window_binder.go:827-858,correlation_binding.go:153-179,pkg/frontend/authenticate.go:7418-7469. A restricted-role server probe remains required before calling this a complete privilege bypass.C11 [A, S] Used named-window definitions are bound twice
Main
pkg/sql/plan/window_binder.go:667-700validates every definition with a separate builder; actual windows bind the expanded definition again at:1108-1206. The validation builder and context cloning are at:568-679. v4.2.8 lacks this validation-only builder.For
SELECT SUM(t.a) OVER w ... WINDOW w AS (...), expansion already places the definition in the executable window. Record the used-definition closure and reserve validation-only binding for definitions not covered by an executable window. Unused definitions still require complete semantic, catalog and privilege validation. Compare errors, plans, Params, CatalogDependencies, ViewReferences and carriers; cover chained/shared definitions.C12 [A, S] Window count validation and named-window expansion repeat the same AST walk
Main
pkg/sql/plan/query_builder.go:6555-6558consecutively calls the passes inwindow_binder.go:49-96and:478-550. Both walk SELECT/WHERE/GROUP BY/HAVING/ORDER BY; their window-node actions differ, but the rest of the traversal is repeated.Share one named-window preprocessing traversal while preserving the current 127-window limit and error precedence. Acceptance must include 127/128 windows combined with undefined/cyclic definitions, ORDER BY windows and no descent into subqueries. A plain query without named windows should not pay for a new abstraction.
C13 [A, S] Correlated scalar projection recomputes the same expression properties
Main
pkg/sql/plan/flatten_subquery.go:1129-1189repeatedly callshasCorrColandexprHasColReffor the same projection, including up to four correlation walks on a successful normalization path. v4.2.8 uses the older, smaller normalization path.Cache a per-projection summary
{hasCorr, allDepthOne, hasInnerCol}for the duration of this read-only normalization; keep volatile/type validation separate. Validate plan equivalence for no-correlation, depth>1, aggregates, volatile expressions, pure-outer and mixed inner/outer expressions. Do not introduce a cross-subquery cache after plan mutation.C14 [A, S] UDF metadata dependencies make cached metadata plans permanently stale
Main
pkg/sql/plan/build_show.go:637-642setsViewMetadataDependsOnUdf;pkg/frontend/mysql_cmd_executor.go:4530-4534immediately returnschanged=true, reaching rebuild at:6291-6312. v4.2.8 does not have this coarse UDF entry.Repeated
SHOW CREATE VIEWfor a view referencing an unchanged SQL UDF therefore cannot reuse the affected ordinary cached plan. Introduce versioned UDF identity in the existing dependency contract and invalidate on definition generation change, not on the mere presence of a UDF. Until a generation exists, the conservative branch must remain. Verify repeated execution plus DROP/CREATE FUNCTION, view alteration and prepared behavior.C16 [A, S] Updating one cached statement deep-copies all statement statistics maps
Main
pkg/frontend/plan_cache.go:155-162,267-276, entered fromsession.go:2491-2508, clones the full per-statement stats-version map collection before replacing one index and re-aggregating. v4.2.8 lacks these maps.Copy the outer slice, retain untouched immutable maps and clone only the replaced statement's map. Preserve old-cache immutability, conflict rejection, AST/LRU lifetime and concurrent readers. A multi-statement benchmark should show cost depending on the changed statement, not unrelated statement count; incremental aggregate maintenance is a later optimization, not a prerequisite.
C17 [A, S] Low-precision MySQL output allocates and converts a whole column before row output
Main
pkg/frontend/output.go:815-838,885-888creates a full[]float32; getters later consume it row by row at:599-610.mysql_protocol.go:412-425converts each batch before writing. v4.2.8 does not have these low-precision output branches.Retain the typed source and perform
ToFloat32at the requested row, as the existing row-extraction path already does. Cover BF16/FLOAT16/FLOAT8/FLOAT4, NULL, const, special values and text/binary protocols. Assert identical wire metadata/values and lower per-batch allocation; do not change the externally reported FLOAT type.C18 [C, S] Authorization derives related facts through repeated plan walks
Main
pkg/frontend/authenticate.go:9864-9877callshasMoCtrl,isTargetSysWhiteList, thenextractPrivilegeTipsFromPlan;authenticate2.go:242-268adds expression traversal. UPDATE/DELETE also precomputes targets before the main scan atauthenticate.go:7446-7464. v4.2.8 has repeated derivation too; main covers more expression shapes.Produce these facts through one read-only analysis only if measured plan sizes justify it. Preserve all
mo_ctrl/fault_injectplacements, whitelist partial/full matches, privilege tips, REPLACE/MERGE and prepared SET behavior. This is not a request to create a generic plan-analysis framework for a handful of nodes.C02 [B, S] PK conflict checks build data-block filters when no data block survives pruning
Main
pkg/vm/engine/disttae/txn_table.go:3216-3259marshals all keys, constructs base/block filters, creates a search closure and allocates cache vectors before thelen(candidateBlks)>0guard at:3261. The tombstone branch at:3343usestombstonePKExistsInRange, which receives keys directly and does not consume those objects. v4.2.8 has the same ordering with two cache vectors.When ZM/BF pruning leaves zero candidate blocks, this setup is dead with or without tombstone checking. Move data-block-only setup behind the guard. Preserve candidate-block bailout ordering, tombstone checks, cancellation, obsolete-object retry and filter cleanup; benchmark zero-candidate allocation with small and large key vectors.
C29 [A, S] Aggregate-spine admission repeats an unchanged subtree search
Main
pkg/sql/plan/flatten_subquery.go:2034-2057callsfindAggNodeBelow(first.Children[0])at:2037and again at:2052, with only read-only checks between. Reuse the first result for the grouped/suppression decision. This is a small local cleanup, not a reason for a cache framework. Acceptance compares all five return values and the complete plan for no-second-AGG, grouped-first-AGG and non-single-child controls.4. Expression and container execution
C07 [A, S] Decimal specialized fallbacks re-evaluate inputs already computed
Main
pkg/sql/colexec/evalExpressionDecimalTyped.go:110-140evaluates left/right, then on const, NULL, shape or kernel rejection callsroot.Eval.FunctionExpressionExecutor.Evalevaluates its parameter executors again atevalExpression.go:1949-1997. The chain path has the same structure atevalExpressionDecimalChain.go:267-340. v4.2.8 lacks these specializations.Thus a fallback can execute the same leaf/subexpression twice in one batch. Add an internal root evaluation entry that consumes the already-produced parameter results; keep the numeric kernels, but do not rerun the tree. Count leaf executions for NULL, const, dictionary, selectList, empty and changing shapes, and compare NULL bitmap, scale, overflow and errors with the generic tree.
C08 [A, S] Expression DAG reuse is split between build-time memoization and post-build discovery
Main has memo construction in
pkg/sql/colexec/evalExpression.go:96-173,329-357, then a second plan/executor discovery and replacement pass inevalExpressionSubjectReuse.go:37-96,108-169,267-335, entered fromfilter/filter.go:123andtable_scan/table_scan.go:395. v4.2.8 only has recursive construction.Identity, purity, NULL substitution, reset and lifetime rules now have two owners. Move subject admission/identity into the build context with per-OR reset generations, then retire the post-build replacement only after equivalent execution-count and lifecycle tests. Cover nested CASE select lists, volatile/diagnostic functions, cross-batch/query reset, construction failure and Free ownership. This is a design consolidation candidate, not a request to delete the OR/LIKE optimization.
C09 [A, S] Pipeline batch decoding parses the stable envelope twice
Main
pkg/container/batch/pipeline_codec.go:73-92callsstableBatchPayloadLength, thenUnmarshalBinaryWithPrepareParamKinds; the latter repeats the length parse atbatch.go:686-692. The parser visits vector, attribute and ExtraBuf fields atbatch.go:969-1032. v4.2.8 has the direct stable decoder.Use one internal envelope decode that returns stable/trailer/grouping boundaries, while keeping released wire formats and public wrappers intact. Instrument one stable-field traversal per decode. Verify legacy/stable byte identity, no extension, both trailers, grouping, truncation, forged footer magic and receiver reuse cleanup. This is repeated metadata parsing, not a claim of an extra full-batch copy.
C10 [C, S] FunctionParameter Generate/Reuse duplicate shape logic, while converted buffers are not reusable
Main
pkg/container/vector/functionTools.go:61-237,239-375maintains parallel fixed/string Generate and Reuse classifiers. Conversion arrays are allocated at:95-98,115-123,140-148; Reuse rejects a converted wrapper when effective types differ at:193-195. v4.2.8 already has the dual implementation; main adds dictionary/effective-type branches.Consolidate binding/classification and let conversion wrappers own a reusable conversion buffer, with shape/type changes falling back to replacement. Cover fixed/string × const-null/const/flat-null/flat-nonnull/dictionary and DECIMAL64/FLOAT→DECIMAL128. Stable-shape rebinds must preserve logical row selection and NULLs while avoiding conversion-array reallocation.
5. Runtime, CDC and protocol candidates
C19 [C, S] Prepared
Compile.Resetrecursively walks the same scope tree twiceMain
pkg/sql/compile/compile.go:394-427resets scopes, thenUpdateScopeTxnOffsetat:423-425walks them again (:530-540); main additionally visits operators for Apply even thoughresetForReusealready has an operator walk. v4.2.8 has the repeated scope traversal atcompile.go:241-284.Compute the write offset once and pass it through the existing reset recursion, updating Apply in the existing operator callback. Verify nested PreScopes and Apply receive the current offset, prepared DML cannot see prior writes incorrectly, generation cleanup stays ordered, and reset failure/executor absence preserve current behavior.
C20 [B, S]
OpWorker.WaitStopbusy-spins until pending work drainsMain and v4.2.8
pkg/vm/engine/tae/tasks/worker/worker.go:157-189spin onPendingat:179-186; decrements occur at:142-150,197-207. A long operation turns shutdown into continuous atomic polling.Use a stop-only drained notification and funnel all decrement paths through one helper. Cover empty, queued and long-running operations, concurrent SendOp/Stop, send failure, exactly-once QUIT/close and no lost wakeup. Measure CPU during blocked shutdown, not just wall time.
C21 [B, S]
txnWaiterallocates a channel for every active generation even without waitersMain
pkg/vm/engine/tae/txn/txnbase/txnmgr.go:129-171; v4.2.8:126-169.Addallocates on 0→1 andDonediscards the channel at 1→0, even ifWaitis never called.Create the channel lazily in
Waitwhile holding the existing mutex; close only a non-nil channel on drain. Validate no-wait allocation, wait-before/after-add, multiple waiters, repeated generations, cancellation and race safety. This is a bounded lazy-allocation candidate, not a waiter protocol redesign.C22 [B, S] Watermark SQL construction repeats row serialization and copying
Main
pkg/cdc/watermark_updater.go:1038-1224builds row/predicate strings, copies them into builders, and can serialize the same boundary row twice while deciding whether to split a batch. v4.2.8 additionally usesvalues += fmt.Sprintf(...)at:758-781.Write rows/predicates directly to the destination builder and compute exact escaped lengths for batch accounting. Preserve SQL golden output for quotes/backslashes, the 200-row and 256 KiB boundaries, alias/task predicates, batch ordering and owner fencing. Benchmark 1/200/1000 rows; do not infer allocation merely from
ReplaceAllwhen no special character exists.C23 [C, S] Watermark phase state is split across parallel maps
Main
pkg/cdc/watermark_updater.go:337-354,734-766,2180-2221maintains TS, generation and fence in parallel maps and moves/deletes each key several times during update/flush. v4.2.8 has the phase TS maps without the newer generation/fence maps.Keep the three phases, but store
{ts,generation,fence}as one value per phase so transitions move one record. Do not merge the phases or alter ownership fencing. Validate generation-0 replay, same-generation monotonicity, cross-generation update, uncommitted update during committing, stale owner, failed commit retry, circuit breaker and cleanup under race.C24 [B, S] CDC transaction state duplicates a timestamp and nested lock reads
Main
pkg/cdc/reader_v2_txn_manager.go:34-52,125-158,212-243holds the manager lock while calling tracker getters that take their own locks.reader_v2_state.go:62-78,90-169stores and updates bothtoTsandexpectedWatermark; v4.2.8 has the same structure.First remove the redundant timestamp by deriving its getter from
toTs, and add a single snapshot/range read for paired timestamps. Only consider removing tracker locks after checking allGetTrackerconsumers. Validate leftover rollback, completed-range retry, range replacement, commit/rollback failure and multi-batch watermark updates under race.C25 [B, S] LogService heartbeat grows its replica slice from zero capacity
Main
pkg/logservice/store.go:2050-2101, triggered fromservice_commands.go:260-286; v4.2.8store.go:1292-1334.NodeHostInfois available before the append loop, butReplicasstarts asmake(...,0).Preallocate
len(nhi.ShardInfoList); skipped pending shards only overestimate capacity. Verify empty/single/multi/pending shard protobuf equivalence and nil-map behavior, then benchmark allocation. This is a small safe cleanup, not a high-severity item.C26 [C, S] Deadlock detection builds four/five parallel snapshot slices
Main
pkg/lockservice/txn.go:1552-1571allocates groups, tables, keys, uncertain keys and owner-local snapshots; v4.2.8:640-657has the first four. Their lengths and lifetimes are shared.Use one
[]lockWaitSnapshotwhile preserving fixed-slice reference cleanup, uncertain-map copying and owner-local deduplication. Validate binary/multi-party deadlock, non-deadlock, transaction close, cancellation, legacy table behavior and race. Benchmark single/multi-table cases rather than claiming a fixed allocation win without measurement.C27 [C, S] Proxy response processing repeats packet normalization; main repeats a boundary lock
Main
pkg/proxy/tunnel.go:757-827,1539-1545,1944-1968parses response status for transaction tracking and response-boundary tracking; helpers normalize the first packet again. main also callsresponseMayCarryTxnStatusandtrackServerResponseunder separate boundary-lock acquisitions. v4.2.8 has repeated parsing attunnel.go:405-445,1052-1056,1324-1348without the added main lock duplication.Construct one internal packet view and combine the boundary read/update in one critical section. Preserve OK/ERR/EOF/deprecate-EOF, PREPARE/EXECUTE/cursor/FETCH/FIELD_LIST/LOCAL INFILE, 16 MiB continuation, short EOF-like continuation, split/coalesced packets and sequence errors. Compare all transaction/boundary/migration state under race before claiming throughput improvement.
C28 [B, S] Watermark update repeats key formatting and formats disabled Debug arguments
Main
pkg/cdc/watermark_updater.go:2223-2238computeskey.String()for metrics and again for Debug, plus two timestamp strings; v4.2.8:1159-1174has the same pattern. Reuse the metric label and gate debug-only formatting with the existing debug-enabled mechanism. Verify identical enabled logs and unchanged metrics, and benchmark disabled Debug. This is a small hot-path cleanup.Disposition and next triage
Not counted as established optimizations:
EvalProjectionslice construction before escape/allocation evidence, tracing-disabled cost before tracing implementation/benchmark evidence, and merging MORPC Future channels before cold-versus-pooled allocation evidence.No production source was modified. The C01 probe and C15 benchmarks were local diagnostic overlays. C03 is a complete source-chain finding but still needs its scheduler integration counterexample. Most other entries need their focused behavior/allocation matrix before promotion to a confirmed defect or performance regression. This comment does not claim six hours of completed validation or production-wide coverage; it records the current evidence boundary for continued focused work.
XuPeng-SH commentedon Nov 18, 2026
Verification round 2: C03 reproduced again, C05 measured, C07 narrowed
Snapshots remain
main@87c44445f83e308ef12dd7ca0e570cec1e6690d9/v4.2.8@10d204b8763f19b2b37ba2147d1d4c1a7828d6d4. All new probes were local diagnostic overlays; no production source changed.C03 is already tracked by #32428; independent latest-main control fails as predicted
A duplicate search found the existing #32428: TAE merge scheduler ignores denied memory reservations and releases another in-flight task's quota. No duplicate issue was filed.
I independently revalidated the same path with two identical tasks (
eSize=865103600), holding A while completing B:The tested checkout's merge/throttler files were verified identical to the main snapshot above. Raw revalidation note: #32428 (comment). This remains an admission/accounting reproduction, not a physical-OOM claim.
C05 now has exact storage-range evidence and an allocation/latency tradeoff matrix
A fake
ObjectStoragerecorded actual ranges while comparing the ordinary envelope path with the already-existingreadEntriesIndividuallyfallback. Both paths returned identical entry bytes.Two 4 KiB entries were placed at offsets 0 and 16 MiB:
Adjacent-entry controls both transported 8192 bytes; the envelope used one read and the individual path used two.
Controlled local microbenchmark, Go 1.27.1, darwin/arm64, Apple M4, 30 iterations per arm:
This supports applying the existing sparse-envelope guard before the ordinary range read; it does not support always splitting reads. The adjacent control retains the envelope advantage in request count and allocations.
B/opis allocated bytes in this microbenchmark, not live heap or a leak measurement.C07 must be narrowed; the earlier high-priority formulation was too broad
The NULL-fallback probe confirmed that
decimalTypedExecutorre-enters each generic root parameter once after its initial raw-column reads. However, the fallback occurs before specialized arithmetic, so the earlier wording did not establish recomputation of completed Decimal arithmetic chains. Do not implement a new prepared-parameter evaluation API solely on that earlier claim.The same probe produced a separate local performance counterexample for the simple
decimal64 -> decimal128 CASTfollowed by+shape, with 8192 rows:Therefore:
These are focused local results, not production-wide latency claims. They replace the corresponding preliminary disposition in the preceding 29-candidate catalog.
XuPeng-SH commentedon Nov 18, 2026
Correction: C07 is rejected as an optimization candidate
The single-run Decimal timing in verification round 2 was not reproducible. I reran the exact original benchmark in a fresh process with
-count=3, then ran the operator × row-count × NULL matrix with-count=3.Exact original benchmark, 8192 rows:
Thus the earlier statement that the typed fast path was slower in this shape is withdrawn. In the repeated run it was faster, while NULL fallback showed no consistent specialized/generic overhead. The wider
+,-,*× 256/8192-row matrix likewise did not establish a stable specialized-path regression; the one-run counterexamples disappeared or changed direction on repetition.The source-level fallback reentry observation remains true, but it only established repeated cheap setup/raw-column reads before fallback, not recomputation of completed Decimal arithmetic or a measured performance penalty. Therefore:
EvalFromPrepared-style API on this evidence.This correction does not change the C03 accounting reproduction or the C05 storage-range/allocation results.
XuPeng-SH commentedon Nov 18, 2026
Verification round 3: seven candidates validated, two direct rewrites rejected
Local checkout:
main@517e1695388cbaf1135238d5ab0c19a4556fb551. The production files used for these probes were checked byte-identical to the earliermain@87c44445f83e308ef12dd7ca0e570cec1e6690d9snapshot. All implementations below are temporary diagnostic overlays, not committed patches. The checkout remains unmodified.Numbers are local
darwin/arm64, Apple M4 results. Benchmarks used fresh processes and-count=3; medians below are diagnostic, not production latency claims.1. C03: merge execution now has a complete acquire/execute/release ownership probe
The previously reported scheduler/throttler contract break is reproduced independently of the throttler test helper:
865103600bytes.Acquire, but the current scheduler still executes B and releases A's reservation:865103600 -> 0.Diagnostic fix: acquire before execution; skip execution on denial without releasing; if executor admission fails after a successful acquire, roll back exactly once. Focused denial/grant/executor-failure tests and the complete
pkg/vm/engine/tae/db/mergepackage passed, including-race.This is a correctness/ownership fix, not a tuning heuristic. Existing issue: #32428.
2. C04: merge memory estimation can use the table's actual
BlockMaxRowsCurrent
mergesort.EstimateMergeSizehard-codes 8192 rows, while merge execution usesschema.Extra.BlockMaxRows. This makes admission estimation disagree with execution for tables with non-default block capacity.Diagnostic change:
EstimateMergeSizeWithBlockRows; keep the old function as the default-8192 wrapper.GetBlockMaxRowsthroughcatalog.MergeTable/TNMergeTableand pass it through scheduler admission and merge-start estimation.objectio.BlockMaxRows.Focused cases verified default-output equality for row counts
0, 1, 1000, 2000, 8192, 8193, 10000, 16384. A 2000-row/16-MiB object with capacity 1000 lowers the block-read term by exactly1000 * ((16<<20)/2000) * 2; a 10000-row/80-MiB object with capacity 10000 raises it by(10000-8192) * ((80<<20)/10000) * 2.Complete
mergesort,db/merge, andcatalogpackages passed normally and with-race. This validates the estimate plumbing and arithmetic; it does not yet claim a measured production peak-memory reduction.3. C05: sparse S3 ranges need a selective guard, not universal splitting
The earlier executable example remains:
16781312-byte envelope read instead of8192bytes through individual reads.2379457 ns/op,36234817 B/opfor the envelope versus11567 ns/op,23617 B/opfor individual reads.The sparse-only diagnostic guard passed Data, partial-cache-hit, Writer, and ReadCloser cases. Complete
pkg/fileservicepassed normally (33.326s) and with-race(51.809s). This remains a storage/memory investigation result, not proof that the original merge heap sample was entirely read amplification.4. C09: pipeline decoding can reuse the already parsed stable boundary
UnmarshalBinaryForPipelinealready computesstableBatchPayloadLength, thenUnmarshalBinaryWithPrepareParamKindsrepeats the same envelope walk. The diagnostic refactor adds an internalunmarshalBinaryWithPrepareParamKindsAtPrefix; public wrappers and wire bytes are unchanged.Equivalence and truncated-input probes passed. Complete
pkg/container/batchpassed normally and with-race. This is a modest CPU cleanup, not a memory-allocation optimization.5. C20: replace
OpWorker.WaitStopbusy polling with a condition variableWith one pending operation and
WaitStopblocked for one second:979.707 msprocess CPU.0.170 msprocess CPU.The overlay signals only when pending reaches zero and keeps the wait predicate in a loop. Complete
pkg/vm/engine/tae/tasks/workerpassed normally (1.627s) and with-race(2.598s). An unrelatedpkg/sql/colexecrun was cancelled and is not used as evidence for this worker change.6. C21: allocate
txnWaiternotification state only when a waiter existsLazy channel/state creation preserves cancellation and waiter-generation behavior in focused equivalence tests. No-wait generation microbenchmark:
26-32 ns/op,112 B/op, 1 allocation.6.3-6.9 ns/op,0 B/op, 0 allocations.The complete
pkg/vm/engine/tae/txn/txnbasepackage and focused race tests passed. This is a fast-path allocation reduction; it does not claim a workload-wide latency improvement.7. C25: preallocate LogService heartbeat replica capacity
Move replica-slice allocation after
GetNodeHostInfoand uselen(nhi.ShardInfoList)as capacity. Pending shards only make the capacity an overestimate; contents and nil-map behavior are unchanged in the focused checks.Complete
pkg/logservicepassed normally (132.077s) and with-race(132.830s). This is a small, independently deliverable cleanup, not a high-severity item.Rejected direct rewrites: do not promote C17 or C22
C17: row-at-a-time low-precision float output is rejected
Removing the whole-column BF16/FLOAT16/FLOAT8/FLOAT4 widened buffer does reduce the 8192-row conversion from
32800 B, 3 allocsto8 B, 1 alloc, but repeated benchmarks show a substantial CPU regression:Four repeated reads per row were roughly 2.4-5.5x slower. Value, NULL, const, NaN/Inf and extraction-equivalence probes passed, but that only proves correctness. The existing whole-column conversion amortizes dispatch and is the better default; the proposed row-wise rewrite is withdrawn.
C22: direct watermark SQL builder is rejected as a general optimization
A direct-builder prototype produced byte-identical SQL for 1/199/200/201/1000 rows, special characters, task deduplication and the max-SQL-size flush boundary. It reduced bytes and ordinary-path allocation counts, but was consistently slower and regressed allocations for escaped strings:
48.1 us -> 55.3 us;127.6 KB -> 108.5 KB; 268 -> 40 allocs.253.2 us -> 278.9 us;588.0 KB -> 496.8 KB; 1146 -> 130 allocs.61.8 us -> 76.7 us; 692 -> 816 allocs.289.9 us -> 354.3 us; 2861 -> 3473 allocs.The extra length/escape scans are not justified by the 10-15% byte reduction. Keep the current builder; do not replace it with this direct version.
Disposition
perf: streamline pipeline decoding and heartbeat replicas (#32918)
fix: park TAE worker shutdown and defer waiter allocation (#32915)
perf: reduce CDC watermark and persisted PK check overhead (#32939)
fix(taskservice): unblock async completion on runner shutdown (#33040)
fix: account for merge block capacity and avoid sparse S3 overreads (#…
docs(skills): strengthen upgrade compatibility checks (#33712)