Skip to content

feat: technical-indicator window kernels and rolling risk analytics - #31017

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-29949-main-47ae232d
Oct 24, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-29949-main-47ae232d

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #29949

What this PR does / why we need it:

Issue #29949 asks for a technical-indicator / rolling risk analytics family usable as window functions in SQL. This change adds eleven builtin per-partition sequential kernels to the window operator: sma, wma, trima, ema, wilder, kama, dema, tema, t3, mmaxDrawdown (frame-local bounded maximum drawdown) and cumPositiveStreak, with documented warmup/NULL semantics, strict constant-period admission [1, 1024] routed through the shared deterministic constant-expression evaluator, procedure-M/U numerical contracts (compensated normalized mean; hull-clamped convex recurrence) and SQL migration recipes for the already-expressible cumulative/trend operators.

Root cause

  • The eleven requested names were absent from the builtin window-function registry, so every call failed at entry resolution with ERROR 20105 (not supported: function or operator '...') before any evaluation could happen.
  • The family is structurally inexpressible as ordinary window composition: chained smoothing (dema, tema, t3) and frame-local bounded drawdown need recursive per-partition state with warmup and NULL semantics that the generic sliding-frame value functions do not expose.

Exact changes

  • pkg/sql/plan/function/function_id.go (pins mirrored in function_id_test.go): register the eleven new builtin function IDs.
  • pkg/sql/plan/function/function.go: registry bookkeeping entries required for the new family.
  • pkg/sql/plan/function/list_window.go: WIN_VALUE registrations with isWin exposure, required ORDER BY, explicit-frame rejection and the period-argument overload layout.
  • pkg/sql/parsers/dialect/mysql/mysql_sql.y, regenerated mysql_sql.go, keywords.go: add the eleven names as non-reserved MySQL tokens so they parse in the window-function position while remaining usable as ordinary identifiers; the generated parser file is proven content-fresh against a fresh run of the repo's goyacc generator.
  • pkg/sql/plan/base_binder.go: name resolution exposes the WIN_VALUE registrations so the new names bind as window functions.
  • pkg/sql/plan/window_binder.go (with window_binder_test.go, window_binder_indicator_test.go): binder rules for the family — win-value visibility, required ORDER BY, explicit-frame rejection, strict constant-period admission [1, 1024] through the shared deterministic constant-expression evaluator with fold-time diagnostics for non-constant or out-of-range periods, and NOT NULL propagation pins.
  • pkg/sql/colexec/window/types.go, window.go: the window operator gains the indicator evaluation path beside the existing value-function path (per-partition state machine).
  • pkg/sql/colexec/window/indicators.go (with indicators_test.go, indicators_lifecycle_test.go): the kernels themselves, tested against independent naive references and an oracle fuzzer, with warmup/NULL-semantics pins, cancellation-latency pins, stage-seed-ring bounds, lifecycle generation-isolation proofs and failure/cancel-then-reuse proofs through real Window.Call transitions.
  • test/distributed/cases/function/func_indicator_kernels.sql (69 statements) with regenerated func_indicator_kernels.result: BVT exercising availability separately from math, including red/green entry probes and a cumulative-drawdown control. A period-2 drawdown pass asserts the defined value-domain ratios ([100,0] -> 1.0, [100,-20] -> 1.2, [1,-10] -> 11.0) at the trough row beside the period-3 all-warmup/NULL-axis pass, and a dedicated eight-row chain series takes tema(3) and t3(2) past warmup (first defined at m = 3n-2 = 6n-5 = 7), pinning each chain's first defined value and its subsequent update (review revision).
  • docs/design/technical_indicator_window_kernels.md: the versioned design document (r7 approval).
  • docs/sql/technical-indicators.md: SQL user documentation, including the documented migration recipes for the cumulative/trend operators that are already expressible without new syntax.

