Repository navigation
fix(window): reuse full and cumulative RANGE aggregates - #31553
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 83992d44848b1dcc6a749860632e9f97cbdda854
Assessment: approve
Reviewed the complete delta, linked issue, discussion and affected consumers. The optimization coherently reuses existing aggregate and cleanup owners while preserving frame semantics and fallbacks. No actionable findings or substantive discussion disputes remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1
Validation:
-
Complete aggexec and window packages passed normally and under -race; every changed behavioral test ran and passed.
-
Thirty additional integer/decimal snapshot cases matched fresh prefix aggregation exactly, including NULLs and cleanup.
-
Verified native provenance, unchanged frozen source, and command/source/exit receipts against retained logs. Evidence mapping: /home/xupeng/.local/state/mo-bot/jobs/403e51fb11a5655723ab8e77/attempt-1/review-validation.json.
-
Saved review-plan.md, review-notes.md and complete discussion-assessment.json; final audit passed.
Limitations:
-
Frozen CI remains pending. Author-reported SQL BVT, stress repetitions and performance measurements were not independently reproduced.
-
Two existing allocation-measurement tests intentionally skipped race instrumentation; both passed normally.
## What type of PR is this? - [ ] API-change - [x] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #28109 and #28110. ## What this PR does / why we need it: Jinpan AP queries can repeatedly aggregate the same full window partition or evaluate a filtering OR of correlated EXISTS with expensive MARK joins. Extend the full-partition reuse introduced in #31553 to multiple partitions, evaluating ordinary aggregates only for the output partitions needed and reusing each result across output chunks. Rewrite eligible EXISTS disjunctions as a shared-key hash SEMI join over UNION ALL, with branch-specific residual predicates. Unsupported frames, aggregates, predicates, and subquery shapes keep the existing path. Validation: - Full `pkg/sql/colexec/window` and `pkg/sql/plan` Go test suites, including TPC-H plan tests; window package under `-race`. - Embedded SQL integration covering window aggregates, duplicates, NULL keys, mixed EXISTS, and physical hash-join plans. - `go vet`, formatting, and changed-line lint on the affected packages. - The previously failing `TestCheckConstraintNamespace` passed locally with package coverage enabled. The previous full CI coverage failure did not yield a coverage verdict; new CI remains authoritative. A [Jinpan replay](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/40651930820) of the pre-rebase candidate `2f114269a109aecb622c15be6bfd8814b3f76686` completed q1021 in 1.03 s (500 rows) and q1143 in 51.63 s (2,000 rows). In a [previous run](https://github.com/matrixorigin/mo-nightly-regression/actions/runs/40635601332), both timed out at 1,800 s. These are single runs on different commits/environments; the replay did not compare results against a golden dataset, and the rebased head has not yet been replayed on Jinpan. TPC-H and TPC-DS runtime performance have not been measured for this change. Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
…31941) ## What type of PR is this? - [ ] API-change - [ ] BUG - [ ] Improvement - [ ] Documentation - [x] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #29945 ## What this PR does / why we need it: MatrixOne had no exponentially weighted window statistics. Issue #29945 asks for the pandas-style `ewm` family at the SQL level: `ewmMean`, `ewmVar`, `ewmStd`, `ewmCov` and `ewmCorr` over a window frame, with `alpha` (or the string tag `halflife`) decay and the constant policies `adjust`, `ignoreNA` and `minPeriods`. Before this change none of the pipeline stages knew about these functions, so users had to pull the data out and post-process it. The change adds the whole path, and each stage needed its own repair because the general window machinery could not express this family: - No grammar existed for the five names or for a window function whose first argument is a value column followed by positional configuration arguments (`pkg/sql/parsers/dialect/mysql/keywords.go`, `mysql_sql.y`, `mysql_sql.go`): the parser now accepts the 2-7 argument positional forms, with `halflife` as a string literal decay tag and the names kept identifier-compatible. - The bound window spec carried only the function name, so the policies had no safe transport. Binding window policies as folded plan literals would silently clamp execution-dependent values (`second(current_timestamp()) = 1`) and over-wide decimals to one compile-time value and would let constant folding hide the dependency from the cache gates. `pkg/sql/plan/window_binder.go` (with `query_builder.go`, `utils.go`, `function/function.go`, `function_id.go`, `list_window.go`) binds constant alpha/halflife/policies immediately, keeps marker-decay and execution-dependent arguments unfolded, types the decay/policy argument positions, deduces the EWM outputs as nullable float64, and classifies execution-dependent EWM plans so the frontend can exclude them from both the prepare-compile cache and the mixed-runtime specialization cache (`pkg/frontend/computation_wrapper.go`, `types.go`). - `minPeriods` had no typed resolution path: a fractional constant would be silently truncated to an integral threshold and a value above int32 was rejected outright. `pkg/sql/compile/operator.go` now resolves `minPeriods` in the original plan type (`bool` to 0/1; integral integer spellings carried exactly; float64 required integral and finite; decimal64/128/256 tested with the exact raw significand-vs-scale remainder, so no fractional spelling can slip through, including the 65-digit fraction that float64 alone would round to one), saturates above-int64 values at `math.MaxInt64`, and rejects non-finite policy constants (NaN/+Inf/-Inf) with the family error. - The indexed window operator assumed a query-scoped constant specification and could not accept configuration per execution, which prepared statements need. `pkg/sql/colexec/window/ewm_dispatch.go` admits the per-execution configuration into the priority-queue container ahead of any allocation (capacity and ordering errors leave no partial state), emits each peer group exactly once, preserves partition isolation, and honors the bounded cancellation contract; `pkg/sql/colexec/aggexec/ewm_config.go` carries the resolved `EwmConfig{Mode, Alpha, HalfLife, Adjust, IgnoreNA, MinPeriods}` across the operator boundary with a strict length-gated decode. The `pkg/sql/colexec/window/ewm` engine evaluates the adjust/ignoreNA recurrences for mean, variance, covariance and correlation in row and event-time modes, publishes NULL while the running observation count is below `max(1, minPeriods)`, and computes correlation with the zero-variance rule (NULL rather than a divide by zero). - Arrays of expected SQL semantics are frozen in `test/distributed/cases/window/ewm_statistics.sql` / `ewm_statistics.result`: profile vectors (e.g. values 1,2,3,4 with alpha=.5, adjust=false publish 1, 1.5, 2.25, 3.125), partitions, ties, all-NULL and NULL-clock inputs, constant signals, pair statistics with the zero-variance rule, the event-time corpus, `minPeriods` boundary and rejection blocks, constant/non-integer policy rejections with session recovery (`SELECT 1` after each error), prepared marker forms, and regression rows for AVG/var_pop/stddev_pop beside the new functions. Validation (issue #29945 -> tests): - Grammar: `pkg/sql/parsers/dialect/mysql` `TestEwmWindowFunctionGrammar` (all five names, decay/halflife/policy forms parse; invalid arities and bare usage reject) and `TestEwmNamesRemainIdentifierCompatible`. - Binding: `pkg/sql/plan` `TestEwmBinderRejections` and `TestEwmBinderAcceptances` (the constant-policy catalog: non-constant or out-of-range alpha, boolean-typed policy positions, wrong arities all reject), `TestEwmMarkerDecayBindsDecimal256HalfLife`, `TestEwmDomainlessNullSamplesBindAsFloat64`, `TestEwmWindowOutputsRemainNullable`, `TestEwmRealTimeConfigClassifiesExecutionDependent`. - Configuration: `pkg/sql/compile` `TestConstructEwmConfig` (valid forms and the invalid families), `TestConstructEwmConfigMinPeriodsIntegrality`, `TestConstructEwmConfigMinPeriodsUpperBound`, `TestConstructEwmConfigNonFinitePolicy`, `TestValidateEwmWindowConfigsAfterModeResolution` (event-time mode requires one ascending numeric ORDER BY key). - Wire: `pkg/sql/colexec/aggexec` `TestEwmConfigRoundTrip`, `TestEwmConfigDecode` (the widened record round-trips at `MinPeriods` 2147483648 and math.MaxInt64). - Operator and engine: `pkg/sql/colexec/window` `TestEwmDispatchSplitPeerExactlyOnce`, `TestEwmDispatchPartitionIsolation`, `TestEwmDispatchLimitThenResetResumesFromScratch`, `TestEwmDispatchErrorThenCleanReuse`, `TestEwmDispatchCancellationMidGroup`, `TestEwmDispatchConfigChannelDrivesRows`, `TestEwmDispatchDecimalKeys`, `TestEwmDispatchEventIgnoreNAPartitionsIndexLocally`, `TestEwmDispatchPeerDirectoryAdmission`; `pkg/sql/colexec/window/ewm` `TestOracleVectors` (204 frozen expectation vectors, bit-exact), `TestEvaluatorSliceResumability`, `TestNonFiniteSampleRejection`, `TestKeyDomainRules`, `TestEventTimeNullInstantClock`, `TestMergePhaseCancellation`, `TestDdsumResidualCancellation`. - Frontend: `pkg/frontend` `TestShouldCachePrepareCompileRejectsEwmParameter`, `TestPreparedEwmDisablesMixedRuntimeSpecializationCache`, `TestPreparedEwmMarkerDecayKeepsRowModeOrderLatitude`, `TestPreparedEwmRealTimeConfigIsExcludedFromBothCaches`. - User-visible SQL behavior: `test/distributed/cases/window/ewm_statistics.sql` (377 mo-tester statements). The expected result was regenerated against a launched development instance and then verified with two clean comparison runs at rate=100 (368/368 statements each, error file empty). The committed `.result` file extends the previously accepted result with insertion-only edits (a mechanical comparison of the file against its predecessor reports zero replaced or deleted lines). Regression proof for the `minPeriods` defect (the routed family existed neither in grammar nor engine before this change, so the pre-fix witness is the SQL probe): on the parent tree the same probe silently published rows for fractional `minPeriods` constants (a threshold of 2 became an effective 1), published NULL rows for an -1 float bound, and raised error 20301 for the 2147483648 spelling; the identical `.sql` case file now publishes the exact profile for the integral 2.0 bound, returns the family error for every fractional/non-finite spelling while the session stays usable, and carries 2147483647/2147483648/4611686018427387905 exact. The pre-fix unit-level run of `TestConstructEwmConfigMinPeriodsIntegrality` failed during fixture construction ("can't be converted to Decimal64(18,18)") because the cast-bound decimal fixtures are also introduced by this change; the integrality acceptance itself is witnessed by the SQL probe above. Both tests are green on the final tree. Focused test commands (single-package batches, run from the repository root on the committed tree): GOEXPERIMENT=simd CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \ go test -mod=readonly -count=1 -timeout=20m -run 'Ewm' github.com/matrixorigin/matrixone/pkg/sql/compile GOEXPERIMENT=simd CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \ go test -mod=readonly -count=1 -timeout=20m -run 'Ewm' github.com/matrixorigin/matrixone/pkg/sql/colexec/aggexec GOEXPERIMENT=simd CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \ go test -mod=readonly -count=1 -timeout=20m -run 'Ewm' github.com/matrixorigin/matrixone/pkg/sql/colexec/window GOEXPERIMENT=simd CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \ go test -mod=readonly -count=1 -timeout=20m github.com/matrixorigin/matrixone/pkg/sql/colexec/window/ewm Each of the four batches reports `ok` (exit 0) on the committed tree. The parser, plan and frontend packages were also green in focused batches during development and are byte-identical in this commit. The BVT comparison runs are performed with the repository's standard mo-tester flow on a locally launched development instance (launch config under a scratch directory, MySQL on an isolated port, both `ewm_stat` databases dropped after the run and the service stopped with its listeners released). Residual risks and limitations: - The five new names are window-only: bare calls error, and every error case in the BVT leaves a usable session (verified with recovery rows). - Spelled `decimal(M)` grammar caps M at 65, so the widest *spelled* precision usable in a constant policy is decimal(65,x). Bare plain numeric literals up to 76 digits bind into the DECIMAL256 carrier and are accepted, which is why the integral `minPeriods` test is implemented over raw decimal256 significands (a fraction that float64 rounds to one still rejects), not over a float64 interpolation. - `minPeriods` spellings above int64 saturate at math.MaxInt64 instead of erroring (the gate then publishes NULL), which follows the design's "no upper limit" rule. - Event-time decay computes one exact per-instant transcendental per distinct key; the focused benchmarks in `pkg/sql/colexec/window/ewm/bench_test.go` record both modes (row decay at ~0.67us/row over one-row peer groups; event-time distinct instants at ~70us/row). - The window configuration record widened (24 -> 28 bytes) with the same version tag; decode uses a strict length gate so a mixed-version session degrades rather than misinterprets. - Broader package suites (for example the full `pkg/sql/...` tree and the complete distributed BVT set) are left to CI; this PR's focused proofs cover each stage of the new family plus the AVG/variance regression rows in the new BVT file. ### Rebase onto main (2026-10-31) — conflict resolution and validation Mergify's `Rule: Auto update branch (update)` failed because main had advanced and the branch reported `mergeStateStatus=DIRTY`. The branch was rebased onto current `main` (`4f894474ad10e1b9dc338868145a118a71c1fa23`, 270 commits ahead of the old base) with semantic resolution of the overlapping features that landed for the sibling window-kernel families: - **Function IDs**: main allocated 605..623 (technical-indicator kernels #31017, local sliding-window ranks #31020, quantileExactWeighted, unsigned-decimal admission, mo_index_sub_part). The EWM family renumbered 605..609 -> 624..628 and `FUNCTION_END_NUMBER` 610 -> 629. Every reference is by the named constant, so the renumbering is behavior-neutral; the ID pins in `pkg/sql/plan/function/function_id_test.go` now cover 624..628 together with main's own 605..623 pins. - **Parser**: the five ewm tokens joined main's extended non-reserved keyword set and window-function grammar; `mysql_sql.go` was regenerated with the repository's goyacc generator from the merged grammar (exit 0, zero shift/reduce conflicts, the Makefile's own gate), and `TestEwmWindowFunctionGrammar`/`TestEwmNamesRemainIdentifierCompatible` plus the full `pkg/sql/parsers/dialect/mysql` package pass. - **Window operator**: main's full-partition results refactor (#31553/#31585) replaced the ordered-set partition-result cache the EWM teardown used to ride on. The EWM state release (`freeEwmState`) now hangs on the new lifecycle points beside `freeFullPartitionResults`/`freeIndicatorState` in `Reset`, `Free` and the per-generation eval entry, and the dispatch switch keeps both families: main's indicator kernels first, then the EWM processors, before the generic value/order/aggregate paths. - **Local validation service**: the base update also refreshed the pinned native thirdparty (usearch 2.26.5-20261030) required by the new go.mod replace; the worktree's stale prebuilt artifacts were rebuilt with the repository's own `make cgo` (provenance flow) before any test was rerun. Validation rerun after the resolution (branch head `effb9768d9`, single commit on `4f894474ad`): - Unit tests, all fresh `-count=1` batches through the repository CGo wrapper, each `ok` (exit 0): `pkg/sql/parsers/dialect/mysql` (1.052s), `pkg/sql/plan/function` with the renumbered ID pins (53.042s), `pkg/sql/colexec/aggexec` (9.030s), `pkg/sql/colexec/window` (9.923s), `pkg/sql/colexec/window/ewm` (0.859s), `pkg/sql/compile -run Ewm` (1.566s), `pkg/sql/plan -run Ewm` (1.478s), `pkg/frontend -run Ewm` (1.859s). - Whole-tree link integrity: `mo-service` built from the rebased tree (272597714 bytes) after `make cgo`. - SQL-level BVT on that binary through the standard mo-tester flow against an isolated dev instance (private launch config, MySQL on a private port). The first comparison run reported 363/368 (98%, mo-tester exit 1) with five statement mismatches, all traced to behavior main itself changed in the meantime rather than to the EWM code: - two metadata-only SHOW COLUMNS header rows (`Field[1,0,0]` -> `Field[12,-1,0]` in `ctas_m9`/`ctas_c9`): main #31033 (`42b5912ac3`, T_char -> T_varchar metadata) regenerates its own BVT `.result` headers; the same regeneration applies here. - three non-finite-policy rows (the `cast('NaN' as double)` / `cast('-Infinity' as double)` spellings and the prepared NaN `EXECUTE`): the expected family rejection did not fire because those string literals now convert to 0.0 through the ordinary MySQL string-to-double conversion; see main #31838 (`f17a2c6204`, which keeps NaN/Inf values for FLOAT/DOUBLE prepared parameters while ordinary SQL string literals keep the MySQL conversion). The test was adapted, not weakened: the three spellings now construct genuinely non-finite doubles through the IEEE bit pattern (`bit_cast(unhex('000000000000f87f') as double)` for NaN and `...f0ff` for negative infinity), exactly the construction main's own `test/distributed/cases/prepare/prepared_nonfinite_float_param.sql` uses. The round-7 invariant is preserved: non-finite `adjust`/`ignoreNA` constants still raise `invalid input: invalid argument: ewm statistics require constant adjust and ignoreNA booleans`, the failing prepared `EXECUTE` still leaves the statement usable, and finite 0/1 spellings still resolve. - The expected `.result` was regenerated with the standard mo-tester `genrs` flow on the same isolated instance. A mechanical comparison against the pre-rebase result reports exactly five replaced lines — the three statement echoes for the new bit-cast spellings and the two SHOW COLUMNS metadata headers — with every outcome row unchanged, including both family-error rejections and the prepared `EXECUTE` error/recovery pair. - Final comparison run: `TOTAL: 368, SUCCESS: 368, FAILED: 0, SUCCESS RATE: 100%` (mo-tester exit 0). Both BVT runs, the probe runs and the regeneration used isolated report/classpath directories; the dev service was stopped with SIGTERM honored after each run and its MySQL listener verified released. ### SCA err-check fix (2026-10-31): moerr-only error construction CI run `41156869916` failed its `Matrixone CI execution / SCA Test on Linux/arm64` job at the `err-check` gate of `make static-check-analysis`: this branch's new `pkg/sql/colexec/window/ewm/engine.go` still used `errors.New`, while the repository's own Makefile gate requires moerr-constructed errors throughout non-test `pkg/` ("Use moerr instead"). The fix rounds out the last non-moerr error constructions of the branch: - The three package-level contract errors are moerr singletons now. `ErrNonFiniteSample`/`ErrDecimalGapOverflow` use `moerr.NewInvalidInputNoCtx`, rendering byte-for-byte as the design contract texts `invalid input: ewm sample values must be finite` and `invalid input: ewm decimal key gaps exceed the decimal domain` (verified by direct rendering), and pointer identity is retained, so the equality assertions in `engine_test.go` and the dispatch `Contains` assertions keep their meaning. - `ErrBadConfig` uses `moerr.NewBadConfigNoCtx` (the repo's bad-configuration family) with the same alpha/half-life message suffix. Its only operator consumer already folds it through `moerr.NewInternalErrorNoCtx(err.Error())` at the decoded-config boundary, and no SQL/BVT surface asserts the old `invalid argument:` prefix, so the family rename stays internal to the decode boundary. - The two walker invariants (`ewm: non-sequential output request`, `ewm: peer-group walker desynchronized`) use `moerr.NewInternalErrorNoCtx`. Verification after the change (all fresh `-count=1` runs through the repository CGo wrapper, on the rebased tree): - Err-check re-simulation over non-test `pkg/` files: zero `fmt.Errorf`/`errors.New` remain anywhere in this tree's `pkg/` (main itself has none), including this PR's files. - `pkg/sql/colexec/window/ewm` full package suite and `pkg/sql/colexec/window` full package suite pass (they pin the singleton identities and the rejected-sample error lists). - Focused EWM suites in `pkg/sql/colexec/aggexec`, `pkg/sql/parsers/dialect/mysql`, `pkg/sql/plan/function`, `pkg/sql/plan`, `pkg/sql/compile` and `pkg/frontend` pass unchanged (`-run 'Ewm|EWM|ewm'`), and the repo's own lint stage (`molint check` + `golangci-lint run` via `make static-check-selected`) on the PR's packages is clean. Known residue, unrelated to this branch: the same SCA tree-wide gate also flags `context.WithTimeout`/`context.WithDeadline` categories, and every one of those hits lives in files this branch never touches and is byte-identical at the base commit `4f894474ad` (`pkg/cdc/sinker_v2_executor.go:633`, `pkg/fileservice/disk_cache.go:1098`, plus further cdc/cnservice/proxy/frontend/clusterservice files). A no-change proposal against today's `main` fails those two categories exactly the same way, so repairing them belongs to `main`, outside this PR's scope; no open issue currently tracks that residue at the time of this update. Additionally, to keep the same SCA job's `molint check` stage green once it stops at err-check, the repository's `checkunsafe` allowlist rule (the linter pins exactly which files may import `unsafe`; `pkg/sql/colexec/window/window.go` is this package's pre-approved allocation-owner file) prompted two layout-accounting relocations, both behavior-neutral: - `pkg/sql/colexec/window/ewm/engine.go`: `RetainedAccountBytes` now sizes the two value layouts through `reflect` (`reflect.TypeOf((*Evaluator)(nil)).Elem().Size()` and the same for `Out`, computed once at init; no value copy), so the file no longer imports `unsafe`. - `pkg/sql/colexec/window/ewm_dispatch.go`: the staged-row sizing factors `ewmRowSize`/`ewmKeySize` moved into the whitelisted `window.go` (same package, next to this operator's existing `unsafe.Sizeof` accounting), and the dispatch file itself stays unsafe-free; all references are unchanged package-scope identifiers. The same preemptive lint pass also cleared golangci-lint's own findings in the branch's files (the SCA job never reached that analyzer on the failing head): one `copyloopvar` (`c := c`) in `engine_test.go` and five `unused` private helpers left over from earlier iterations (`nopPoller` in `engine.go`; `isZeroPair`, `isNumZero`, `isScalarFloat`, `xsub` in `x.go`) are removed; every one of them had zero references anywhere in the tree and no public or cross-package use (all are package-private). ### Review-22 fix (2026-10-31): runtime-constant admission for constant-expression configs iamlinjunhong's review (head `8e8b448e`, REQUEST_CHANGES) flagged the binder constancy gate: it used `function.IsConstant(arg, true)` — the foldability policy, whose `fid == CASE` branch rejects every CASE node — so a statement-level constant CASE in a decay or policy position (and IFNULL, which binding lowers to CASE) was rejected with `ewm statistics require constant decay and policy arguments` even though §4 admits constant expressions and the per-execution configuration evaluation (§9) already owns them. Valid finding, fixed in `4161c0b69e`. - `pkg/sql/plan/window_binder.go` `validateEwmWindowCallSignatures` now judges input-row independence per execution (`function.IsRuntimeConstant`): a constant CASE/IFNULL config binds and reaches `constructEwmConfig` like its literal equivalent. Column-dependent CASE trees, volatile CASE branches (`rand()`) and nested aggregate/window calls keep the §7 rejection; markers, session variables and real-time trees are admitted exactly as before and stay flagged execution-dependent by `PreparedPlanHasEwmParams` (so a marker inside a CASE now resolves per execution as well). - Reproduction at head `8e8b448` and post-fix pass, same tests: `pkg/sql/plan` `TestEwmConstantExpressionConfigs` — the 7 constant CASE/IFNULL acceptance rows (reviewer's witness in the adjust position, decay/ignoreNA/minPeriods positions, cov/corr shifted positions) all bind-fail at the previous head with the spurious error and all 11 rows (acceptance plus column-dependent policy/decay, column-through-IFNULL and volatile-branch rejections) pass on the fixed tree, fresh `-count=1` batches through the repository CGo wrapper; the whole `pkg/sql/plan -run Ewm` batch stays green. - New `pkg/sql/compile` `TestEwmConstantCaseConfigEvaluation` pins the per-execution evaluation the admission now reaches: an unfolded constant CASE evaluates to the identical decoded `EwmConfig` as its literal equivalent for the adjust policy (adjust=false), the binding-lowered IFNULL shape (`case(isnull(x), y, x)`), the numeric decay (alpha 0.5 row mode) and the CASE-spelled `'halflife'` tag (event-time mode, h=3600). The `pkg/sql/compile -run Ewm` batch is green. - Live SQL pair on the reviewer's exact witness through the development instance (isolated runtime, private port): `ERROR 20301 ... ewm statistics require constant decay and policy arguments` on the pre-fix binary; `1, 1.5` on the fixed binary. `ewmmean(x, CASE WHEN TRUE THEN 0.5 ELSE 0.25 END)` publishes `1, 1.6666666666666667` (adjust defaults true — the frozen adjT profile), the IFNULL spelling publishes `1, 1.5`, the column-dependent `CASE WHEN id > 1` policy keeps the §7 error, and the literal spellings are unchanged. - BVT `test/distributed/cases/window/ewm_statistics.sql` gained the requested rows — constant CASE/IFNULL spellings in the decay/policy positions that publish exactly the frozen literal profiles (`1, 1.5, 2.25, 3.125` for alpha .5 adjust false; the adjT rows for the CASE-decay default form; the adjF variance rows), and the column-dependent spellings that keep the §7 error texts with session recovery (`select 1 as recover_case`). The `.result` was regenerated through the standard mo-tester `genrs` flow on the fixed binary: the diff against the previous file is insertion-only. A clean comparison run on the whole file reports `TOTAL: 377, SUCCESS: 377, FAILED: 0, SUCCESS RATE: 100%` (mo-tester exit 0). Both runs used isolated report/classpath directories and the dev service was stopped with its MySQL and logservice listeners verified released after every phase. --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
What type of PR is this?
Which issue(s) this PR fixes:
Addresses #31530.
What this PR does / why we need it:
Ordinary aggregate windows on a full partition and the default ordered RANGE frame repeatedly fill the same input rows for each output row. Queries such as
SUM(b) OVER () LIMIT 20andCOUNT(*) OVER (ORDER BY a)therefore spend quadratic work on common large-partition inputs.Reuse the existing full-partition result owner for ordinary COUNT, SUM, AVG, MIN, and MAX. For cumulative RANGE, reuse the existing running aggregate and peer boundaries, and snapshot fixed-width aggregate state without arithmetic or mutation of the running state. The existing civil-time index keeps timestamp folds on the general evaluator. Output chunks, aggregate finalization, and cancellation retain their existing owners.
This applies to a single logical partition when the saved work exceeds the existing running-state cost threshold. Small or coalesced multi-partition inputs and unsupported cumulative states, including DISTINCT and variable-length MIN/MAX, retain the general evaluator. Complex aggregates such as GROUP_CONCAT retain their existing warning and evaluation behavior.
Validation:
windowandaggexecpackages pass normally and under-race; four focused cancellation/reuse tests each pass 100 race repetitions.go build,go vet, configured golangci-lint, molint, and changed-Go-file license checks pass. Molint's existingunsafeimport diagnostic was reproduced on the exact clean base; no new finding was introduced.window_split_resultBVT was extended for full-frame and RANGE results across the 8192-row chunk boundary. It passes normal mo-tester comparison twice on the same isolated single-CN cluster, with schema teardown verified.On the same local Linux/amd64 environment at 4,096 rows, the operator's full SUM improved from 296 ms to 0.113 ms, and cumulative RANGE SUM from 174 ms to 0.409 ms. Public SQL
SUM(...) OVER () LIMIT 20improved from 361 ms to 0.605 ms; default cumulative RANGE from 181 ms to 1.32 ms. These are local measurements; CI is pending.