Skip to content

[Feature Request]: PERCENTILE_CONT / PERCENTILE_DISC ordered-set aggregate functions #25144

Closed

Description

@dengn

Is there an existing issue for the same feature request?

  • I have checked the existing issues.

Is your feature request related to a problem?

When building NL-to-SQL analytics on MatrixOne for a real-world POC (toll-plaza monitoring, 1000-question stress test), arbitrary-percentile queries are very common ("95th-percentile gate processing time yesterday", "P99 wait minutes per plaza", etc.).

MatrixOne has a native MEDIAN() which is great for P50 only. For any other percentile the user / LLM has to hand-roll a ROW_NUMBER() OVER (ORDER BY x) / COUNT(*) OVER () workaround, which is:

  • error-prone (LLMs frequently write subtly wrong versions — observed in 100% of P95 attempts during our stress test),
  • slow on large fact tables,
  • and unfamiliar to users coming from PostgreSQL / Snowflake / Oracle / Spark / DuckDB, all of which support PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY col) as a standard ordered-set aggregate.

Describe the feature you'd like

Implement the two SQL-standard ordered-set aggregates:

  • PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY expr) — continuous percentile (linear interpolation between adjacent values).
  • PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY expr) — discrete percentile (the smallest value with cumulative distribution ≥ p).

Both should be usable as scalar aggregates and (ideally later) as window functions via WITHIN GROUP over partitions.

```sql
-- desired
SELECT plaza_id,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY gate_processing_sec) AS p95_sec
FROM toll_transactions
WHERE transaction_datetime >= NOW() - INTERVAL 1 HOUR
GROUP BY plaza_id;
```

Describe implementation you've considered

PostgreSQL's implementation is a good reference — they treat these as ordered-set aggregates with the special WITHIN GROUP (ORDER BY …) clause. Internally a sorted run of the input column is materialized per group; for CONT the position is interpolated, for DISC the value at the ceiling position is returned.

A pragmatic shortcut for the MVP could be to support only the non-window scalar form first, since that's the form 99% of NL2SQL output uses. Window-partitioned variants can come later.

Documentation, Adoption, Use Case, Migration Strategy

Any analytics tool that emits MySQL/PostgreSQL-flavored SQL (Looker, Metabase, Superset, Tableau live-query, LangChain SQL agents, custom NL2SQL pipelines) generates these aggregates routinely. Without native support, integrators have to special-case MatrixOne in their dialect rules — which is what we ended up doing in our LLM system prompt for this POC.

Additional information

Reproduction on `8.0.30-OmniFabric-v4.0.0-rc2` (commit `e0a8185`):

```
mysql> SELECT PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY gate_processing_sec) FROM toll_transactions LIMIT 1;
ERROR 1064 (HY000): SQL parser error: syntax error at line 1 column 43 near " (ORDER BY gate_processing_sec) ..."

mysql> SELECT PERCENTILE_CONT(0.95) FROM toll_transactions LIMIT 1;
ERROR 20105 (HY000): not supported: function or operator 'percentile_cont'

mysql> SELECT PERCENTILE_DISC(0.95) WITHIN GROUP (ORDER BY gate_processing_sec) FROM toll_transactions LIMIT 1;
ERROR 1064 (HY000): SQL parser error: ...
```

Observed in a 1000-question NL2SQL stress test as the only LLM failure that was directly caused by a missing MatrixOne function — every other failure was generic SQL hygiene or a model-side issue.