Issue-to-test proof

  • Base red -> fixed green entry probes: on the unmodified base binary the four probe calls failed with ERROR 20105 (not supported: function or operator '...'); with this change the same calls parse and return the existing window diagnostic ERROR 1149 (HY000): ... window function ... needs an OVER clause (proving grammar + registry + binder flow), and correct calls evaluate. The cumulative drawdown control returns 0, 0, 0.25, 0.25, unchanged from base.
  • Period admission is proven live in BVT with non-literal deterministic folded expressions: ema(x, LENGTH('abc')) over group g=1 returns NULL, NULL, 103.33333333333333, 106.66666666666666, 93.33333333333333, 81.66666666666666 and wma(x, GREATEST(2,3)) over group g=2 returns NULL, NULL, 10.0, 21.666666666666668, 30.0.
  • Kernel/operator component proof: go test ./pkg/sql/colexec/window/ is green (full package, ok ... 39.418s in the recorded round, re-run green after the final formatting pass: ok ... 36.693s).
  • Planner component proof: go test ./pkg/sql/plan/ -run 'Indicator' -v -> TestIndicatorBinderSurface, TestIndicatorRegistryBits, TestIndicatorDeduceNotNullablePins all PASS (re-run green after the final formatting pass: all PASS, ok ... 2.952s), and the full go test ./pkg/sql/plan/ package is green (ok ... 108.708s).
  • Parser proof: the ./pkg/sql/parsers/... suites are green, and the generated mysql_sql.go is byte-identical to a fresh regeneration from the committed grammar.
  • End-to-end BVT: 69/69 statements, 100% success (TOTAL 69, SUCCESS 69, ... 100%), run by mo-tester with expected-result comparison against an isolated local mo-service built from the PR head (own runtime directory and port plan; readiness verified via SQL before the run; teardown verified with the owned process exited and all owned listeners released).
  • Defined-value SQL coverage (review revision): the period-2 drawdown pass emits the design section 9 ratios exactly (1.0, 1.2, 11.0), keeps all-nonpositive frames NULL, and yields the period-2 NULL-axis profile (0.09999999999999998, 0.0, 0.050000000000000044); the eight-row chain series emits tema(3) 89.537037037037 -> 86.40046296296299 and t3(2) 85.0000447086318 -> 86.16157157614865 at rows 7-8 after all-NULL warmup. Every generated value was cross-checked bit-for-bit against an independent Python oracle of the design section 3.1 formulas, and the regenerated result file differs from the CI-validated predecessor by a pure 48-line insertion.
  • Statics closure on the four changed packages: gofmt clean, go vet clean, golangci-lint run --new-from-rev 8111f870... clean.

Test commands

