hello-stephen commented on code in PR #71158:
URL: https://github.com/apache/doris/pull/71158#discussion_r4804613210


##########
be/src/exec/sink/vrow_distribution.cpp:
##########
@@ -151,6 +164,13 @@ Status VRowDistribution::automatic_create_partition() {
     Status status(Status::create(result.status));
     VLOG_NOTICE << "automatic partition rpc end response " << result;
     if (result.status.status_code == TStatusCode::OK) {
+        // Filling gaps in a UTC bucket can also return existing shifted 
partitions. They
+        // must not become "new" during overwrite or be re-added after 
replacement.
+        // Consecutive buckets can also return the same partition learned by 
an earlier RPC.
+        std::erase_if(result.partitions, [this](const auto& partition) {
+            return _initial_partition_ids.contains(partition.id) ||

Review Comment:
   [P2] Replace reused ranges learned during an overwrite
   
   An `INSERT OVERWRITE ... PARTITION(*)` with auto-create can start with a 
sink plan that lacks the middle range for Jan 4. If another session adds 
`[08:00Z, 16:00Z)` and commits a `10:00Z` row before the overwrite's first 
`02:00Z` partition-creation request, the FE returns the middle with the two 
gaps. The middle is absent from the sink's initial IDs, so it enters 
`_new_partition_ids` and `_replace_overwriting_partition` skips it when a later 
`10:00Z` row arrives. The overwrite can succeed with the old row still present. 
If both rows are buffered before that RPC, replay bypasses replacement as well. 
Carry through which partitions were created for this load and run replacement 
for reused ranges touched on replay or in later batches.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -268,7 +437,7 @@ private static PartitionValue getPartitionFromDate(Type 
partitionColumnType, Lit
             return PartitionValue.MAX_VALUE;
         }
 
-        if (isMinimumTimeStampNs(dateLiteral)) {
+        if (isMinimumTimeStampNs(dateLiteral) || 
partitionColumnType.isTimeStampTz()) {

Review Comment:
   [P2] Skip the unrepresentable leap day when sizing year-zero ranges
   
   On an empty daily TIMESTAMPTZ auto-range table, inserting `0000-02-28 
01:00:00+00:00` from a `-08:00` session now requests the UTC Feb 28 floor. 
Java's `LocalDateTime.plusDays(1)` gives Feb 29 in year zero, which 
`DateLiteral.checkValueValid` rejects. The catch above turns it into 
`MAXVALUE`, so all later timestamps fit the supposed daily partition and no 
later daily partitions are created. The old local projection for this input 
started Feb 27 at 08:00Z and had a representable end. Use March 1 as the next 
representable daily boundary here and reserve `MAXVALUE` for the upper end of 
the supported domain.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -202,50 +263,158 @@ public static Map<String, AddPartitionOp> 
getAddPartitionClauseFromPartitionValu
                             + "_" + 
Integer.toHexString(partitionName.hashCode());
                     }
                 }
+                if (hasTimestampTz) {
+                    partitionName = 
existingListPartitions.getOrDefault(typedKey, partitionName);
+                }
             } else {
                 throw new AnalysisException("now only support range and list 
partition");
             }
 
-            Map<String, String> partitionProperties = Maps.newHashMap();
-            DistributionInfo defaultDistributionInfo = 
olapTable.getDefaultDistributionInfo();
-            DistributionDesc distributionDesc = 
defaultDistributionInfo.toDistributionDesc();
-            if (olapTable.isAutoBucket() && partitionType == 
PartitionType.RANGE) {
-                // Use unified auto bucket calculator
-                AutoBucketCalculator.AutoBucketContext context = new 
AutoBucketCalculator.AutoBucketContext(
-                        olapTable, partitionName, partitionName, false,
-                        defaultDistributionInfo.getBucketNum());
-
-                int bucketsNum = 
AutoBucketCalculator.calculateAutoBucketsWithBoundsCheck(context);
-
-                // Only update distribution if calculation was successful 
(bucketsNum != default)
-                if (bucketsNum != defaultDistributionInfo.getBucketNum()) {
-                    if (defaultDistributionInfo.getType() == 
DistributionInfo.DistributionInfoType.HASH) {
-                        HashDistributionInfo hashDistributionInfo = 
(HashDistributionInfo) defaultDistributionInfo;
-                        List<String> distColumnNames = new ArrayList<>();
-                        for (Column distributionColumn : 
hashDistributionInfo.getDistributionColumns()) {
-                            distColumnNames.add(distributionColumn.getName());
-                        }
-                        distributionDesc = new 
HashDistributionDesc(bucketsNum, distColumnNames);
-                    } else {
-                        distributionDesc = new 
RandomDistributionDesc(bucketsNum);
+            Map<String, PartitionKeyDesc> descriptions = Maps.newHashMap();
+            if (partitionType == PartitionType.RANGE && 
partitionColumn.get(0).getType().isTimeStampTz()
+                    && "date_trunc".equalsIgnoreCase(intervalInfo.fnName)) {
+                descriptions = timestampTzRangePartitions(olapTable, 
partitionInfo, partitionName, partitionKeyDesc,
+                        result);
+            } else {
+                descriptions.put(partitionName, partitionKeyDesc);
+            }
+            for (Map.Entry<String, PartitionKeyDesc> entry : 
descriptions.entrySet()) {
+                if (!result.addPartitionOps.containsKey(entry.getKey())) {
+                    result.addPartitionOps.put(entry.getKey(), 
buildAddPartitionOp(

Review Comment:
   [P2] Check the partition cap before sizing new gaps
   
   One missing row in a yearly auto-bucket table with 10,001 alternating 
minute-long formal ranges can produce more than 10,000 gaps. This loop asks 
`AutoBucketCalculator` to copy and sort the same history and obtain visible 
versions once per gap, with metadata calls in cloud mode. Only afterward does 
`FrontendServiceImpl` reject the plan for exceeding the default limit of 20,000 
partitions. Apply the request limit before sizing new gaps, keeping the 
publication-time check for concurrent changes.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -202,50 +263,158 @@ public static Map<String, AddPartitionOp> 
getAddPartitionClauseFromPartitionValu
                             + "_" + 
Integer.toHexString(partitionName.hashCode());
                     }
                 }
+                if (hasTimestampTz) {
+                    partitionName = 
existingListPartitions.getOrDefault(typedKey, partitionName);
+                }
             } else {
                 throw new AnalysisException("now only support range and list 
partition");
             }
 
-            Map<String, String> partitionProperties = Maps.newHashMap();
-            DistributionInfo defaultDistributionInfo = 
olapTable.getDefaultDistributionInfo();
-            DistributionDesc distributionDesc = 
defaultDistributionInfo.toDistributionDesc();
-            if (olapTable.isAutoBucket() && partitionType == 
PartitionType.RANGE) {
-                // Use unified auto bucket calculator
-                AutoBucketCalculator.AutoBucketContext context = new 
AutoBucketCalculator.AutoBucketContext(
-                        olapTable, partitionName, partitionName, false,
-                        defaultDistributionInfo.getBucketNum());
-
-                int bucketsNum = 
AutoBucketCalculator.calculateAutoBucketsWithBoundsCheck(context);
-
-                // Only update distribution if calculation was successful 
(bucketsNum != default)
-                if (bucketsNum != defaultDistributionInfo.getBucketNum()) {
-                    if (defaultDistributionInfo.getType() == 
DistributionInfo.DistributionInfoType.HASH) {
-                        HashDistributionInfo hashDistributionInfo = 
(HashDistributionInfo) defaultDistributionInfo;
-                        List<String> distColumnNames = new ArrayList<>();
-                        for (Column distributionColumn : 
hashDistributionInfo.getDistributionColumns()) {
-                            distColumnNames.add(distributionColumn.getName());
-                        }
-                        distributionDesc = new 
HashDistributionDesc(bucketsNum, distColumnNames);
-                    } else {
-                        distributionDesc = new 
RandomDistributionDesc(bucketsNum);
+            Map<String, PartitionKeyDesc> descriptions = Maps.newHashMap();
+            if (partitionType == PartitionType.RANGE && 
partitionColumn.get(0).getType().isTimeStampTz()
+                    && "date_trunc".equalsIgnoreCase(intervalInfo.fnName)) {
+                descriptions = timestampTzRangePartitions(olapTable, 
partitionInfo, partitionName, partitionKeyDesc,
+                        result);
+            } else {
+                descriptions.put(partitionName, partitionKeyDesc);
+            }
+            for (Map.Entry<String, PartitionKeyDesc> entry : 
descriptions.entrySet()) {
+                if (!result.addPartitionOps.containsKey(entry.getKey())) {
+                    result.addPartitionOps.put(entry.getKey(), 
buildAddPartitionOp(
+                            olapTable, partitionType, entry.getKey(), 
entry.getValue()));
+                }
+            }
+        }
+        return result;
+    }
+
+    private static AddPartitionOp buildAddPartitionOp(OlapTable olapTable, 
PartitionType partitionType,
+            String partitionName, PartitionKeyDesc partitionKeyDesc) throws 
AnalysisException {
+        Map<String, String> partitionProperties = Maps.newHashMap();
+        DistributionInfo defaultDistributionInfo = 
olapTable.getDefaultDistributionInfo();
+        DistributionDesc distributionDesc = 
defaultDistributionInfo.toDistributionDesc();
+        if (olapTable.isAutoBucket() && partitionType == PartitionType.RANGE) {
+            // Use unified auto bucket calculator
+            AutoBucketCalculator.AutoBucketContext context = new 
AutoBucketCalculator.AutoBucketContext(
+                    olapTable, partitionName, partitionName, false,
+                    defaultDistributionInfo.getBucketNum());
+
+            int bucketsNum = 
AutoBucketCalculator.calculateAutoBucketsWithBoundsCheck(context);
+
+            // Only update distribution if calculation was successful 
(bucketsNum != default)
+            if (bucketsNum != defaultDistributionInfo.getBucketNum()) {
+                if (defaultDistributionInfo.getType() == 
DistributionInfo.DistributionInfoType.HASH) {
+                    HashDistributionInfo hashDistributionInfo = 
(HashDistributionInfo) defaultDistributionInfo;
+                    List<String> distColumnNames = new ArrayList<>();
+                    for (Column distributionColumn : 
hashDistributionInfo.getDistributionColumns()) {
+                        distColumnNames.add(distributionColumn.getName());
                     }
+                    distributionDesc = new HashDistributionDesc(bucketsNum, 
distColumnNames);
+                } else {
+                    distributionDesc = new RandomDistributionDesc(bucketsNum);
                 }
             }
+        }
 
-            SinglePartitionDesc singleRangePartitionDesc = new 
SinglePartitionDesc(true, partitionName,
-                    partitionKeyDesc, partitionProperties);
-            // iff table's storage medium is not equal default storage medium,
-            // should add storage medium in partition properties
-            if 
(!DataProperty.DEFAULT_STORAGE_MEDIUM.equals(olapTable.getStorageMedium())) {
-                
partitionProperties.put(PropertyAnalyzer.PROPERTIES_STORAGE_MEDIUM,
-                        olapTable.getStorageMedium().name());
+        SinglePartitionDesc singleRangePartitionDesc = new 
SinglePartitionDesc(true, partitionName,
+                partitionKeyDesc, partitionProperties);
+        // iff table's storage medium is not equal default storage medium,
+        // should add storage medium in partition properties
+        if 
(!DataProperty.DEFAULT_STORAGE_MEDIUM.equals(olapTable.getStorageMedium())) {
+            partitionProperties.put(PropertyAnalyzer.PROPERTIES_STORAGE_MEDIUM,
+                    olapTable.getStorageMedium().name());
+        }
+        AddPartitionOp addPartitionClause = new AddPartitionOp(
+                singleRangePartitionDesc.translateToPartitionDefinition(),
+                distributionDesc.toDistributionDescriptor(), 
partitionProperties, false);
+        return addPartitionClause;
+    }
+
+    private static Map<PartitionKey, String> 
timestampTzListPartitionNames(OlapTable table,
+            PartitionInfo partitionInfo) {
+        Map<PartitionKey, String> names = Maps.newHashMap();
+        table.readLock();
+        try {
+            // Older writers named partitions with their local offset. Reuse 
the same key even
+            // when that persisted partition's name differs from today's UTC 
spelling.
+            // Scan formal history once per request, not once per missing key. 
ADD still checks
+            // uniqueness under the publication write lock if metadata changes 
after this snapshot.
+            for (Map.Entry<Long, PartitionItem> entry : 
partitionInfo.getIdToItem(false).entrySet()) {
+                String name = table.getPartition(entry.getKey()).getName();
+                for (PartitionKey key : ((ListPartitionItem) 
entry.getValue()).getItems()) {
+                    names.put(key, name);
+                }
             }
-            AddPartitionOp addPartitionClause = new AddPartitionOp(
-                    singleRangePartitionDesc.translateToPartitionDefinition(),
-                    distributionDesc.toDistributionDescriptor(), 
partitionProperties, false);
-            result.put(partitionName, addPartitionClause);
+            return names;
+        } finally {
+            table.readUnlock();
         }
-        return result;
+    }
+
+    private static Map<String, PartitionKeyDesc> 
timestampTzRangePartitions(OlapTable table,
+            PartitionInfo partitionInfo, String canonicalName, 
PartitionKeyDesc requestedDesc, AutoPartitionPlan plan)
+            throws AnalysisException {
+        List<Column> columns = partitionInfo.getPartitionColumns();
+        Range<PartitionKey> requested = Range.closedOpen(
+                
PartitionKey.createPartitionKey(requestedDesc.getLowerValues(), columns),
+                
PartitionKey.createPartitionKey(requestedDesc.getUpperValues(), columns));
+        RangeSet<PartitionKey> missing = TreeRangeSet.create();
+        missing.add(requested);
+        Map<String, PartitionKeyDesc> descriptions = Maps.newHashMap();
+        table.readLock();
+        try {
+            for (Map.Entry<Long, PartitionItem> entry : 
partitionInfo.getIdToItem(false).entrySet()) {

Review Comment:
   [P3] Look up RANGE overlaps without scanning all ranges per bucket
   
   `planAutomaticPartitions` calls this scan under the table read lock for each 
distinct requested TIMESTAMPTZ range. At the default limit of 20,000 formal 
partitions, a batch of 8,192 missing daily buckets can make about 164 million 
range visits before the FE rejects the request, even with fixed distribution 
buckets. Snapshot ordered formal bounds once per request and visit the 
intervals that overlap each requested bucket.



##########
be/src/exprs/function/function_other_types_to_date.cpp:
##########
@@ -501,7 +501,11 @@ struct DateTrunc {
                        [](unsigned char c) { return std::tolower(c); });
 
         std::shared_ptr<State> state = std::make_shared<State>();
-        state->timezone = context->state()->timezone_obj();
+        // Keep the boundary mode captured when the partition expression was 
opened.
+        // Before the Master upgrades, its RANGE creation still requires local 
buckets.
+        state->timezone = context->use_utc_partition_boundaries()

Review Comment:
   [P2] End the first UTC week at the next weekly boundary
   
   In an empty weekly TIMESTAMPTZ auto-range table with a `+08:00` session, a 
single insert of `0000-01-01 20:00Z` and `0000-01-02 20:00Z` previously 
requested one local week containing both rows. Under UTC truncation, Doris 
treats Jan 1 as Sunday and leaves its day unchanged when subtracting to the 
previous Monday fails at the lower bound. Jan 2 is Monday and produces a second 
floor. The FE adds seven days to each floor and plans `[Jan 1, Jan 8)` and 
`[Jan 2, Jan 9)` against the same empty table. The second ADD rejects the 
overlap. End the initial partial UTC week at the first representable Monday and 
cover both inputs in one request.



##########
be/src/exec/sink/vrow_distribution.h:
##########
@@ -101,6 +102,9 @@ class VRowDistribution {
         _block_convertor = ctx.block_convertor;
         _tablet_finder = ctx.tablet_finder;
         _vpartition = ctx.vpartition;
+        for (const auto* partition : _vpartition->get_partitions()) {

Review Comment:
   [P3] Allocate the initial-ID set only for auto-partition sinks
   
   Every writer and tablet-shuffle instance now copies all planned partition 
IDs into a `std::set`. On a large manually partitioned table, each parallel 
instance retains a separate tree for the lifetime of the load, even though only 
the automatic creation callback reads it. Populate the set only when automatic 
partition creation is enabled.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -202,50 +263,158 @@ public static Map<String, AddPartitionOp> 
getAddPartitionClauseFromPartitionValu
                             + "_" + 
Integer.toHexString(partitionName.hashCode());
                     }
                 }
+                if (hasTimestampTz) {
+                    partitionName = 
existingListPartitions.getOrDefault(typedKey, partitionName);

Review Comment:
   [P2] Check LIST keys before reusing a canonical name
   
   A formal partition named `p20242d062d1720003a003a002e0000002b003a0032` can 
hold the June 18 key. An Asia/Shanghai insert of `2024-06-17 08:00:00+08:00` 
into this `TIMESTAMPTZ(6)` AUTO LIST table generates that same name after UTC 
normalization. The typed lookup has no June 17 entry, but 
`InternalCatalog.addPartition` treats the name match as `IF NOT EXISTS` success 
before checking the key. `getPartitionIds` then returns the June 18 partition, 
and the writer filters the June 17 row on retry. Choose a free name for 
unmatched LIST keys and validate key membership when taking the response 
snapshot.



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