Skip to content

[Refactoring]: Simplify MatrixOne runtime architecture and resolve design debt across 4.2 and main #32278

Open
9 of 26 issues completed

Description

@XuPeng-SH

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.x patch candidate from the latest generally available 4.2.x release that precedes it. For a new release line cut from main, such as 5.0, use the latest generally available 4.2.x at target release time. Pin the official source artifact, commit and persisted catalog identity for each validation run. Repeat the check if a newer 4.2.x ships 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 catalog Version, 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/1 is 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 READY catalog, 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 used 57e7871e500e6e3d35fd352a092ee41b03a979fc; 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 was f3c72c6bf90c402e147197991fc8fd29c8c3c056, 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.

Sub-issues

Sub-issues

9 of 26 Issues completed
Loading 26 sub-issues

Activity

  1. self-assigned this
    on Nov 5, 2026
  2. added theissue type on Nov 5, 2026
  3. 15 remaining items

  4. XuPeng-SH commented on Nov 18, 2026

    @XuPeng-SH
    ContributorAuthor

    Focused main/v4.2.8 drift campaign: 29 concrete optimization candidates

    Snapshots: main@87c44445f83e308ef12dd7ca0e570cec1e6690d9, v4.2.8@10d204b8763f19b2b37ba2147d1d4c1a7828d6d4, merge-base 2758eb1d3f812759c03c7c8a7463e2757dacb633.

    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:

    • R: focused behavior reproduced locally.
    • M: local diagnostic microbenchmark executed; not production latency.
    • S: source path/control flow confirmed; performance or final SQL disposition still needs the named probe.
    • A/B/C: main-introduced mechanism / shared baseline debt / baseline debt amplified on main. Provenance is not severity.

    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 acquired

    Main:

    • pkg/vm/engine/tae/db/merge/scheduler.go:1273-1278 calls ExecuteFor, then calls rc.Acquire(eSize) but ignores both return values, and always executes AddTask/Admit after executor acceptance.
    • pkg/common/rscthrottler/resource_throttler.go:600-620 returns granted=false without incrementing reserved when avail < ask.
    • pkg/vm/engine/tae/db/merge/scheduler.go:216-224 releases eSize when the task completes.

    v4.2.8 has the same ignored result at scheduler.go:1267-1272 and denial path at resource_throttler.go:602-617.

    A source-derived counterexample is:

    1. A acquires 60 and owns a reservation of 60.
    2. B asks for 60 with only 40 available. Acquire returns false and leaves A's 60 reserved.
    3. The scheduler still runs and admits B.
    4. B completes and releases 60. reserved becomes 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: controlTaskMemInPlace stops shrinking at one object and trigger.assigns retains 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 legacy OnMergeDone paths. Then test the 100-available/three-60-estimate batch without assuming every Acquire succeeds.

    C04 [B, S] Merge estimation is disconnected from actual block capacity

    pkg/vm/engine/tae/mergesort/task.go:524-541 hard-codes 8192 rows and mixes input, transfer and GC margins. Actual buffers use schema.Extra.BlockMaxRows (tables/jobs/mergeobjects.go:192-194, mergesort/task.go:266-279). v4.2.8 has the same formula at task.go:547-564.

    For BlockMaxRows=16384, the estimate's main byte terms can be approximately 1.75*S + 30*R, while one input plus one output block is approximately 2*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-1250 checks expensiveMinimalRangeRead only on the full-object streaming fallback. The ordinary non-full-object range path goes directly from readRange to one getContent/io.ReadAll over [minOffset,maxEnd). The range calculation is at pkg/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, WriterForRead and ReadCloserForRead, with identical returned bytes.

    C06 [B, S] S3ReadSize does not measure physical S3 bytes

    Main pkg/fileservice/s3_fs.go:1044-1066 accumulates requested entry sizes; actual transport bytes are already counted at :1171-1193, but only sent to S3ReadIOBytesHistogram. 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] appendPrepareSchemas is quadratic, but an unconditional high-allocation index is not the right fix

    Main pkg/sql/plan/build_dcl.go:663-688; v4.2.8 build_dcl.go:415-440. Every new dependency scans all retained dependencies and performs snapshot proto.Equal checks.

    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.

    D Variant ns/op B/op allocs/op
    128 baseline 63,208 2,168 8
    128 slice-index 13,740 44,488 270
    128 compact-index 16,069 51,272 14
    512 baseline 1,055,364 9,336 10
    512 slice-index 55,212 181,448 1,040
    512 compact-index 63,438 206,024 16
    2,048 baseline 16,598,792 48,248 13
    2,048 slice-index 249,609 736,697 4,127
    2,048 compact-index 259,120 835,000 31

    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.Equal and 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 1 probe passed for an ordinary plan and failed for a dependent plan: CatalogDependencies retained customer in both, but the privilege carrier survived only the ordinary path. customer remained non-executable. The source consumer is Query.Nodes-based extractPrivilegeTipsFromPlan.

    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-700 validates 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-6558 consecutively calls the passes in window_binder.go:49-96 and :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-1189 repeatedly calls hasCorrCol and exprHasColRef for 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-642 sets ViewMetadataDependsOnUdf; pkg/frontend/mysql_cmd_executor.go:4530-4534 immediately returns changed=true, reaching rebuild at :6291-6312. v4.2.8 does not have this coarse UDF entry.

    Repeated SHOW CREATE VIEW for 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 from session.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-888 creates a full []float32; getters later consume it row by row at :599-610. mysql_protocol.go:412-425 converts each batch before writing. v4.2.8 does not have these low-precision output branches.

    Retain the typed source and perform ToFloat32 at 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-9877 calls hasMoCtrl, isTargetSysWhiteList, then extractPrivilegeTipsFromPlan; authenticate2.go:242-268 adds expression traversal. UPDATE/DELETE also precomputes targets before the main scan at authenticate.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_inject placements, 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-3259 marshals all keys, constructs base/block filters, creates a search closure and allocates cache vectors before the len(candidateBlks)>0 guard at :3261. The tombstone branch at :3343 uses tombstonePKExistsInRange, 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-2057 calls findAggNodeBelow(first.Children[0]) at :2037 and 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-140 evaluates left/right, then on const, NULL, shape or kernel rejection calls root.Eval. FunctionExpressionExecutor.Eval evaluates its parameter executors again at evalExpression.go:1949-1997. The chain path has the same structure at evalExpressionDecimalChain.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 in evalExpressionSubjectReuse.go:37-96,108-169,267-335, entered from filter/filter.go:123 and table_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-92 calls stableBatchPayloadLength, then UnmarshalBinaryWithPrepareParamKinds; the latter repeats the length parse at batch.go:686-692. The parser visits vector, attribute and ExtraBuf fields at batch.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-375 maintains 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.Reset recursively walks the same scope tree twice

    Main pkg/sql/compile/compile.go:394-427 resets scopes, then UpdateScopeTxnOffset at :423-425 walks them again (:530-540); main additionally visits operators for Apply even though resetForReuse already has an operator walk. v4.2.8 has the repeated scope traversal at compile.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.WaitStop busy-spins until pending work drains

    Main and v4.2.8 pkg/vm/engine/tae/tasks/worker/worker.go:157-189 spin on Pending at :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] txnWaiter allocates a channel for every active generation even without waiters

    Main pkg/vm/engine/tae/txn/txnbase/txnmgr.go:129-171; v4.2.8 :126-169. Add allocates on 0→1 and Done discards the channel at 1→0, even if Wait is never called.

    Create the channel lazily in Wait while 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-1224 builds 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 uses values += 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 ReplaceAll when 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-2221 maintains 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-243 holds the manager lock while calling tracker getters that take their own locks. reader_v2_state.go:62-78,90-169 stores and updates both toTs and expectedWatermark; 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 all GetTracker consumers. 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 from service_commands.go:260-286; v4.2.8 store.go:1292-1334. NodeHostInfo is available before the append loop, but Replicas starts as make(...,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-1571 allocates groups, tables, keys, uncertain keys and owner-local snapshots; v4.2.8 :640-657 has the first four. Their lengths and lifetimes are shared.

    Use one []lockWaitSnapshot while 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-1968 parses response status for transaction tracking and response-boundary tracking; helpers normalize the first packet again. main also calls responseMayCarryTxnStatus and trackServerResponse under separate boundary-lock acquisitions. v4.2.8 has repeated parsing at tunnel.go:405-445,1052-1056,1324-1348 without 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-2238 computes key.String() for metrics and again for Debug, plus two timestamp strings; v4.2.8 :1159-1174 has 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

    • Immediate correctness/ownership investigation: C03, C01, C07.
    • High-value controlled performance/memory probes: C05, C04, C14, C11, C08, C09, C10.
    • Measured scaling work with an explicit allocation tradeoff: C15.
    • Small independent cleanups: C02, C17, C21, C25, C28, C29; these should not be inflated into architectural programs.
    • Concurrency/protocol changes requiring the strongest matrices: C19, C20, C23, C24, C26, C27.

    Not counted as established optimizations: EvalProjection slice 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.

  5. XuPeng-SH commented on Nov 18, 2026

    @XuPeng-SH
    ContributorAuthor

    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:

    granted_control: denied=0, after B: reserved=865103600  PASS
    denied_second:   denied=1, executor attempts=2,
                     after B: reserved=0                  FAIL
                     expected A's 865103600, actual 0
    

    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 ObjectStorage recorded actual ranges while comparing the ordinary envelope path with the already-existing readEntriesIndividually fallback. Both paths returned identical entry bytes.

    Two 4 KiB entries were placed at offsets 0 and 16 MiB:

    ordinary envelope: 1 read,  [0,16781312), transport=16781312 bytes
    individual reads:  2 reads, [0,4096) + [16777216,16781312), transport=8192 bytes
    requested payload: 8192 bytes
    

    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:

    Layout Path ns/op B/op allocs/op
    sparse envelope 2,379,457 36,234,817 54
    sparse individual 11,567 23,617 58
    adjacent envelope 4,138 19,384 33
    adjacent individual 4,146 23,617 58

    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/op is 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 decimalTypedExecutor re-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 CAST followed by + shape, with 8192 rows:

    Input Executor ns/op B/op allocs/op
    non-NULL generic 28,598 0 0
    non-NULL specialized typed 46,408 16 1
    one NULL, forcing generic fallback generic 31,392 16 2
    one NULL, forcing generic fallback specialized typed 36,912 16 2

    Therefore:

    1. Fallback reentry is real, but the demonstrated extra work is much narrower than the original C07 wording.
    2. The typed specialization is not universally faster; this shape was slower even without fallback.
    3. C07 is downgraded from an immediate optimization to a benchmark/dispatch investigation. The next useful matrix is operator × row count × NULL/const/dictionary shape, with result equality and existing generic kernels as the baseline.

    These are focused local results, not production-wide latency claims. They replace the corresponding preliminary disposition in the preceding 29-candidate catalog.

  6. XuPeng-SH commented on Nov 18, 2026

    @XuPeng-SH
    ContributorAuthor

    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:

    non-NULL generic:      11681, 11606, 11570 ns/op
    non-NULL specialized:   4989,  5035,  5042 ns/op
    
    NULL-fallback generic: 13483, 13517, 13422 ns/op
    NULL-fallback typed:   13463, 13372, 13458 ns/op
    

    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:

    • C07 should not be promoted to a code change.
    • Do not add an EvalFromPrepared-style API on this evidence.
    • The preceding single-run timing table and C30-like dispatch hypothesis are not accepted findings.
    • The active candidate count is now 28, not 29; C07 is retained only as a rejected/calibration record.

    This correction does not change the C03 accounting reproduction or the C05 storage-range/allocation results.

  7. XuPeng-SH commented on Nov 18, 2026

    @XuPeng-SH
    ContributorAuthor

    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 earlier main@87c44445f83e308ef12dd7ca0e570cec1e6690d9 snapshot. 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:

    • Task A acquires a live reservation of 865103600 bytes.
    • Task B is denied by Acquire, but the current scheduler still executes B and releases A's reservation: 865103600 -> 0.
    • The granted control preserves A's reservation.

    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/merge package 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 BlockMaxRows

    Current mergesort.EstimateMergeSize hard-codes 8192 rows, while merge execution uses schema.Extra.BlockMaxRows. This makes admission estimation disagree with execution for tables with non-default block capacity.

    Diagnostic change:

    • Add EstimateMergeSizeWithBlockRows; keep the old function as the default-8192 wrapper.
    • Expose GetBlockMaxRows through catalog.MergeTable/TNMergeTable and pass it through scheduler admission and merge-start estimation.
    • Zero capacity falls back to 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 exactly 1000 * ((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, and catalog packages 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:

    • Two 4-KiB entries, 16 MiB apart, produce one 16781312-byte envelope read instead of 8192 bytes through individual reads.
    • Sparse microbenchmark: 2379457 ns/op, 36234817 B/op for the envelope versus 11567 ns/op, 23617 B/op for individual reads.
    • Adjacent-range controls still favor the envelope path, so splitting every read would be the wrong fix.

    The sparse-only diagnostic guard passed Data, partial-cache-hit, Writer, and ReadCloser cases. Complete pkg/fileservice passed 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

    UnmarshalBinaryForPipeline already computes stableBatchPayloadLength, then UnmarshalBinaryWithPrepareParamKinds repeats the same envelope walk. The diagnostic refactor adds an internal unmarshalBinaryWithPrepareParamKindsAtPrefix; public wrappers and wire bytes are unchanged.

    Shape Baseline median Single-parse median Allocation
    128 vectors x 1 row 17986 ns/op 17281 ns/op 65317 B, 258 allocs: unchanged
    8 vectors x 8192 rows 1129 ns/op 1067 ns/op 4048 B, 18 allocs: unchanged

    Equivalence and truncated-input probes passed. Complete pkg/container/batch passed normally and with -race. This is a modest CPU cleanup, not a memory-allocation optimization.

    5. C20: replace OpWorker.WaitStop busy polling with a condition variable

    With one pending operation and WaitStop blocked for one second:

    • Current polling: 979.707 ms process CPU.
    • Condition-variable overlay: 0.170 ms process CPU.

    The overlay signals only when pending reaches zero and keeps the wait predicate in a loop. Complete pkg/vm/engine/tae/tasks/worker passed normally (1.627s) and with -race (2.598s). An unrelated pkg/sql/colexec run was cancelled and is not used as evidence for this worker change.

    6. C21: allocate txnWaiter notification state only when a waiter exists

    Lazy channel/state creation preserves cancellation and waiter-generation behavior in focused equivalence tests. No-wait generation microbenchmark:

    • Current: about 26-32 ns/op, 112 B/op, 1 allocation.
    • Lazy overlay: about 6.3-6.9 ns/op, 0 B/op, 0 allocations.

    The complete pkg/vm/engine/tae/txn/txnbase package 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 GetNodeHostInfo and use len(nhi.ShardInfoList) as capacity. Pending shards only make the capacity an overestimate; contents and nil-map behavior are unchanged in the focused checks.

    Input shards Current Preallocated
    1 144 B, 1 alloc 144 B, 1 alloc
    8 237 ns, 2160 B, 4 allocs 109 ns, 1152 B, 1 alloc
    64 1375 ns, 19056 B, 7 allocs 635 ns, 9472 B, 1 alloc
    256 5090 ns, 80496 B, 9 allocs 2609 ns, 40960 B, 1 alloc

    Complete pkg/logservice passed 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 allocs to 8 B, 1 alloc, but repeated benchmarks show a substantial CPU regression:

    Type, convert + one read/row Current median Row-wise median
    BF16 22434 ns 32844 ns
    FLOAT16 31367 ns 44567 ns
    FLOAT8 49385 ns 76740 ns
    FLOAT4 25172 ns 41016 ns

    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:

    • 200 ordinary rows: about 48.1 us -> 55.3 us; 127.6 KB -> 108.5 KB; 268 -> 40 allocs.
    • 1000 ordinary rows: about 253.2 us -> 278.9 us; 588.0 KB -> 496.8 KB; 1146 -> 130 allocs.
    • 200 escaped rows: about 61.8 us -> 76.7 us; 692 -> 816 allocs.
    • 1000 escaped rows: about 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

    • Independently actionable candidates: C03, C04, C05, C09, C20, C21, C25. They should remain separate focused changes, not one combined patch.
    • Rejected/calibration records: C07, C17, C22. No code change should be promoted from the tested versions.
    • Remaining source-only candidates are not promoted by this comment. In particular, no memory or latency claim is made for C02, C19, or C29 without their named probes.
    • Production merge peak-memory improvement still requires an end-to-end merge benchmark/profile; the C04 arithmetic and C05 storage probes are necessary evidence but not a substitute for that measurement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions