Repository navigation
Conversation
|
Workflow [PR], commit [c098044] Summary: ❌
AI ReviewSummaryReviewed #122308 at PR MetadataThe
Missing context / blind spots
Findings💡 Nits
Final Verdict✅ Approve — no blocker or major findings. The metadata correction is non-blocking. |
|
|
||
| void buildQueryGraph(QueryGraphBuilder & query_graph, QueryPlan::Node & node, QueryPlan::Nodes & nodes, int join_steps_limit); | ||
|
|
||
| static String dumpStatsForLogs(const RelationStats & stats) |
There was a problem hiding this comment.
Merged to src/Processors/QueryPlan/Optimizations/RelationStatisticsUtils.cpp
| namespace | ||
| { | ||
|
|
||
| String dumpStatsForLogs(const RelationStats & stats) |
There was a problem hiding this comment.
Merged to src/Processors/QueryPlan/Optimizations/RelationStatisticsUtils.cpp
| namespace DB | ||
| { | ||
|
|
||
| String dumpRelationStatsForLogs(const RelationStats & stats) |
There was a problem hiding this comment.
Moved from src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp and src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp
| #include <Processors/QueryPlan/ReadFromMergeTree.h> | ||
| #include <Processors/QueryPlan/Serialization.h> | ||
| #include <Processors/Transforms/JoiningTransform.h> | ||
| #include <Processors/QueryPlan/Optimizations/Optimizations.h> |
| for (const auto & [column_name, estimator] : column_estimators) | ||
| { | ||
| if (!isCompatibleStatistics(metadata, estimator.stats, column_name)) | ||
| continue; |
There was a problem hiding this comment.
Perform type check on statistics.
A typical sequence is:
- Statistics are collected for column
x UInt32. ALTER TABLE ... MODIFY COLUMN x Int64changes the table metadata.- Existing data parts and their stored statistics may still describe x as
UInt32until the mutation is materialized or parts are rewritten.
During that interval, using the old NDV, min/max, or null statistics for the new logical column type may be invalid. isCompatibleStatistics() compares the statistic’s stored type with the current metadata and skips mismatches.
| /// Constrain the inner-product estimate to the join semantics (outer joins keep the preserved side, | ||
| /// semi/anti/any bound it). Applied after the join-order hint so a hint cannot exceed a semantic | ||
| /// upper bound (e.g. a semi join above its preserved-side row count). | ||
| const auto & join_operator = join_step.getJoinOperator(); |
There was a problem hiding this comment.
Moving the definition up to enable use in line 259
| #include <fmt/format.h> | ||
| #include <Common/Exception.h> | ||
| #include <Common/SipHash.h> | ||
| #include <Common/assert_cast.h> |
| rhs_estimation ? toString(rhs_estimation.value()) : "unknown"); | ||
|
|
||
| if (lhs_extimation && rhs_extimation && lhs_extimation < rhs_extimation) | ||
| if (lhs_estimation && rhs_estimation && lhs_estimation < rhs_estimation) |
| stats.null_fraction.reset(); | ||
| } | ||
| mapped[outputs[output_lineage.output_position]->result_name] = stats; | ||
| mapped[output.result_name] = stats; |
There was a problem hiding this comment.
Make sure statistics of ambiguous column name don't get mixed up. We'd have to make the map position-based to obtain the correct statistics.
We got a similar issue in #121647 (Resolve JOIN runtime filter keys by header position) iirc.
After `ALTER TABLE ... MODIFY COLUMN`, a part keeps statistics of the old type until the mutation rewrites it. `ConditionSelectivityEstimatorBuilder` kept the type of the first part and skipped parts of another type, while `total_rows` still counted every part. With the current type first - the usual state while a mutation runs, since it rewrites the leading parts first - the column got the NDV and value range of the rewritten parts only. With the old type first, `isCompatibleStatistics` rejected the column. The result depended on the part order. Drop a column whose parts carry statistics for different types for the whole snapshot. Parts with the same type but a different set of statistics (e.g. `MODIFY STATISTICS` not materialized yet) keep the previous behavior.
A Cascades read adds an entry to the column statistics of every column it reads, to carry the column width, whether the column has statistics or not. Such an entry has `num_distinct_values = 0`, but `keyDistinctValues` took any entry as a known NDV: `GROUP BY` or `DISTINCT` on a column without statistics - including one whose statistics were rejected for an outdated type - estimated a single group with `max_row_count = 0`. The join derivation copied the zero into the output key NDV, where the shared key update erased the other side's known NDV, and `INTERSECT` erased a known NDV the same way. Add `knownDistinctValues`, which treats zero as unknown, and use it in all three places, so each falls back as it does for a missing entry: 10% of the input rows for a group key, the row count for a join key, no bound for `INTERSECT`. `remapColumnStats` added the +1 of a null-aware hop (e.g. `assumeNotNull`, a `CAST` dropping `Nullable`) to an unknown zero as well, which turned it into a known NDV of 1 and kept such keys at a single group. Keep an unknown NDV unknown there. Test changes: - 04926 case 3a (join key without an NDV hint) now gets the same plan as case 3; it still checks that the aggregation is not pushed down. - 03836 Q09 groups by `toYear(o_orderdate)`; its hint now carries the SF100 `o_orderdate` NDV of the base hint, which keeps the plan.
This comment was marked as outdated.
This comment was marked as outdated.
hanfei1991
left a comment
There was a problem hiding this comment.
We have some bug fix and comestic changes in this PR. Could we seperate them to make it easier to review?
| return; | ||
|
|
||
| has_data = true; | ||
| if (columns_with_mixed_types.contains(column_name)) |
There was a problem hiding this comment.
Could you please give me an example to reproduce some bug for unequal types? because for some type of unequal types it's OK, for example Int32->Int64.
| result.rows = total_rows; | ||
| for (const auto & [column_name, estimator] : column_estimators) | ||
| { | ||
| if (!isCompatibleStatistics(metadata, estimator.stats, column_name)) |
There was a problem hiding this comment.
Could you write a stateless test to cover this case? I couldn't figure out a bug here right now.
cv4g
left a comment
There was a problem hiding this comment.
Thank you Han Fei, I'll look into the two issues not covered by tests yet
…Y COLUMN A part keeps the statistics of the type it stores. After a metadata-only `ALTER TABLE ... MODIFY COLUMN` (e.g. `Enum8` -> `Int8`) they still describe the values a read returns, but the estimator rejected every statistic whose type was not equal to the current one, in the filtered and now also in the unfiltered profile. Accept the conversions that keep the representation, like the statistics part pruning and the skip indexes do, and keep rejecting those that change the values (e.g. `DateTime` -> `Date` for a part detached during the `ALTER`). Move the Cascades regression for a rejected sketch from 05394 to a dedicated test, which now uses a value-changing conversion.
…nt types Statistics of different column types cannot be merged. The estimator builder kept the type of the first part and skipped the others, so the result depended on the part order, and the previous commit of this PR dropped the column altogether, also after a metadata-only `MODIFY COLUMN` followed by inserts, until all old parts were merged. The builder now gets the metadata of the read. It skips statistics that do not describe the values of the current type, and prefers the statistics of the current type, which all parts get eventually. Only of two outdated types, which are equally good, the column gets none.
| EXPECT_FALSE(restored->hasNullCount()); | ||
| } | ||
|
|
||
| namespace |
There was a problem hiding this comment.
Kindly prefer writing stateless SQL tests instead of low-level unit tests. The latter are harder to run and expensive to maintain.
|
|
||
| -- Q09: Product type profit measure (part, supplier, lineitem, partsupp, orders, nation) | ||
| -- Filter: p_name LIKE '%green%' -> ~1.13M parts (real selectivity ~5.6%). | ||
| -- `o_orderdate` keeps its SF100 NDV: the `o_year` group key inherits it, without it the key would |
There was a problem hiding this comment.
Someone reading the new comment in a few weeks from now will not be able to understand what it means, better remove it.
| estimator->total_rows += rows; | ||
| } | ||
|
|
||
| /// Compare type names as `ColumnStatistics::structureEquals` does: `Bool` and `UInt8` are equal under |
There was a problem hiding this comment.
I feel this code should go somewhere into existing function isCompatibleStatistics.
There was a problem hiding this comment.
Done. There is a new matchStatisticsType that returns an enum StatisticsTypeMatch (equal, compatible, incompatible) that is also called by isCompatibleStatistics now.
| private: | ||
| bool has_data = false; | ||
| ConditionSelectivityEstimatorPtr estimator; | ||
| /// Columns whose parts carry statistics for different data types. They get no statistics, see `addStatistics`. |
There was a problem hiding this comment.
How can the parts of a column carry statistics for different data types? In ALTER TYPE, no? In any case this is an edge case and we should rather do something more simple and more dumb like calculating a best-effort estimation instead of adding special handling for them (that needs its own member variable).
There was a problem hiding this comment.
Yes, it's ALTER TYPE until the mutation rewrites the parts. This can also happen when a part is attached after an alter type it seems. Also column type changes between types with the identical on disk serialization are metadata-only and not converted eagerly by mutation.
I simplified it in 5711d6de48ec: The builder now skips incompatible statistics, merges those of the same structure, and prefers those of the column type. Statistics it can neither merge nor prefer are skipped, like those of a part with the same type but a different set of statistics. That can happen after aMODIFY STATISTICS that is not materialized in all parts yet.
With 10000 distinct values the `uniq_v2` sketch (`uniqCombined64` with precision 12) is in its HyperLogLog mode and estimates 9826, so the `GROUP BY` estimate before the `ALTER` never matched `~10000.0`. Check that it is close to 10000 instead, which still tells the statistics from the fallback to 10% of the rows after the `ALTER`.
Two outputs of a query can share a name only when they are the same expression (e.g. `SELECT k, k`, or `SELECT k, j AS k`, where `k` resolves to the alias), and then their statistics are the same as well. Dropping them made `(k, k) INTERSECT DISTINCT (x, y)` estimate 1000 rows, the fallback, instead of 5, the exact number of rows, as before. Restore the previous behavior of `remapColumnStats` and of the `INTERSECT` derivation.
A join took the zero NDV of a key without statistics as known, and narrowing the join keys to the smaller NDV erased the known NDV of the other side. A `GROUP BY` on that key above the join was estimated at 1000000 groups on master, and at the 10 groups it has now.
While the mutation of a `DateTime` -> `Date` conversion waits, the part keeps the `DateTime` statistics, which count 9826 distinct values for a column with 1. The join-order optimizer used them without a filter and estimated a join that returns 100000 rows at 1.02 thousand rows on master; with a filter they were rejected. Both estimates are 100.00 thousand rows now.
After a metadata-only `UInt32` -> `DateTime` conversion followed by inserts, the old and the new partitions store `ts` with different types. Only the statistics of the first part's type were used, and with a filter those of the old type were rejected: the same data gave 198.22 thousand, 201.00 thousand and 2.01 thousand rows on master, depending on the part order and the filter. The current type is preferred now, and all three are 2.01 thousand rows.
The estimator builder compared statistics types with the metadata in `isCompatibleStatistics` and `hasCurrentType`, with each other in `haveSameDataType`, and kept the columns whose parts carried two outdated types in a member of its own, so that they got no statistics. `matchStatisticsType` now tells whether the type of statistics is equal to the column type (by name, as `structureEquals` compares them), compatible with it (a read converts the values without changing them), or incompatible, and `isCompatibleStatistics` is built on it. The builder skips incompatible statistics, merges those of the same structure, prefers those of the column type, and otherwise keeps the first ones, as it already did for a different set of statistics. With two outdated types, or without metadata, the column now keeps the statistics of the first part instead of none: they still describe the values, only of a subset of the parts. #122308 (comment) #122308 (comment)
AI review of a later commit does not approve the PR, see the AI Review comment.
Extracted from #121736: three independent fixes of the estimates that the planner derives from column statistics, and a few cosmetic changes. Each fix has a stateless test that fails on master. Query results do not change, only the estimates used by join reordering and by the Cascades optimizer.
1. Statistics of an outdated column type
After
ALTER TABLE ... MODIFY COLUMNwith a conversion that changes the values (e.g.DateTime->Date), a part keeps the column of the old type and its statistics until a mutation rewrites it: while the mutation is running or waiting, for good afterKILL MUTATION, or for a part attached from before theALTER. A read converts the values, but the statistics still describe the old ones. The relation profile without a filter did not check the type of the statistics, and Cascades passed no metadata to the estimator, so these statistics were used as they are. With a filter, they were rejected.isCompatibleStatisticsaccepts the conversions that keep the values (isRepresentationPreservingConversion, as statistics-based part pruning and skip indexes do, e.g. the metadata-onlyEnum8->Int8), instead of requiring equal types.RelationStatisticsEstimatordoes.Tests:
05617_statistics_outdated_type_join_estimate: aDatecolumn with 1 distinct value keeps theDateTimestatistics of 9826 distinct values while its mutation waits. A join that returns 100000 rows was estimated at 1.02 thousand rows without a filter and 100.00 thousand rows with one; both are 100.00 thousand now.05483_statistics_after_modify_column(metadata-only,converted), and unit tests ingtest_stats.cpp.2. Parts that store a column with different types
Parts can also store a column with different types: after a metadata-only conversion (e.g.
UInt32->DateTime) followed by inserts, until the old parts are merged, which in a table partitioned by time never happens; while a mutation is running; or for a part attached from before theALTER. Statistics of different types cannot be merged.ConditionSelectivityEstimatorBuilderkept the type of the first part and skipped the parts of any other type, so the estimate depended on the part order, and, since the profile with a filter rejected an outdated type, on the filter.The builder now gets the metadata of the read (
IStorage::getConditionSelectivityEstimatortakes it). It skips the statistics that do not describe the current values, and prefers the statistics of the current type, which all parts get eventually. If the parts carry statistics of different outdated types only, the column gets none.Statistics of an old type that keep the values but not their representation, e.g.
Int32->Int64, are still not used: their states cannot be merged with those of the current type, and combining the estimates of different types is left for a follow-up.Tests:
05618_statistics_mixed_part_types_join_estimate: the same data in two tables that differ only in the partition holding the old type. A join that returns 1000 rows was estimated at 198.22 thousand rows with the old data first, 201.00 thousand rows with a filter, and 2.01 thousand rows with the old data last. All three are 2.01 thousand now.05483_statistics_after_modify_column(stale first,stale second,inserted after), and unit tests ingtest_stats.cpp.3. Keys without a known number of distinct values in Cascades
A Cascades read adds an entry to the column statistics of every column it reads, to carry the column width, also for a column without statistics. The number of distinct values (NDV) of such an entry is 0, and several places took it as known:
INTERSECTdid not take a known NDV of a later input when the first input had no known NDV.+1of a null-aware function such asassumeNotNullturned the unknown NDV into a known NDV of 1.They all treat 0 as unknown now, like a missing entry (
knownDistinctValues). As before for a missing entry, a join key without a known NDV is bounded by the row count of its side.Tests:
05394_cascades_group_by_key_without_statistics: e.g. aGROUP BYon a join key with 10 distinct values, whose other side has no statistics, was estimated at 1000000 groups, and at 10 now.04926_cascades_aggregation_pushdown: the plans of cases 3a and 25 change.03836_tpch_join_order_plans: Q09 gets an NDV hint foro_orderdate, which itso_yeargroup key inherits.gtest_column_stats_derivation.cpp.4. Cosmetic changes
Include order,
extimation->estimation, an em dash in a comment, and the name of a lambda in a test. No behavior change.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes the row estimates that the query planner derives from column statistics after
ALTER TABLE ... MODIFY COLUMN. Statistics of parts that still store the old column type are no longer used when they do not describe the current values, and when parts store a column with different types, the estimates no longer depend on the order of the parts or on whether the query has a filter. Also fixes estimates for join keys without statistics in the experimental Cascades optimizer. Better estimates help the planner choose a better join order; query results are not affected.Workflow [PR]
Sync PR [sync-upstream/pr/122308]