nooneuse opened a new pull request, #71067:
URL: https://github.com/apache/doris/pull/71067

   ### Background
   
   Apache Doris stores and queries serialized Apache DataSketches HLL sketches 
via `datasketches_hll_union_agg(sketch [, lg_max_k])` (#63143, #67469) and 
`datasketches_hll_downsample(sketch, lg_k [, tgt_type])` (#69257). Because 
`datasketches_hll_union_agg` outputs a scalar `DOUBLE` cardinality estimate 
rather than a mergeable sketch, its `RollUpTrait.canRollUp()` returns `false`. 
As a result, asynchronous materialized views (MTMVs) cannot pre-aggregate 
DataSketches HLL columns for transparent rollup rewrites.
   
   ### What problem does this PR solve?
   
   Issue Number: TODO(author): the issue in issue-feature-hll_sketch_rollup.md
   Related PR: #63143 (introduces datasketches_hll_union_agg), #67469 (adds 
configurable lg_max_k to datasketches_hll_union_agg), #69257 (adds 
datasketches_hll_downsample and shared HLL utility)
   PR Type: Feature
   
   Problem Summary:
   
   Users ingesting DataSketches HLL sketches at minute granularity need 
pre-aggregated MTMVs that transparently serve coarser queries, such as hourly 
cardinality estimates. Users get `datasketches_hll_union(sketch [, lg_max_k [, 
tgt_type]])` (alias `ds_hll_union`), preserving the first argument's type so 
MTMV expressions match without implicit casts, alongside 
`DataSketchesHllRollupHandler` in Nereids. Sixty-five percent of added lines 
are unit and regression tests; the remaining production code spans BE aggregate 
state and serialization, FE constant validation, and multi-argument 
precision-checked MTMV rewriting (`Kq_eff <= Kmv_eff`). Existing queries and 
functions are unaffected after an upgrade.
   
   ```sql
   -- Minute-level MTMV:
   datasketches_hll_union(sk) AS sk_union
   -- Coarser hourly query rewritten transparently to use sk_union:
   datasketches_hll_union_agg(sk)  -->  datasketches_hll_union_agg(sk_union)
   ```
   
   ### Details
   
   - **Change map:** +1681 −9 lines across 18 files, of which +1093 (65%) are 
tests: +618 in unit tests, +403 in two regression suites, and +72 in 
auto-generated `.out` fixtures. Production code is +588 −9 in three parts:
     1. BE aggregate state, `VarargsExpression` nullable aggregate execution, 
and shared `tgt_type` parsing (`+247 −9` in 
`aggregate_function_datasketches_hll_union_agg.{h,cpp}`, 
`datasketches_hll_util.{h,cpp}`, and `function_datasketches_hll.cpp`). Read it 
first for runtime semantics.
     2. FE Nereids expression `DataSketchesHllUnion`, arg0-preserving signature 
filtering, constant validation, and builtin/visitor registration (`+238`).
     3. Nereids MTMV rollup handler `DataSketchesHllRollupHandler` and rule 
registration (`+103`).
   - **Scope:** Supports `datasketches_hll_union(sketch [, lg_max_k [, 
tgt_type]])` (`STRING`, `VARCHAR`, `VARBINARY`; optional constant `lg_max_k` in 
`[7, 21]` and `tgt_type` in `{HLL_4, HLL_6, HLL_8}`) and Nereids async MTMV 
transparent rollups (`datasketches_hll_union_agg -> datasketches_hll_union` and 
cascading `datasketches_hll_union -> datasketches_hll_union`). Synchronous MVs 
(`CREATE MATERIALIZED VIEW`), native storage aggregate column types, and 
`_state`/`_merge`/`_union` combinator MV handlers are out of scope. Invalid 
arguments fail analysis with `AnalysisException`; corrupted sketches fail 
execution with `CORRUPTION`.
   - **Design:** Preserves arg0's type and uses `NullableAggregateFunction` 
semantics (NULL on empty or all-NULL groups; compact empty sketch of `lg_max_k` 
or `12` when all non-NULL rows are empty sketches). Alternatives rejected: 
fixing output to `VARBINARY`/`STRING` (implicit casts break MV expression 
matching), returning an empty sketch on all-NULL groups (violates user 
expectation and SQL NULL rollup semantics), and relaxing 
`MappingRollupHandler`'s single-argument `Any.INSTANCE` check instead of adding 
`DataSketchesHllRollupHandler` between `DirectRollupHandler` and 
`MappingRollupHandler` to enforce `Kq_eff <= Kmv_eff` (omitted `lg_max_k` = 
`21`, `tgt_type` ignored). Proposed in `issue-feature-hll_sketch_rollup.md`; 
not discussed yet.
   - **Usage:**
   
     ```sql
     CREATE MATERIALIZED VIEW mv_min_hll
     BUILD IMMEDIATE REFRESH COMPLETE ON MANUAL
     DISTRIBUTED BY RANDOM BUCKETS 2
     PROPERTIES ('replication_num' = '1')
     AS
     SELECT date_trunc(event_ts, 'hour') AS hour_ts,
            date_trunc(event_ts, 'minute') AS min_ts,
            k,
            datasketches_hll_union(sk, 12, 'HLL_8') AS sk_union
     FROM ds_hll_mv_events
     GROUP BY date_trunc(event_ts, 'hour'), date_trunc(event_ts, 'minute'), k;
   
     -- Rewritten to datasketches_hll_union_agg(sk_union, 8) since 8 <= 12:
     SELECT date_trunc(event_ts, 'hour') AS hour_ts, k,
            CAST(ROUND(datasketches_hll_union_agg(sk, 8)) AS BIGINT) AS uv
     FROM ds_hll_mv_events
     GROUP BY date_trunc(event_ts, 'hour'), k;
     ```
   
   - **Default behavior:** Always available when MTMV rewrite is enabled. 