Activity

  1. fengttt commented on Jun 26, 2026

    @fengttt
    Contributor

    Dup #24550

  2. added
    severity/s2
    on Jun 30, 2026
  3. added this to the MO-202607 milestone on Jun 30, 2026
  4. added
    ai-heavy
    on Jul 1, 2026
  5. removed
    severity/s2
    on Aug 6, 2026
  6. added a commit that references this issue on Aug 11, 2026
  7. 6 remaining items

  8. slyunnn commented on Sep 21, 2026

    @slyunnn

    @daviszhen 请确认 PCT-R024 的最终 NaN 排序合同。

    PCT-R024 NaN ordering test status

    Feature: #25144. Test design: MatrixOne Ordered-Set Percentile 测试设计. The R024 expectation is ASC NaN before ordinary numeric values and DESC NaN after them; a NaN continuous-percentile endpoint returns NaN.

    Previous 3-CN evidence:

    • MatrixOne main 9a07655c54efdd1b5d24f801f701602b7231d013 passed the NaN assertion in TKE 35504840643; other assertions in that run failed independently.
    • Later main commits 7f9505e7b8eb4ba45264114a76e3145f6fa26c7a and 370c310a994de258ee01e87c31062590a7022f34 returned ASC p=0 as -Inf and DESC p=0 as +Inf in TKE 35496856957 and TKE 35498299316.

    2026-10-29 local follow-up

    On MatrixOne main 652a8ec6d0ea8999d2fe45b4cb28b67f8c4f2430, an isolated 1-CN SQL test used NaN, -Inf and +Inf constructed from their DOUBLE bit patterns, together with -1, 0 and 1. For (CONT ASC p0, DISC ASC p0, DISC ASC p1, DISC DESC p0, DISC DESC p1):

    • Expected by R024: (NaN, NaN, +Inf, +Inf, NaN).
    • Actual: (-Inf, -Inf, NaN, +Inf, NaN). This result reproduced in the individual and combined runs.
    • On the same fixture, SQL ORDER BY v ASC returned [-Inf,-1,0,1,+Inf,NaN]; ORDER BY v DESC returned [+Inf,1,0,-1,-Inf,NaN].

    The result matches SQL float ordering described by PR #26956 and the expectation of the closed #28854, while R024 expects the opposite ASC NaN placement. The expected result has not been changed, and this discrepancy has not been submitted as a duplicate product bug. Please decide which contract should govern this feature; the local test does not establish a mixed-version or multi-CN result on this SHA.

  9. slyunnn commented on Nov 2, 2026

    @slyunnn

    Feature verification for #25144 (Ordered-Set Percentile) (2026-11-02)

    Test environment

    • Feature implementation: #26781, merge commit f6889dd2a90077aa4fbe46e66ad91e02b36966cf. The merge commit is an ancestor of main at ea184ad90624ae3dba8ced628ac019271a6c309c, verified on 2026-11-02 by GitHub's commit comparison; git fetch origin main also completed successfully. The local tests below used this frozen main commit.

    • The evidence below comes from separate earlier executions on different MatrixOne commits, not one frozen release build. A common release binary SHA256 or image digest, build parameters, and complete deployment/resource fingerprint for all required cases have not been established.

    • Earlier SQL tests and the latest local follow-up ran against isolated MatrixOne services using a MySQL-protocol client. Cancellation tests ran on isolated TKE deployments with one or three CNs as specified below.

    • The latest local follow-up used an isolated one-CN, one-TN and one-LogService deployment on macOS arm64, Go 1.27.1. git_version() returned ea184ad90624ae3dba8ced628ac019271a6c309c; the mo-service binary SHA256 was e230970187d179a8d9f0947dd645818fb513b0db3daae69c39b26b80abc15067. Standard native build failed its completion-marker check; after building native libraries from the same source, the repository's build-with-prebuilt-native target produced the binary. Both build logs are retained locally.

    Test results

    • On ea184ad90624ae3dba8ced628ac019271a6c309c, three individual scripts from MOTR #291 commit c83a873ef39127641b0c40c515caf2d1eb58793b passed 23/23, 27/27 and 2/2 printed assertions; the MOTR runner subsequently passed all three serially with their checked-in expected outputs. This was not the complete MOTR suite.
    • The non-finite prepared-parameter script from MOTR #298 commit 51e23b6c61fa471fa8ad569d14f9d9d9119748cd passed individually and through the runner on the same product commit. Its script blob matched GitHub; no same-named golden output was found. The existing ordered-percentile unit-test group passed 21/21 top-level tests and four remote-protocol unit tests passed; these do not prove target-specific multi-CN cleanup.
    • Earlier local SQL runs exercised continuous and discrete percentiles, ranks, boundaries, grouping, types, NULLs, window functions, and rejected input. For the values 1 through 5, p=0.95 returned continuous 4.8 and discrete 5 on 21991b38274208798e67e14d4b2dfc4743048572. This is not the original toll-transactions SQL with its original data.
    • An earlier local run on c0dd71c7b9d980969f96ef24e7a1bec086828a7c checked NaN ordering and percentile results in memory and actual spill paths; the focused cases and their function group passed. The revised design uses NaN-last ordering in both directions. This does not prove multi-CN behavior on that commit.
    • In the single-CN cancellation run, product a54850983d9cddaacc97e38a84515ec724c937b7 canceled an active spilling query with context canceled; the observed spill file descriptors closed and a subsequent health query succeeded. Query-specific mpool release was not observed directly.
    • In the three-CN cancellation run, product d24f446e1e94a58c329d422519f7aad621cdcd05 canceled the active target statement and the subsequent health query succeeded. Its diagnostic record reports selection of three CNs and spill activity; the collected logs do not establish target-associated remote execution and exit on each involved CN or query-specific resource release. The successful workflow does not establish the full cancellation/cleanup requirement.

    Bugs

    • #31697 tracks a reproducible panic for directly merging incompatible internal percentile states on 21991b38274208798e67e14d4b2dfc4743048572. Normal MergeGroup preflight rejects the mismatch; SQL reachability and the direct internal API contract remain unconfirmed. The issue is open.
    • #31720, for prepared non-finite parameters, is closed. The latest local follow-up above directly verified the associated regression on ea184ad90624ae3dba8ced628ac019271a6c309c.

    Regression coverage

    • The focused MOTR and unit tests described above were executed on the frozen main commit; they are not a complete run of all necessary cases. MOTR #291 and MOTR #298 are open and unmerged.
    • Nightly #1888 is open and unmerged; its script commit 0b8a4a190679e76826a6eb4bb9e55fc82176a4cb was used in the three-CN run above. A real spilling workload is relevant to the feature; generic two-hour soak and large-scale performance matrices are not required by the revised necessary-scope design.

    Evidence and not covered

    • The focused TKE baseline-only preflight ran against product ea184ad90624ae3dba8ced628ac019271a6c309c and script 9038822138c3e114e80c7a0265d42831b1523c47. The three-CN SQL preflight passed, but the baseline step failed because the service reports the short revision ea184ad while the script required the full SHA. This was a test-script validation failure; the 10M fixture was not loaded, and the run-owned cluster, bucketclaim and namespace were cleaned up. The artifact contains the original results. The corrected image-version check subsequently passed on TKE as described below.
    • The single-CN baseline-only run passed SQL and session-pool preflight on ea184ad90624ae3dba8ced628ac019271a6c309c using script 492738a96814a20d51a269d7a82adc6769ec080a. The built image and actual CN, DN and Log pod image IDs had digest sha256:6542d4fb89990e5e9ef2735a21bddd2abd516abea6bca1ebec7db0381797236e; SQL reported short revision ea184ad. The captured cluster-spec fingerprint is a custom canonical-JSON SHA256, not a Kubernetes deployment digest. This preflight did not run the cancellation workload.
    • The 10M single-CN cancellation run used the same product and script commits; fixture creation passed. The target statement logged context canceled, but the observation script failed when the held-open session still showed the target SQL. It did not preserve the session-pool samples, so no mpool-release conclusion can be drawn. The run-owned database, cluster, bucketclaim and namespace were cleaned up. A script fix was locally tested and pushed in PR [Feature Request]: Make MO compatible to mysqldump #1888; the first focused follow-up stopped before loading the 10M fixture: the runtime-baseline script did not yet support TKE CN pods owned by CloneSet. Its run-owned cluster and namespace were cleaned up. In a subsequent follow-up, the cluster object was created but no Running Pods appeared for over 10 minutes; the run was canceled and the owned cluster and namespace were deleted. Its cause was not established. The bounded baseline-only environment probe did not reach SQL or load the fixture: scheduler events report insufficient CPU/memory, node affinity and taint constraints, and node groups at maximum size. The three Log pods remained Pending. The run-owned cluster and namespace were deleted; the baseline, cancellation mpool release and target-associated remote exit remain unverified.
    • The three-CN artifact contains the target statement record, preflight, fixture and CN diagnostics; the run logs report that its run-owned database, cluster and namespace were cleaned up. The artifact is subject to repository retention limits. Other detailed raw results are archived locally and are not public evidence links.
    • The full necessary design has not been executed on the frozen main commit; a complete matching TKE workload-controller fingerprint, query-specific mpool release, and target-associated remote exit remain unverified. Existing product interfaces inspected so far expose aggregate pipeline/resource information rather than the required target-specific proof. Further instrumentation or an established equivalent observation method is needed; absence of evidence is not evidence of a leak. The local test databases and isolated service were cleaned up.
    • The source workspace had pre-existing modifications and untracked files; they were not changed by this update. The original issue SQL and its production dataset were not reproduced verbatim.

    Conclusion

    Blocked — the feature is merged and prior focused tests provide useful evidence, but the necessary release-baseline and cancellation/resource evidence is insufficient for a complete acceptance conclusion. The historical executions above must not be combined into a single all-passed run.

  10. slyunnn commented on Nov 3, 2026

    @slyunnn

    Follow-up verification — 2026-11-03

    Product baseline: MatrixOne main commit ea184ad90624ae3dba8ced628ac019271a6c309c; test script commit 7a300f6d09346e06791d90697327d13a2677fff3.

    • Single-CN cancellation: on 10M rows, the identified target returned 1317 / context canceled. Its identified session pool recorded off-heap current bytes of 0 before, 2,555,904 while active, and 0 after cancellation; on-heap current bytes were 8 at each sample. Both observed spill file descriptors closed, and the subsequent health query passed. This demonstrates the sampled session pool on one CN, not all operator or remote allocations.
    • Three-CN cancellation: on 10M rows, the identified target returned 1317 / context canceled and the subsequent health query passed. The target-filtered marker and before/after goroutine stacks show that one non-coordinator CN receiver handler was active and subsequently exited, with the same pod, container and process identity. Another remote CN emitted a marker but did not have a paired active/after witness. Therefore this is partial remote evidence; it does not establish that every remote fragment, child goroutine or allocation exited. Raw artifact.
    • The single-CN and three-CN runs captured the build image digest, actual pod image IDs and UID-checked workload spec fingerprints. These fingerprints are custom canonical-spec hashes rather than Kubernetes-native deployment digests. Both runs cleaned up their owned database, cluster, bucketclaim and namespace.

    The remaining gap is complete target-associated remote execution and exit and resource cleanup evidence across the involved remote execution; the above observations should not be treated as proof of all remote/operator cleanup. The earlier overall conclusion is retained pending the remaining necessary evidence.

    • Follow-up run 41574808417 on script ee1e793ea438453284d906a7e190fc3874382214 recorded markers on both remote CNs and cancellation of the target; one handler was observed exiting after cancellation, while the other handler was absent already in the active snapshot. The stricter collector marked that latter witness unavailable and the job failed. This is an observation gap, not a demonstrated product failure. Owned resources were cleaned up. A revised collector separately records handlers absent before cancellation and requires at least one handler to exit afterward; it does not claim that all child work or allocations were cleaned up. The focused follow-up 41575688908 did not start SQL: TKE scheduling reported insufficient CPU/memory, node constraints and maxed node groups. The owned cluster and namespace were deleted. This is an environment failure; no product assertion was executed.

    • Run 41587492692 on script c0d8810ddbe2993082d39ef91ac87fab9ca6eebb again stopped during TKE cluster setup: scheduler events report insufficient CPU and memory, node affinity/taint constraints, and node groups at maximum size. No SQL or 10M fixture ran. The owned cluster and namespace were deleted. This is an environment capacity constraint, not a product test failure.

    2026-11-05: multi-CN cancellation follow-up

    Run 42008949522 used MatrixOne ea184ad90624ae3dba8ced628ac019271a6c309c and script c0d8810ddbe2993082d39ef91ac87fab9ca6eebb. The 10M-row fixture and three-CN environment were confirmed, and all product pod image digests matched the build digest. The target query returned 1317 / context canceled; session reuse and the health query passed. Of the two identified remote handlers, one was already absent in the snapshot before cancellation, and one was observed active before cancellation and absent afterward, with unchanged pod/container/process identity. The test report marks acceptance as partial: receiver-handler observations alone do not establish that every remote child goroutine or allocation was released. The owned database, cluster, bucketclaim and namespace were cleaned up. Raw artifact.

    R050 remote resource evidence review

    The target statement record from run 42008949522 reports missing_fragments=1 and missing_memory_domains=1. The frozen source names remote compile pools compile; the available pool report is not keyed by statement ID. Therefore neither the incomplete statement summary nor a process-wide pool sample can establish that this target's remote allocations and children were released. The observed handler exit remains valid for that handler and is not, by itself, proof of all descendant cleanup. There is no evidence here of a resource leak.

    For the necessary test scope, the observed multi-CN cancellation and subsequent health checks pass; the target-related handler observations are retained as direct evidence. Complete query-specific remote pool, registry and descendant cleanup remain partially verified because the relevant diagnostics are incomplete. Record this as an observability limitation rather than requiring another large-data run or asserting that every internal goroutine and allocation was released. Release acceptance of the remaining limitation is separate from the measured result; existing bug issues are tracked separately.

  11. assigned and unassigned on Nov 4, 2026
  12. slyunnn commented on Nov 6, 2026

    @slyunnn

    Feature verification for #25144 (ordered-set percentile) (2026-11-06)

    Test environment

    • The core feature was merged in PR #26781, merge commit f6889dd2a90077aa4fbe46e66ad91e02b36966cf. GitHub's commit comparison confirms that this commit is an ancestor of the local supplemental test target.
    • The 2026-11-06 local supplemental SQL tests used MatrixOne main commit b6c57d315c8d1df2aca40ab19dee72136e6f2f81 (fix(disttae): preserve optimistic RC write dependencies across snapshot advances (#32174)). The running binary reported b6c57d315c; its SHA256 was dd8d7567b1ae6ff7bcd1742a674162fa00c5ccbee6206c33f4226114bafd1ec6. The local isolated deployment had one CN, one TN and one LogService; tests used PyMySQL over the MySQL protocol. The original build command for this existing binary was not independently recorded in this supplemental run.
    • Earlier local contract tests and the TKE cancellation tests used MatrixOne ea184ad90624ae3dba8ced628ac019271a6c309c. The TKE runs captured build image digest sha256:6542d4fb89990e5e9ef2735a21bddd2abd516abea6bca1ebec7db0381797236e and checked the product pod image IDs against that digest. Results below identify their execution round; they are not one run on a single SHA.

    Test results

    • Basic and grouped queries: On b6c57d3, both percentile functions returned the expected results for the basic input; implicit and explicit ascending order agreed. A filtered grouped query with HAVING and output ordering by the percentile alias returned the expected per-group results. A JOIN/CTE input and an equivalent UNION ALL input preserved row multiplicity and returned the same expected aggregates. These are representative queries; the original issue's production table and SQL were not replayed verbatim.
    • Boundaries and types: On b6c57d3, single values, duplicates, empty and all-NULL inputs, NULL filtering, NULL percentile rejection, large integers, Infinity ordering and discrete endpoints, and Decimal64 values and result metadata passed targeted checks. Seeded tests varied input size, NULLs, duplicates, groups, direction and percentile. A separate recheck of the archived 120 continuous results against the independent oracle found 120/120 identical binary64 bit patterns; discrete results were also exact.
    • Additional SQL contracts: Earlier direct local tests on ea184ad passed prepared-parameter reuse and rejection checks, partitioned window checks, Decimal128/256 boundaries, supported and rejected order types, and NaN/Infinity cases including forced spill. Protocol gating and aggregation-state behavior were exercised by focused implementation-layer tests; these unit tests are not a mixed-version deployment test.
    • Cancellation and resource observations: In the single-CN TKE run, a target over 10M rows returned 1317 / context canceled; its observed session pool off-heap bytes returned from 2,555,904 while active to 0 afterward, two observed spill file descriptors closed, and the health query passed. In the three-CN TKE run, the target was canceled and the subsequent health and session-reuse checks passed. One target-associated remote handler was observed active and then absent; another was already absent before cancellation. This does not prove cleanup of every remote child or allocation. The runtime observations and their limitations are detailed in the follow-up evidence.

    Bugs

    • #31697 tracks a reproducible panic when incompatible partial-state types are passed directly to an internal Merge API. The normal preflight rejects the mismatch; a SQL-reachable panic or production impact has not been demonstrated. The issue remains open and is tracked separately.

    Regression coverage

    • MOTR contract and non-finite parameter coverage was merged in motr #291 and motr #298. Earlier local execution used the corresponding recorded test commits.
    • The supplemental local SQL script was run case by case, then as a group: 11/11 cases passed individually and 11/11 passed in the group. It is retained as execution evidence; it was not submitted as a new MOTR regression.
    • The scale and topology coverage in mo-nightly-regression #1728 and the additional observation work in #1888 remain open. Their PR status is distinct from the completed TKE runs above. Large-data checks are useful for the actual spill and cancellation paths; they do not imply a general performance or long-duration guarantee.

    Evidence and not covered

    • The linked Actions runs and three-CN artifact contain TKE execution and diagnostic evidence. Local per-case SQL, actual/expected values, metadata, oracle comparisons, environment details and cleanup checks are archived in the test workspace; local files are not publicly accessible artifacts.
    • The three-CN observation does not establish query-specific cleanup of all remote child work or memory allocations. No resource leak is inferred from that observability limitation. A real mixed-version cluster and all possible production workloads were not verified by these tests.
    • The supplemental local test databases and isolated service data were removed after verification. The referenced TKE runs report cleanup of their owned test resources.

    Conclusion

    Passed for the tested core ordered-set percentile functionality, with the internal Merge issue tracked separately and the remote resource-observation limitation stated above. This conclusion is limited to the explicitly described executions and does not claim that all tests ran on one release build, that every internal path passed, or that the open Nightly PRs have merged.

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

Metadata

Metadata

Assignees

Labels

ai-heavy

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions