Skip to content

feat(aggexec): add approx_percentile aggregate function for p95/p99 - #24667

Closed
ULookup wants to merge 17 commits into
matrixorigin:mainfrom
ULookup:fix/issue-24550-percentile-quantile-agg
Closed

ULookup wants to merge 17 commits into
matrixorigin:mainfrom
ULookup:fix/issue-24550-percentile-quantile-agg

Conversation

@ULookup

@ULookup ULookup commented May 28, 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:

issue #24550

What this PR does / why we need it:

Adds the approx_percentile(v, percentile) aggregate function that computes
the approximate percentile of a numeric column using O(n) quickselect
with linear interpolation. This enables p95/p99 latency analytics and
observability dashboards previously limited to median (p50) only.

The implementation wires together the parser grammar (already present),
plan-layer function registration, execution-layer executor (reusing the
median infrastructure), and compile-layer config extraction for the
percentile constant.

@ULookup
ULookup requested review from aunjgr and ouyuanning as code owners May 28, 2026 07:43
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify mergify Bot added the kind/feature label May 28, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label May 28, 2026
ULookup added a commit to ULookup/matrixone that referenced this pull request May 28, 2026
…raction

Replace non-existent vec.GetFloat64At/GetInt64At/etc with
vector.MustFixedColWithTypeCheck[T] generic API. Also use
strconv.FormatFloat instead of fmt.Sprintf for percentile config.

Fixes SCA build error in matrixorigin#24667
ULookup added a commit to ULookup/matrixone that referenced this pull request May 28, 2026
The expected result had column `a` typed as a[8,54,0] (int64), but
the CI environment maps INT to a[4,32,0] (int32). Regenerated the
.result to match the actual CI output.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@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.

I found one blocking contract issue in the new approx_percentile aggregate. The execution path assumes the percentile argument is a non-null no-column constant, but the SQL function contract does not enforce that.

  • list_agg.go accepts T_any for arg2 and does not require constness.
  • constructGroup / constructWindow then strip the last argument and feed it through colexec.GetReadonlyResultFromNoColumnExpression.
  • On the current head, a minimal package-local repro still panics for a NULL percentile constant: getPercentileConfig(vector.NewConstNull(types.T_float64.ToType(), 1, mp)) crashes at operator.go:2332 with index out of range [0] with length 0.
  • The same missing contract also admits row-dependent percentile expressions. GetReadonlyResultFromNoColumnExpression explicitly forbids column expressions; for a simple Expr_Col it indexes the const-fold batch directly, so approx_percentile(v, p_col) is on the same bad path.

Please reject NULL / non-constant percentile arguments during planning (or at least return a user error instead of panicking), and add regressions for both approx_percentile(v, null) and approx_percentile(v, p_col).

f.F.Func.ObjName == plan2.NameClusterCenters ||
f.F.Func.ObjName == "approx_percentile") && len(f.F.Args) > 1 {
argExpr := f.F.Args[len(f.F.Args)-1]
vec, free, err := colexec.GetReadonlyResultFromNoColumnExpression(proc, argExpr)

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.

This assumes the last argument is a non-null no-column constant, but the new SQL contract does not enforce that. On this head, a NULL percentile constant already panics in getPercentileConfig because the returned const-null vector has no fixed payload to index. And a row-dependent percentile expression is also admitted by approx_percentile's type check even though GetReadonlyResultFromNoColumnExpression explicitly forbids column expressions. Please validate arg2 before this path instead of panicking here.


drop table if exists t1;
create table t1 (a int, b float);
insert into t1 values (1, 1.1), (2, 2.2), (3, 3.3);

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.

You have to add a reasonable tests, for example, 10K rows, with duplicates, with nulls, etc. and check the result it correct.

@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.

The previous NULL/non-constant percentile contract blocker is fixed on the current head, and this branch merges cleanly with current main. I still found two merge blockers:

  1. Decimal interpolation is incorrect for values that cannot be represented exactly as float64. A package-local regression with DECIMAL128 values 9007199254740993.00 and 9007199254740994.00 at p = 0 expects 9007199254740993.000, but the current code returns 9007199254740994.048. This is user-visible corruption, including at the exact min boundary.
  2. The executor is not approximate or bounded: it embeds the median executor, retains every non-NULL value for every group, serializes all retained rows as intermediate state, and copies them all again during finalize. Therefore both local state and distributed shuffle are O(rows), with an additional O(rows) Go-heap allocation outside the mpool during flush. That defeats the scale motivation of approx_percentile and can OOM on the p95/p99 observability workloads this feature targets. Please use a bounded, mergeable sketch (for example t-digest/KLL), or expose/document this as an exact percentile API rather than approx_percentile.

Please also add a realistic regression (10K+ rows with duplicates and NULLs, including partial-state merge) and large DECIMAL64/128 cases above 2^53. Existing tests pass, but the largest dataset is only 20 rows and does not exercise either blocker.

frac := idx - float64(lo)

// Use float64-based interpolation for accuracy.
fLo := types.Decimal128ToFloat64(vLo, argScale)

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.

[blocker] Converting Decimal128 through float64 corrupts valid decimal inputs. Repro: values 9007199254740993.00, 9007199254740994.00, p=0; expected 9007199254740993.000, actual 9007199254740994.048. The same precision loss affects general interpolation (and Decimal64 once its significant digits exceed float64 precision), so a p=0 special case alone would not close this. Please keep the interpolation in decimal/fixed-point arithmetic and add >2^53 regressions.

// --- Executor types ---

type approxPercentileNumericExec[T numeric] struct {
medianColumnExecSelf[T, float64]

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.

[blocker] Reusing medianColumnExecSelf makes this aggregate retain every input value per group. Its inherited intermediate-state methods also serialize every value, and collectMedianValues allocates another complete []T at finalize. Thus approx_percentile has O(rows) state/shuffle and roughly doubles peak local storage instead of providing a bounded mergeable approximation. This needs a bounded sketch (or an exact-percentile API/name with explicit resource semantics) before it is safe for the intended large observability rollups.

@aunjgr aunjgr 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.

This implementation retains every input row, serializes unbounded intermediate state, and converts Decimal128 interpolation through float64, corrupting values above 2^53. PR #25881 is the bounded replacement and Mergify reports that this PR blocks evaluation of it. Please close this PR in favor of #25881.

@aunjgr aunjgr 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.

This implementation retains every input row, serializes unbounded intermediate state, and converts Decimal128 interpolation through float64, corrupting values above 2^53. PR #25881 is the bounded replacement and Mergify reports that this PR blocks evaluation of it. Please close this PR in favor of #25881.

This branch was previously deployed

1 inactive deployment
ci — ad34b977 Deployed Jul 20, 2026 by VioletQwQ-0 via Matrixone Utils CI / Coverage #41441
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Percentile / quantile aggregate functions (p95 / p99)

6 participants