morrySnow commented on code in PR #59972:
URL: https://github.com/apache/doris/pull/59972#discussion_r3662340119
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AsyncMaterializationContext.java:
##########
@@ -56,6 +57,7 @@ public class AsyncMaterializationContext extends
MaterializationContext {
private static final Logger LOG =
LogManager.getLogger(AsyncMaterializationContext.class);
private final MTMV mtmv;
private Map<MTMVRelatedTableIf, Map<String, Set<String>>>
partitionMultiFlatMap;
Review Comment:
**⚠️ Thread safety:** `coveredQueryUsedBaseTablePartitionMap` (and
`partitionMultiFlatMap` at line 10) are mutable instance fields accessed in
`calculatePartitionMappings()` without any synchronization. In concurrent
query-rewrite scenarios, multiple threads may call
`calculatePartitionMappings()` on the same `AsyncMaterializationContext`
instance, leading to:
1. **Visibility issues** – writes by one thread may not be visible to
another (fields are not `volatile`).
2. **Check-then-act races** – `isPartitionMappingsCovered()` reads
`partitionMultiFlatMap`, and moments later another thread could mutate both
cached maps.
3. **Concurrent `HashMap` modification** – `mergeCoveredPartitions()` calls
`coveredPartitions.addAll()` while `isTableCovered()` may be reading, causing
`ConcurrentModificationException` or silent corruption.
Consider using `synchronized` on `calculatePartitionMappings`, or
`ConcurrentHashMap` with `computeIfAbsent`/`merge`, or document that this class
requires external synchronization.
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AsyncMaterializationContext.java:
##########
@@ -202,6 +211,58 @@ public Map<MTMVRelatedTableIf, Map<String, Set<String>>>
calculatePartitionMappi
.addAll(set);
}
}
+ mergeCoveredPartitions(effectiveQueryUsedBaseTablePartitionMap,
pctTables);
return partitionMultiFlatMap;
}
+
+ private boolean isPartitionMappingsCovered(Map<List<String>, Set<String>>
effectiveQueryUsedBaseTablePartitionMap,
+ Set<MTMVRelatedTableIf> pctTables) {
+ if (partitionMultiFlatMap == null) {
+ return false;
+ }
Review Comment:
**Minor:** Double map lookup with `containsKey` + `get`. This could be
simplified to:
```java
Set<String> queryUsedPartitions =
effectiveQueryUsedBaseTablePartitionMap.get(tableQualifiers);
```
(The same pattern appears at position 77 in `mergeCoveredPartitions`.)
##########
fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java:
##########
@@ -530,15 +553,25 @@ public Map<String, PartitionKeyDesc>
generateMvPartitionDescs() {
* @return mvPartitionName ==> pctTable ==> pctPartitionName
* @throws AnalysisException
*/
- public Map<String, Map<MTMVRelatedTableIf, Set<String>>>
calculatePartitionMappings() throws AnalysisException {
+ public Map<String, Map<MTMVRelatedTableIf, Set<String>>>
calculatePartitionMappings(
+ Map<List<String>, Set<String>> queryUsedBaseTablePartitionMap)
throws AnalysisException {
if (mvPartitionInfo.getPartitionType() ==
MTMVPartitionType.SELF_MANAGE) {
return Maps.newHashMap();
}
long start = System.currentTimeMillis();
+ // For EXPR-type partitions with RANGE base tables, expand the
query-used partition
+ // filter to MV partition granularity. This ensures complete partition
mappings per
+ // MV partition (needed for isSyncWithPartitions correctness) while
skipping
+ // irrelevant MV partitions entirely (the performance optimization).
+ // For nested MVs where pctTable is not in the filter, the expanded
map is empty,
+ // so the pipeline runs without filtering (full computation) — correct
behavior.
Review Comment:
**Potentially redundant `getEffectiveQueryUsedBaseTablePartitionMap` call:**
In the `AsyncMaterializationContext` path,
`mtmv.getEffectiveQueryUsedBaseTablePartitionMap(...)` is called first in
`calculatePartitionMappings` for the coverage check (via the public overload,
which may internally call `getAndCopyPartitionItems()`), and then
`this.mtmv.calculatePartitionMappings(queryUsedBaseTablePartitionMap)` calls
`getEffectiveQueryUsedBaseTablePartitionMap(...)` again (via the private
overload, also with `getAndCopyPartitionItems`). For large partition counts,
these redundant copies add up. Consider passing the pre-computed
`mvPartitionItems` through from the outer caller.
##########
fe/fe-core/src/main/java/org/apache/doris/catalog/MTMV.java:
##########
@@ -530,15 +553,25 @@ public Map<String, PartitionKeyDesc>
generateMvPartitionDescs() {
* @return mvPartitionName ==> pctTable ==> pctPartitionName
* @throws AnalysisException
Review Comment:
**Missing `@param` in Javadoc:** The new `queryUsedBaseTablePartitionMap`
parameter should be documented — explain that an empty map means "compute all"
and a non-empty map filters partition generation to only the partitions the
query touches. This is important for callers who need to understand the
semantics.
##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/exploration/mv/AsyncMaterializationContext.java:
##########
@@ -202,6 +211,58 @@ public Map<MTMVRelatedTableIf, Map<String, Set<String>>>
calculatePartitionMappi
.addAll(set);
}
}
+ mergeCoveredPartitions(effectiveQueryUsedBaseTablePartitionMap,
pctTables);
return partitionMultiFlatMap;
}
+
+ private boolean isPartitionMappingsCovered(Map<List<String>, Set<String>>
effectiveQueryUsedBaseTablePartitionMap,
+ Set<MTMVRelatedTableIf> pctTables) {
+ if (partitionMultiFlatMap == null) {
+ return false;
+ }
+ for (MTMVRelatedTableIf pctTable : pctTables) {
+ List<String> tableQualifiers = pctTable.getFullQualifiers();
+ Set<String> queryUsedPartitions =
effectiveQueryUsedBaseTablePartitionMap.containsKey(tableQualifiers)
+ ?
effectiveQueryUsedBaseTablePartitionMap.get(tableQualifiers)
+ : null;
+ if (!isTableCovered(tableQualifiers, queryUsedPartitions)) {
+ return false;
+ }
+ }
+ return true;
+ }
Review Comment:
**Fragile null-sentinel pattern:** `isTableCovered` relies on
`containsKey()` + `get()` to distinguish "not present" from "present with null
value" (where `null` means "full/complete mapping was done"). This is correct
given the `containsKey` guard, but is fragile without synchronization (TOCTOU
between `containsKey` and `get`). Consider using an explicit sentinel like
`Collections.emptySet()` as a marker for fully-covered tables instead of
overloading `null`.
##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPartitionExpander.java:
##########
@@ -0,0 +1,122 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.mtmv;
+
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionKey;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.RangePartitionItem;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.datasource.mvcc.MvccSnapshot;
+import org.apache.doris.datasource.mvcc.MvccUtil;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Utility to expand query-used partition filters to MV partition granularity
+ * using Range.encloses(), avoiding expensive dateTrunc / strToDate /
dateIncrement
+ * per-partition operations in the rollup pipeline.
+ * Separated from MTMV to keep a lightweight dependency tree for testability —
+ * loading this class does not trigger MTMV → OlapTable → CloudReplica class
loading.
+ */
+public class MTMVPartitionExpander {
+
+ /**
+ * Expand queryUsedPartitions to MV partition granularity for RANGE base
tables.
+ * For example, if MV is monthly partitioned (date_trunc(month)) and base
table is daily:
+ * - Query uses p_20250115 (Jan 15)
+ * - Find MV partition p_202501 that encloses [20250115, 20250116)
+ * - Expand to ALL daily partitions within p_202501's range [20250101,
20250201)
+ * - Result: {p_20250101, p_20250102, ..., p_20250131}
+ */
+ public static Map<List<String>, Set<String>>
expandToMvPartitionGranularity(
+ Map<List<String>, Set<String>> queryUsedBaseTablePartitionMap,
+ Map<String, PartitionItem> mvPartitionItems,
+ Set<MTMVRelatedTableIf> pctTables) throws AnalysisException {
+ List<Range<PartitionKey>> mvRanges = new
ArrayList<>(mvPartitionItems.size());
+ for (PartitionItem item : mvPartitionItems.values()) {
+ mvRanges.add(((RangePartitionItem) item).getItems());
+ }
+
+ Map<List<String>, Set<String>> expanded = Maps.newHashMap();
+ for (MTMVRelatedTableIf pctTable : pctTables) {
+ List<String> qualifiers = pctTable.getFullQualifiers();
+ Set<String> queryUsedPartitions =
queryUsedBaseTablePartitionMap.get(qualifiers);
+ if (queryUsedPartitions == null) {
+ continue;
+ }
+
+ Optional<MvccSnapshot> snapshot =
MvccUtil.getSnapshotFromContext(pctTable);
+ if (pctTable.getPartitionType(snapshot) != PartitionType.RANGE) {
+ expanded.put(qualifiers, queryUsedPartitions);
+ continue;
+ }
+
+ Map<String, PartitionItem> basePartitionItems =
pctTable.getAndCopyPartitionItems(snapshot);
+
+ List<Range<PartitionKey>> relevantMvRanges = new ArrayList<>();
+ for (String queriedBasePartition : queryUsedPartitions) {
+ PartitionItem baseItem =
basePartitionItems.get(queriedBasePartition);
+ if (baseItem == null) {
+ continue;
+ }
+ Range<PartitionKey> baseRange = ((RangePartitionItem)
baseItem).getItems();
+ for (Range<PartitionKey> mvRange : mvRanges) {
+ if (mvRange.encloses(baseRange)) {
+ if (!relevantMvRanges.contains(mvRange)) {
Review Comment:
**Performance nit:** `relevantMvRanges.contains(mvRange)` on an `ArrayList`
is O(n) per iteration. For typical workloads (a query covering 1–2 months) this
is negligible, but consider using a `LinkedHashSet` or a `HashSet`
side-structure for deduplication if queries touching many MV ranges are
expected.
##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPartitionExpander.java:
##########
@@ -0,0 +1,122 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.mtmv;
+
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionKey;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.RangePartitionItem;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.datasource.mvcc.MvccSnapshot;
+import org.apache.doris.datasource.mvcc.MvccUtil;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Utility to expand query-used partition filters to MV partition granularity
+ * using Range.encloses(), avoiding expensive dateTrunc / strToDate /
dateIncrement
+ * per-partition operations in the rollup pipeline.
+ * Separated from MTMV to keep a lightweight dependency tree for testability —
+ * loading this class does not trigger MTMV → OlapTable → CloudReplica class
loading.
+ */
+public class MTMVPartitionExpander {
+
+ /**
+ * Expand queryUsedPartitions to MV partition granularity for RANGE base
tables.
+ * For example, if MV is monthly partitioned (date_trunc(month)) and base
table is daily:
+ * - Query uses p_20250115 (Jan 15)
+ * - Find MV partition p_202501 that encloses [20250115, 20250116)
+ * - Expand to ALL daily partitions within p_202501's range [20250101,
20250201)
+ * - Result: {p_20250101, p_20250102, ..., p_20250131}
+ */
+ public static Map<List<String>, Set<String>>
expandToMvPartitionGranularity(
+ Map<List<String>, Set<String>> queryUsedBaseTablePartitionMap,
+ Map<String, PartitionItem> mvPartitionItems,
+ Set<MTMVRelatedTableIf> pctTables) throws AnalysisException {
+ List<Range<PartitionKey>> mvRanges = new
ArrayList<>(mvPartitionItems.size());
+ for (PartitionItem item : mvPartitionItems.values()) {
+ mvRanges.add(((RangePartitionItem) item).getItems());
Review Comment:
**Unchecked cast assumption:** The cast `(RangePartitionItem) item` assumes
all MV partition items are `RangePartitionItem`. The caller in
`MTMV.getEffectiveQueryUsedBaseTablePartitionMap()` guards this by only
expanding for `MTMVPartitionType.EXPR`, which always produces range partitions.
However, this invariant is implicit. Consider either:
- Adding a `@param mvPartitionItems` note that all items must be
`RangePartitionItem` instances, or
- Adding an `instanceof` guard with a clear error message to fail fast with
a diagnostic rather than a cryptic `ClassCastException` if a non-RANGE item
ever reaches here.
--
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]