Component UTs (CGo build env used in this tree: CGO_ENABLED=1 with the repo's cgo/thirdparties include and lib flags, GOWORK=off):

go test -mod=readonly -count=1 -timeout 20m ./pkg/sql/colexec/window/
go test -mod=readonly -count=1 -timeout 20m ./pkg/sql/plan/ -run 'Indicator' -v
go test -mod=readonly -count=1 -timeout 20m ./pkg/sql/plan/
go test -mod=readonly -count=1 ./pkg/sql/parsers/...
go vet -mod=readonly ./pkg/sql/colexec/window/ ./pkg/sql/parsers/dialect/mysql/ ./pkg/sql/plan/ ./pkg/sql/plan/function/
golangci-lint run -c .golangci.yml --new-from-rev 8111f870f5d8cee40c53fc48bcbcde8292da1fa5 ./pkg/sql/colexec/window/ ./pkg/sql/parsers/dialect/mysql/ ./pkg/sql/plan/ ./pkg/sql/plan/function/

End-to-end BVT: start an isolated mo-service on a dedicated port plan and run the mo-tester case-runner over test/distributed/cases/function/func_indicator_kernels.sql with its committed .result (69 statements, all green).

Residual risks

  • Period admission is routed through the shared deterministic constant-expression evaluator rather than a literal-only whitelist, so any foldable scalar expression evaluating into [1, 1024] is accepted (LENGTH('abc'), GREATEST(2,3) are pinned in BVT); non-constant or out-of-range periods fail at fold time with a diagnostic. This widens admissibility relative to a literal-only check while keeping evaluation deterministic.
  • Broad suites (full-repo UTs and the distributed BVT suite beyond the focused case) are deferred to CI; the focused suites establishing this change are green.
  • Recorded kernel capacity (mmaxDrawdown 3.74s, sma 6.21s for p=65536, n=1024 in the benchmark pins) documents headroom; it is informative and not a CI gate.

Related to #29949

Add the technical-indicator window-function family requested by issue matrixorigin#29949
as builtin per-partition sequential kernels on the window operator: sma, wma,
trima, ema, wilder, kama, dema, tema, t3, mmaxDrawdown (frame-local bounded
maximum drawdown) and cumPositiveStreak, with documented warmup/NULL
semantics, strict constant-period admission [1, 1024] through the shared
deterministic constant-expression evaluator, procedure-M/U numerical
contracts (compensated normalized mean; hull-clamped convex recurrence), and
SQL migration recipes for the already-expressible cumulative/trend operators.

The names resolve through the builtin registry path (MySQL token grammar so
the names parse as window functions while remaining usable as ordinary
identifiers, WIN_VALUE registrations with isWin exposure, required ORDER BY,
explicit-frame rejection), and the window operator evaluates them as a
per-partition state machine beside the existing value-function path.

Root cause: the eleven names were absent from the builtin window-function
registry, so every call failed at entry resolution with ERROR 20105 (not
supported: function or operator '...'), and the family is structurally
inexpressible as ordinary window composition because smoothing chains and
frame-local drawdown need recursive per-partition state.

Evidence: focused kernel/operator UT suites (independent naive references,
oracle fuzz, cancellation-latency pins, stage-seed-ring bounds, lifecycle
generation-isolation and failure/cancel-then-reuse proofs through real
Window.Call transitions), full planner/window package runs clean, and a
63-statement BVT case exercising availability separately from math, with
red/green entry probes (base 20105 rejections -> OVER-clause window
diagnostic; cumulative drawdown control 0, 0, 0.25, 0.25 preserved).

Design: docs/design/technical_indicator_window_kernels.md
(r7 approval a8233922edf26c77c6219ea34e1a2bfeaef7ad362a86c0d3ce4d4e03436fdca3).

Related to matrixorigin#29949

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 61a925cd9dbb509086002f2d2abe1693455ab2e3

Assessment: approve

The prior SQL coverage finding is closed. Reviewed the complete delta and affected callers, reusing unchanged prior evidence. The kernels fit the existing Window owner, with no actionable unresolved correctness, lifecycle, compatibility or validation findings.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Frozen evidence matches the assigned head and records successful build, Ubuntu/x86 UT and coverage, arm64 SCA, and complementary PROXY/PESSIMISTIC BVT. The repository selector includes this SQL case.

  • Independent calculations verified all 23 period-2 drawdown rows and both defined TEMA(3)/T3(2) results, including warmup NULLs and exact float bits.

  • Local audit passed: coverage-audit.log and checks/1792842996471766558-2.json record exit 0 against clean current source. Two earlier audit-script CI-name matching failures are retained and superseded.

  • Reconciled the prior parser-generation command, receipt, log and artifact. Parser inputs are unchanged; regenerated output matches current bytes.

  • Reviewed design approval, numerical contracts, shared constant folding, registration, partition/generation resets, cancellation, cleanup, storage bounds and test oracles. Details and assessment are saved under /home/xupeng/.local/state/mo-bot/jobs/777c0210c769ec3e3ca0550d/attempt-1.

  • Final diff check passed: checks/1792843124820004732-2.json and diff-check.log. Source remains unchanged at the assigned head.

Limitations:

  • No local native tests or SQL server run was repeated. CI conclusions were reused; raw CI/author execution logs were not supplied. The Python audit verifies expectations, not production execution.

  • Rolling scans remain O(partition_rows × period), with period capped at 1024 and O(partition_rows) prefix storage. Author timings were not independently measured; no throughput improvement is claimed.

  • The linked issue's full text is absent; its contract was assessed through the frozen PR and versioned design.

@mergify mergify Bot added the queued label Oct 24, 2026
@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-24 11:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-24 14:13 UTC · at 8f8389b5fe44cb272c7ea82a36c32b13a99b8584

This pull request spent 2 hours 13 minutes 48 seconds in the queue, with no time running CI.

Reason

Pull request #31017 has been merged manually at 6fb6531

Hint

You were too fast!

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants