Repository navigation
feat(sql): add ewmMean/ewmVar/ewmStd/ewmCov/ewmCorr window functions - #31941
Conversation
b7bca85 to
effb976
Compare
Implement the exponentially weighted window statistics with alpha/halflife decay and constant adjust and ignoreNA policies plus a typed minPeriods publication threshold: - parser: five function names with 2-7 argument positional forms and the 'halflife' decay tag - plan: the window binder routes constant and marker-decay arguments and keeps execution-dependent ewm plans out of compile caches - compile: minPeriods resolution in the original plan type with exact integral checks over float64 and decimal64/128/256 spellings - window: per-execution configuration channel, exactly-once peer dispatch and the frozen-oracle EWM engine with a bounded cancellation contract - frontend: prepared statements resolve ewm configuration per execution in the plan cache gates - tests: focused unit tests per stage and a BVT suite covering the SQL-level semantics (368 mo-tester statements) Related to matrixorigin#29945
effb976 to
8e8b448
Compare
|
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: 4161c0b69e41f78eb1c491c73395965e0ae032bf
Assessment: approve
The prior CASE/IFNULL configuration rejection is resolved. Current validation and qualified earlier coverage close the affected contracts; no actionable findings remain.
Model: gpt-6-astra / xhigh
Session: 01a1869d-999c-7481-b340-ae4a63e8cee4 · slot 1 · generation 2
Validation:
-
Planner and compiler suites passed, including 11 new binder cases and the original eight-case review probe.
-
Real MySQL execution passed all 377 fixture statements, repeated prepared CASE configurations, and event-time ordering controls.
-
Qualified 27 historical receipts and logs for unchanged numerical, parser, lifecycle and race coverage, preserving their original failure classifications.
-
Recorded validation-audit.json and discussion-assessment.json; all 10 discussion keys covered and source unchanged.
Limitations:
-
Fresh execution used Linux/amd64 and one CN; no CI or multi-CN rerun.
-
MySQL replay validates values, NULLs, ordering and errors, but not JDBC-specific metadata formatting.
-
Reused evidence retains the documented frontend fixture overlay and numerical-oracle qualifications.
iamlinjunhong
left a comment
There was a problem hiding this comment.
Reviewed head 4161c0b69e41f78eb1c491c73395965e0ae032bf against base 4f894474ad10e1b9dc338868145a118a71c1fa23. APPROVE — no remaining in-scope findings were confirmed.
The previous constant CASE/IFNULL admission defect is fixed. The author explicitly replied in the original thread. Comparing the reviewed and current code confirms that IsRuntimeConstant admits row-independent CASE trees while still rejecting column-dependent, volatile, aggregate and window expressions. The new binder tests, compiler configuration tests and SQL fixtures cover the repaired path; per-execution configuration and both prepared-cache exclusions remain consistent with it. The duplicate finding in review 5721551416 also received an explicit author response.
CI/check status follows the supplied review data: 30 checks: 14 success, 14 skipped, 2 neutral. None failed or remained running, but they are not all success. CI Required succeeded, as did UT, SCA, coverage and the selected multi-CN BVT checks.
Validation in this review: read-only code/diff and call-chain inspection, previous-feedback reconciliation, and the PR artifact check (passed). Local tests and service startup were skipped because the relevant regression coverage is committed and exact-head CI is available; author-reported local SQL runs were not independently rerun. git diff --check reports two trailing-space lines in the formatted SQL result fixture; these are not functional findings. Source files were unchanged; no GitHub write was performed.
❌ Left the queue · checks failed1 h 36 min in the queue, with no time running CI. So far
The failure is in this pull request. It failed tested alone on top of Reason The merge conditions cannot be satisfied due to failing checks
To get back in the queue
Merge conditions not met when it left the queue
Requeued — the merge queue status continues in this comment ↓. 2 merge conditions met
Times in UTC · dashboard · how the merge queue works |
🚫 Left the queue1 h 12 min in the queue, with no time running CI. So far
Reason Pull request #31941 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
Hint You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it. Merge conditions not met when it left the queue
Tick the box to put this pull request back in the merge queue (same as
2 merge conditions met
Times in UTC · dashboard · how the merge queue works |
What type of PR is this?
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
ewmfamily at the SQL level:ewmMean,ewmVar,ewmStd,ewmCovandewmCorrover a window frame, withalpha(or the string taghalflife) decay and the constant policiesadjust,ignoreNAandminPeriods. 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:
pkg/sql/parsers/dialect/mysql/keywords.go,mysql_sql.y,mysql_sql.go): the parser now accepts the 2-7 argument positional forms, withhalflifeas a string literal decay tag and the names kept identifier-compatible.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(withquery_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).minPeriodshad 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.gonow resolvesminPeriodsin the original plan type (boolto 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 atmath.MaxInt64, and rejects non-finite policy constants (NaN/+Inf/-Inf) with the family error.pkg/sql/colexec/window/ewm_dispatch.goadmits 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.gocarries the resolvedEwmConfig{Mode, Alpha, HalfLife, Adjust, IgnoreNA, MinPeriods}across the operator boundary with a strict length-gated decode. Thepkg/sql/colexec/window/ewmengine 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 belowmax(1, minPeriods), and computes correlation with the zero-variance rule (NULL rather than a divide by zero).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,minPeriodsboundary and rejection blocks, constant/non-integer policy rejections with session recovery (SELECT 1after each error), prepared marker forms, and regression rows for AVG/var_pop/stddev_pop beside the new functions.Validation (issue #29945 -> tests):
pkg/sql/parsers/dialect/mysqlTestEwmWindowFunctionGrammar(all five names, decay/halflife/policy forms parse; invalid arities and bare usage reject) andTestEwmNamesRemainIdentifierCompatible.pkg/sql/planTestEwmBinderRejectionsandTestEwmBinderAcceptances(the constant-policy catalog: non-constant or out-of-range alpha, boolean-typed policy positions, wrong arities all reject),TestEwmMarkerDecayBindsDecimal256HalfLife,TestEwmDomainlessNullSamplesBindAsFloat64,TestEwmWindowOutputsRemainNullable,TestEwmRealTimeConfigClassifiesExecutionDependent.pkg/sql/compileTestConstructEwmConfig(valid forms and the invalid families),TestConstructEwmConfigMinPeriodsIntegrality,TestConstructEwmConfigMinPeriodsUpperBound,TestConstructEwmConfigNonFinitePolicy,TestValidateEwmWindowConfigsAfterModeResolution(event-time mode requires one ascending numeric ORDER BY key).pkg/sql/colexec/aggexecTestEwmConfigRoundTrip,TestEwmConfigDecode(the widened record round-trips atMinPeriods2147483648 and math.MaxInt64).pkg/sql/colexec/windowTestEwmDispatchSplitPeerExactlyOnce,TestEwmDispatchPartitionIsolation,TestEwmDispatchLimitThenResetResumesFromScratch,TestEwmDispatchErrorThenCleanReuse,TestEwmDispatchCancellationMidGroup,TestEwmDispatchConfigChannelDrivesRows,TestEwmDispatchDecimalKeys,TestEwmDispatchEventIgnoreNAPartitionsIndexLocally,TestEwmDispatchPeerDirectoryAdmission;pkg/sql/colexec/window/ewmTestOracleVectors(204 frozen expectation vectors, bit-exact),TestEvaluatorSliceResumability,TestNonFiniteSampleRejection,TestKeyDomainRules,TestEventTimeNullInstantClock,TestMergePhaseCancellation,TestDdsumResidualCancellation.pkg/frontendTestShouldCachePrepareCompileRejectsEwmParameter,TestPreparedEwmDisablesMixedRuntimeSpecializationCache,TestPreparedEwmMarkerDecayKeepsRowModeOrderLatitude,TestPreparedEwmRealTimeConfigIsExcludedFromBothCaches.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.resultfile 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
minPeriodsdefect (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 fractionalminPeriodsconstants (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.sqlcase 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 ofTestConstructEwmConfigMinPeriodsIntegralityfailed 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):
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_statdatabases dropped after the run and the service stopped with its listeners released).Residual risks and limitations:
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 integralminPeriodstest is implemented over raw decimal256 significands (a fraction that float64 rounds to one still rejects), not over a float64 interpolation.minPeriodsspellings above int64 saturate at math.MaxInt64 instead of erroring (the gate then publishes NULL), which follows the design's "no upper limit" rule.pkg/sql/colexec/window/ewm/bench_test.gorecord both modes (row decay at ~0.67us/row over one-row peer groups; event-time distinct instants at ~70us/row).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 reportedmergeStateStatus=DIRTY. The branch was rebased onto currentmain(4f894474ad10e1b9dc338868145a118a71c1fa23, 270 commits ahead of the old base) with semantic resolution of the overlapping features that landed for the sibling window-kernel families:FUNCTION_END_NUMBER610 -> 629. Every reference is by the named constant, so the renumbering is behavior-neutral; the ID pins inpkg/sql/plan/function/function_id_test.gonow cover 624..628 together with main's own 605..623 pins.mysql_sql.gowas regenerated with the repository's goyacc generator from the merged grammar (exit 0, zero shift/reduce conflicts, the Makefile's own gate), andTestEwmWindowFunctionGrammar/TestEwmNamesRemainIdentifierCompatibleplus the fullpkg/sql/parsers/dialect/mysqlpackage pass.freeEwmState) now hangs on the new lifecycle points besidefreeFullPartitionResults/freeIndicatorStateinReset,Freeand 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.make cgo(provenance flow) before any test was rerun.Validation rerun after the resolution (branch head
effb9768d9, single commit on4f894474ad):-count=1batches through the repository CGo wrapper, eachok(exit 0):pkg/sql/parsers/dialect/mysql(1.052s),pkg/sql/plan/functionwith 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).mo-servicebuilt from the rebased tree (272597714 bytes) aftermake cgo.Field[1,0,0]->Field[12,-1,0]inctas_m9/ctas_c9): main fix: make SHOW metadata identifiers safe #31033 (42b5912ac3, T_char -> T_varchar metadata) regenerates its own BVT.resultheaders; the same regeneration applies here.cast('NaN' as double)/cast('-Infinity' as double)spellings and the prepared NaNEXECUTE): 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 fix(function): keep NaN/Inf FLOAT/DOUBLE prepared parameters non-finite #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...f0fffor negative infinity), exactly the construction main's owntest/distributed/cases/prepare/prepared_nonfinite_float_param.sqluses. The round-7 invariant is preserved: non-finiteadjust/ignoreNAconstants still raiseinvalid input: invalid argument: ewm statistics require constant adjust and ignoreNA booleans, the failing preparedEXECUTEstill leaves the statement usable, and finite 0/1 spellings still resolve..resultwas regenerated with the standard mo-testergenrsflow 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 preparedEXECUTEerror/recovery pair.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
41156869916failed itsMatrixone CI execution / SCA Test on Linux/arm64job at theerr-checkgate ofmake static-check-analysis: this branch's newpkg/sql/colexec/window/ewm/engine.gostill usederrors.New, while the repository's own Makefile gate requires moerr-constructed errors throughout non-testpkg/("Use moerr instead").The fix rounds out the last non-moerr error constructions of the branch:
ErrNonFiniteSample/ErrDecimalGapOverflowusemoerr.NewInvalidInputNoCtx, rendering byte-for-byte as the design contract textsinvalid input: ewm sample values must be finiteandinvalid input: ewm decimal key gaps exceed the decimal domain(verified by direct rendering), and pointer identity is retained, so the equality assertions inengine_test.goand the dispatchContainsassertions keep their meaning.ErrBadConfigusesmoerr.NewBadConfigNoCtx(the repo's bad-configuration family) with the same alpha/half-life message suffix. Its only operator consumer already folds it throughmoerr.NewInternalErrorNoCtx(err.Error())at the decoded-config boundary, and no SQL/BVT surface asserts the oldinvalid argument:prefix, so the family rename stays internal to the decode boundary.ewm: non-sequential output request,ewm: peer-group walker desynchronized) usemoerr.NewInternalErrorNoCtx.Verification after the change (all fresh
-count=1runs through the repository CGo wrapper, on the rebased tree):pkg/files: zerofmt.Errorf/errors.Newremain anywhere in this tree'spkg/(main itself has none), including this PR's files.pkg/sql/colexec/window/ewmfull package suite andpkg/sql/colexec/windowfull package suite pass (they pin the singleton identities and the rejected-sample error lists).pkg/sql/colexec/aggexec,pkg/sql/parsers/dialect/mysql,pkg/sql/plan/function,pkg/sql/plan,pkg/sql/compileandpkg/frontendpass unchanged (-run 'Ewm|EWM|ewm'), and the repo's own lint stage (molint check+golangci-lint runviamake 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.WithDeadlinecategories, and every one of those hits lives in files this branch never touches and is byte-identical at the base commit4f894474ad(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'smainfails those two categories exactly the same way, so repairing them belongs tomain, 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 checkstage green once it stops at err-check, the repository'scheckunsafeallowlist rule (the linter pins exactly which files may importunsafe;pkg/sql/colexec/window/window.gois this package's pre-approved allocation-owner file) prompted two layout-accounting relocations, both behavior-neutral:pkg/sql/colexec/window/ewm/engine.go:RetainedAccountBytesnow sizes the two value layouts throughreflect(reflect.TypeOf((*Evaluator)(nil)).Elem().Size()and the same forOut, computed once at init; no value copy), so the file no longer importsunsafe.pkg/sql/colexec/window/ewm_dispatch.go: the staged-row sizing factorsewmRowSize/ewmKeySizemoved into the whitelistedwindow.go(same package, next to this operator's existingunsafe.Sizeofaccounting), 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) inengine_test.goand fiveunusedprivate helpers left over from earlier iterations (nopPollerinengine.go;isZeroPair,isNumZero,isScalarFloat,xsubinx.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 usedfunction.IsConstant(arg, true)— the foldability policy, whosefid == CASEbranch 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 withewm statistics require constant decay and policy argumentseven though §4 admits constant expressions and the per-execution configuration evaluation (§9) already owns them. Valid finding, fixed in4161c0b69e.pkg/sql/plan/window_binder.govalidateEwmWindowCallSignaturesnow judges input-row independence per execution (function.IsRuntimeConstant): a constant CASE/IFNULL config binds and reachesconstructEwmConfiglike 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 byPreparedPlanHasEwmParams(so a marker inside a CASE now resolves per execution as well).8e8b448and post-fix pass, same tests:pkg/sql/planTestEwmConstantExpressionConfigs— 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=1batches through the repository CGo wrapper; the wholepkg/sql/plan -run Ewmbatch stays green.pkg/sql/compileTestEwmConstantCaseConfigEvaluationpins the per-execution evaluation the admission now reaches: an unfolded constant CASE evaluates to the identical decodedEwmConfigas 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). Thepkg/sql/compile -run Ewmbatch is green.ERROR 20301 ... ewm statistics require constant decay and policy argumentson the pre-fix binary;1, 1.5on the fixed binary.ewmmean(x, CASE WHEN TRUE THEN 0.5 ELSE 0.25 END)publishes1, 1.6666666666666667(adjust defaults true — the frozen adjT profile), the IFNULL spelling publishes1, 1.5, the column-dependentCASE WHEN id > 1policy keeps the §7 error, and the literal spellings are unchanged.test/distributed/cases/window/ewm_statistics.sqlgained 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.125for 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.resultwas regenerated through the standard mo-testergenrsflow on the fixed binary: the diff against the previous file is insertion-only. A clean comparison run on the whole file reportsTOTAL: 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.