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


##########
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();
+        // Automatic partition boundaries are shared by all writers. A 
Shanghai writer
+        // must use the same UTC day as a UTC writer for an identical 
TIMESTAMPTZ value.
+        state->timezone = context->is_auto_partition_boundary_context()

Review Comment:
   [P1] Preserve legacy RANGE requests during the BE-first upgrade
   
   With a legacy `[2024-01-03 16:00Z, 2024-01-04 16:00Z)` partition, a Shanghai 
writer inserting `2024-01-04 20:00Z` previously requested the adjacent range 
starting at `16:00Z`. This change sends `00:00Z` to the still-old FE, which 
attempts the whole UTC day and rejects the overlap in `RangePartitionInfo`. The 
write aborts even after every BE has been upgraded. Activate UTC requests and 
original-instant routing together once the FE supports the new range behavior, 
and cover this BE-first stage.



##########
be/src/exec/sink/vrow_distribution.cpp:
##########
@@ -402,7 +408,10 @@ Status VRowDistribution::_deal_missing_map(const Block& 
input_block, Block* bloc
     col_null_maps.reserve(part_col_num);
 
     auto format_options = DataTypeSerDe::get_default_format_options();
-    format_options.timezone = &_state->timezone_obj();
+    // Partition identity is table-wide: the same instant must not acquire 
different
+    // LIST names when writers use UTC and Asia/Shanghai, for example.
+    const auto partition_timezone = cctz::utc_time_zone();
+    format_options.timezone = &partition_timezone;

Review Comment:
   [P2] Keep LIST key serialization compatible with the old FE
   
   During the BE-first rollout, two Shanghai sessions that both plan before a 
LIST key exists can write the same instant through different BE versions. The 
old BE sends `08:00:00+08:00`, and the new BE sends `00:00:00+00:00`. The 
baseline FE derives two names from those strings, while the catalog resolves 
both to the same key and rejects the second ADD. Before the upgrade, both 
sessions generated the same name and `IF NOT EXISTS` let both writes proceed. 
Switch LIST serialization to UTC once the receiving FE canonicalizes names.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -202,50 +215,147 @@ public static Map<String, AddPartitionOp> 
getAddPartitionClauseFromPartitionValu
                             + "_" + 
Integer.toHexString(partitionName.hashCode());
                     }
                 }
+                if (partitionColumn.stream().anyMatch(column -> 
column.getType().isTimeStampTz())) {
+                    partitionName = 
existingTimestampTzListPartitionName(olapTable, partitionInfo,
+                            PartitionKey.createListPartitionKey(inValues, 
partitionColumn), 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);
+            } else {
+                descriptions.put(partitionName, partitionKeyDesc);
+            }
+            for (Map.Entry<String, PartitionKeyDesc> entry : 
descriptions.entrySet()) {
+                result.put(entry.getKey(), buildAddPartitionOp(

Review Comment:
   [P2] Size auto buckets only for ranges that will be created
   
   A missing row in a yearly bucket can overlap hundreds of existing daily 
ranges. Each reused range now goes through `buildAddPartitionOp`, which copies 
and sorts the entire partition history and looks up visible versions for 
auto-bucket tables. The catalog then skips every one of those ADDs by name. 
This can repeat hundreds of full-history scans during one insert, with 
additional meta-service lookups in cloud mode. Return reused partitions 
directly and calculate sizing only for the new gaps.



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/PartitionExprUtil.java:
##########
@@ -202,50 +215,147 @@ public static Map<String, AddPartitionOp> 
getAddPartitionClauseFromPartitionValu
                             + "_" + 
Integer.toHexString(partitionName.hashCode());
                     }
                 }
+                if (partitionColumn.stream().anyMatch(column -> 
column.getType().isTimeStampTz())) {
+                    partitionName = 
existingTimestampTzListPartitionName(olapTable, partitionInfo,
+                            PartitionKey.createListPartitionKey(inValues, 
partitionColumn), 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);
+            } else {
+                descriptions.put(partitionName, partitionKeyDesc);
+            }
+            for (Map.Entry<String, PartitionKeyDesc> entry : 
descriptions.entrySet()) {
+                result.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());
+        }
+        AddPartitionOp addPartitionClause = new AddPartitionOp(
+                singleRangePartitionDesc.translateToPartitionDefinition(),
+                distributionDesc.toDistributionDescriptor(), 
partitionProperties, false);
+        return addPartitionClause;
+    }
+
+    private static String existingTimestampTzListPartitionName(OlapTable 
table, PartitionInfo partitionInfo,
+            PartitionKey key, String canonicalName) {
+        table.readLock();
+        try {
+            if (table.checkPartitionNameExist(canonicalName)) {
+                return canonicalName;
+            }
+            // 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.
+            for (Map.Entry<Long, PartitionItem> entry : 
partitionInfo.getIdToItem(false).entrySet()) {
+                if (((ListPartitionItem) 
entry.getValue()).getItems().contains(key)) {
+                    return table.getPartition(entry.getKey()).getName();
                 }
             }
+            return canonicalName;
+        } finally {
+            table.readUnlock();
+        }
+    }
 
-            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());
+    private static Map<String, PartitionKeyDesc> 
timestampTzRangePartitions(OlapTable table,
+            PartitionInfo partitionInfo, String canonicalName, 
PartitionKeyDesc requestedDesc)
+            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()) {
+                Range<PartitionKey> existing = ((RangePartitionItem) 
entry.getValue()).getItems();
+                if (requested.isConnected(existing) && 
!requested.intersection(existing).isEmpty()) {
+                    missing.remove(existing);
+                    // IF NOT EXISTS makes these operations no-ops. Keeping 
their names in the
+                    // result also returns the existing tablets to a writer 
with stale metadata.
+                    
descriptions.put(table.getPartition(entry.getKey()).getName(),
+                            timestampTzRangeDescription(existing));
+                }
             }
-            AddPartitionOp addPartitionClause = new AddPartitionOp(
-                    singleRangePartitionDesc.translateToPartitionDefinition(),
-                    distributionDesc.toDistributionDescriptor(), 
partitionProperties, false);
-            result.put(partitionName, addPartitionClause);
+        } finally {
+            table.readUnlock();
         }
-        return result;
+        // A legacy range [08:00,16:00) leaves two gaps in the UTC day. One 
RPC lower
+        // bound can represent rows in both gaps, so cover every gap, not just 
one side.
+        for (Range<PartitionKey> gap : missing.asRanges()) {
+            String name = gap.equals(requested) ? canonicalName
+                    : "p" + timestampTzBoundaryName(gap.lowerEndpoint())
+                            + "_" + 
timestampTzBoundaryName(gap.upperEndpoint());
+            descriptions.put(name, timestampTzRangeDescription(gap));

Review Comment:
   [P2] Prevent gap names from resolving to temporary partitions
   
   With a formal `[08:00Z, 16:00Z)` range on Jan 4, 2024, a temporary `[00:00Z, 
08:00Z)` partition can legally have the generated name 
`p20240104000000000000_20240104080000000000`. An ordinary insert of `02:00Z` 
requests the left gap. `InternalCatalog.addPartition` skips the formal ADD on 
the name match, and `snapshotPartitionResultsByName` returns the temporary 
tablets. The BE can commit the row there, outside ordinary query results. 
Allocate names that avoid both namespaces and check that reused results 
identify formal partitions with the expected bounds.



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