`tgt_type` defaults to `HLL_4`; omitted `lg_max_k` defaults to `21` (narrowing 
dynamically to input sketch `lgK`, minimum `7`); all-empty-sketch groups emit 
an empty compact sketch of `lg_max_k` or `12`; empty or all-NULL groups return 
`NULL`.
   - **Compatibility:** During rolling upgrades, queries or MTMVs calling 
`datasketches_hll_union` require upgraded BEs (older BEs fail with an unknown 
function error rather than returning wrong values). Existing 
`datasketches_hll_union_agg` and `datasketches_hll_downsample` behavior, 
Thrift/Protobuf definitions, storage formats, and EditLog/image metadata are 
unchanged, so downgrades remain safe when no MTMV uses `datasketches_hll_union`.
   - **Follow-up plan:** Synchronous MV support, native storage aggregate 
column types, and explicit combinator rollup handlers remain for follow-up 
phases.
   
   ### Testing
   
   - FE unit tests (`DataSketchesHllUnionAggTest`, `DataSketchesHllUnionTest`, 
`DataSketchesHllRollupHandlerTest`, `InferAggNotNullTest`): 34/34 passed 
locally inside the ASAN build container on commit `1467f4127b`, verifying 
arg0-matching signatures, constant validation, `NullableAggregateFunction` 
empty-group nullability, and `Kq_eff <= Kmv_eff` rollup rules.
   - BE unit tests 
(`AggregateFunctionDataSketchesHllUnionAggTest.*:FunctionDataSketchesHllDownsampleTest.*`,
 run locally in ASAN with `LSAN_OPTIONS` suppression for the OpenMP 
`___kmp_allocate_align` 352-byte teardown allocation): 69/69 passed on commit 
`1467f4127b`, covering `STRING`/`VARBINARY` outputs, `lg_max_k`/`tgt_type` 
preservation across serialize/deserialize/merge, all-empty-sketch output, 
invalid `tgt_type`, and all-NULL groups.
   - Regression suites 
`query_p0/sql_functions/aggregate_functions/test_datasketches_hll_union.groovy` 
and 
`nereids_rules_p0/mv/agg_with_roll_up/datasketches_hll_union_roll_up.groovy`: 
generated `.out` fixtures with `-genOut` and passed verification reruns without 
`-genOut` locally against a 1-FE/1-BE ASAN cluster on commit `1467f4127b` 
(covering positive/negative inputs, NULL/empty semantics, MTMV hit for `Kq <= 
Kmv`, cascading rollup, and rewrite rejection when `Kq > Kmv` or MV uses 
`datasketches_hll_union_agg`); both directories run in `p0` CI pipelines.
   
   ### Notes for Reviewers
   
   - `AggregateFunctionDataSketchesHllUnion` in BE inherits both 
`VarargsExpression` and `NullableAggregateFunction` because 
`be/src/exprs/aggregate/helpers.h` dispatches varargs nullable aggregates only 
when `std::is_base_of_v<NullableAggregateFunction, ...>` holds.
   - `DataSketchesHllUnionData::read()` deserializes parameters into local 
variables and checks `if (!params_set && rhs_params_set)` so cumulative 
deserialization preserves initialized parameters across merges.
   - `DataSketchesHllUnionAgg.canRollUp()` stays `false` because it returns 
`DOUBLE`; only `DataSketchesHllUnion` returns a mergeable sketch (`canRollUp() 
== true`).
   
   ### Release note
   
   Added the `datasketches_hll_union` (alias `ds_hll_union`) aggregate function 
to merge serialized Apache DataSketches HLL sketches into a compact serialized 
sketch of matching type, with transparent Nereids async materialized view 
(MTMV) rollup support for `datasketches_hll_union_agg` and cascading 
`datasketches_hll_union` queries.
   
   ### Check List (For Author)
   
   - Behavior changed: No
   - Does this need documentation: Yes (new aggregate function documentation 
planned in apache/doris-website)
   - Pre-submission status: Ready
   
   ### AI Disclosure
   
   - Tool: Antigravity
   - Generated: design document, FE/BE implementation, unit and regression tests
   - Human review: not stated


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to