This is an automated email from the ASF dual-hosted git repository.

hubgeter pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 386be3dbd1a [fix](iceberg) Honor session time zone in expire_snapshots 
(#70612)
386be3dbd1a is described below

commit 386be3dbd1a31fc3c7be5caa38f40b47a307cd10
Author: daidai <[email protected]>
AuthorDate: Thu Nov 26 14:46:14 2026 +0800

    [fix](iceberg) Honor session time zone in expire_snapshots (#70612)
    
    ### Background
    
    `ALTER TABLE ... EXECUTE expire_snapshots` accepts `older_than` as an
    ISO local datetime or epoch milliseconds. It converts that argument into
    an absolute cutoff before handing expiration to Iceberg, which also
    applies snapshot and reference retention rules.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #59979 (introduced the original timestamp parsing)
    PR Type: Bugfix
    
    Problem Summary:
    
    When the FE JVM default time zone differs from the SQL session time
    zone, an ISO `older_than` cutoff is interpreted at the wrong instant and
    can expire additional historical snapshots or retain snapshots that
    should expire. For example, `2026-11-10T10:00:00` in an Asia/Shanghai
    session means `02:00 UTC`, but a UTC JVM currently interprets it as
    `10:00 UTC`. Resolve the session zone through the existing helper and
    pass it explicitly to the local datetime parser; numeric
    epoch-millisecond input and argument validation remain unchanged. Most
    of this diff adds action tests that compare exact surviving snapshot
    IDs.
---
 .../iceberg/action/BaseIcebergAction.java          |  11 +-
 .../action/IcebergExpireSnapshotsAction.java       |  21 +--
 .../action/IcebergExpireSnapshotsTimeZoneTest.java | 195 +++++++++++++++++++++
 3 files changed, 207 insertions(+), 20 deletions(-)

diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/BaseIcebergAction.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/BaseIcebergAction.java
index 7b0d57b3705..9e36a25d98f 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/BaseIcebergAction.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/BaseIcebergAction.java
@@ -100,11 +100,8 @@ public abstract class BaseIcebergAction {
      * Runs the procedure body and wraps its single row into a {@link 
ConnectorProcedureResult}. Enforces the
      * legacy single-row contract: the row width must equal the declared 
schema width.
      *
-     * <p>{@code session} carries the connector execution context (most 
importantly the session time zone for
-     * {@code rollback_to_timestamp}); the seven non-time-zone procedures 
ignore it. The legacy
-     * {@code BaseExecuteAction} read the time zone from the thread-local 
{@code ConnectContext}; the connector
-     * cannot, so it threads {@link ConnectorSession} here instead — the SPI 
({@code ConnectorProcedureOps})
-     * and factory signatures are unchanged.
+     * <p>{@code session} carries the connector execution context, including 
the time zone used by timestamp
+     * arguments.</p>
      */
     public final ConnectorProcedureResult execute(Table table, 
ConnectorSession session) {
         List<String> resultRow = executeAction(table, session);
@@ -143,8 +140,8 @@ public abstract class BaseIcebergAction {
 
     /**
      * Runs the procedure against the loaded iceberg SDK table and returns its 
single result row (or
-     * {@code null} when there is no result). {@code session} provides the 
execution context (e.g. the session
-     * time zone consumed by {@code rollback_to_timestamp}); most procedures 
do not use it.
+     * {@code null} when there is no result). {@code session} provides the 
execution context, including the time
+     * zone used by timestamp arguments.
      */
     protected abstract List<String> executeAction(Table table, 
ConnectorSession session);
 
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsAction.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsAction.java
index b6eafa09356..e134b8d3fd5 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsAction.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsAction.java
@@ -17,6 +17,7 @@
 
 package org.apache.doris.connector.iceberg.action;
 
+import org.apache.doris.connector.iceberg.IcebergTimeUtils;
 import org.apache.doris.connector.spi.ConnectorColumn;
 import org.apache.doris.connector.spi.ConnectorSession;
 import org.apache.doris.connector.spi.ConnectorType;
@@ -53,15 +54,9 @@ import java.util.concurrent.atomic.AtomicLong;
 import java.util.regex.Pattern;
 
 /**
- * Removes old snapshots from an iceberg table to free storage and improve 
metadata performance. Connector
- * port of legacy {@code IcebergExpireSnapshotsAction} — the most involved of 
the snapshot procedures (five
- * optional arguments, a custom validation pass, an FE-local fixed thread pool 
for concurrent deletes, a
- * {@code deleteWith} callback that classifies deleted files into the six 
Spark-compatible counters, and the
- * file kind map it classifies them by). The validation messages and the SDK 
call chain are verbatim; the validation
- * failures throw {@link DorisConnectorException} in place of the legacy 
{@code AnalysisException}/
- * {@code UserException} (message-identical, T08 byte-parity). {@code 
parseTimestamp} keeps the legacy
- * {@code ZoneId.systemDefault()} (this procedure, unlike {@code 
rollback_to_timestamp}, never used the
- * session time zone).
+ * Removes old snapshots from an iceberg table to free storage and improve 
metadata performance.
+ * Local datetime cutoffs use the session time zone; numeric cutoffs are epoch 
milliseconds.
+ * The result contains six file-deletion counters populated by the {@code 
deleteWith} callback.
  */
 public class IcebergExpireSnapshotsAction extends BaseIcebergAction {
     private static final Logger LOG = 
LogManager.getLogger(IcebergExpireSnapshotsAction.class);
@@ -200,7 +195,7 @@ public class IcebergExpireSnapshotsAction extends 
BaseIcebergAction {
             // If retain_last is specified without older_than, use current 
time as the cutoff
             // This is because Iceberg's retainLast only works in conjunction 
with expireOlderThan
             if (olderThan != null) {
-                long timestampMillis = parseTimestamp(olderThan);
+                long timestampMillis = parseTimestamp(olderThan, 
IcebergTimeUtils.resolveSessionZone(session));
                 expireSnapshots.expireOlderThan(timestampMillis);
             } else if (retainLast != null && snapshotIdsStr == null) {
                 // When only retain_last is specified, expire all snapshots 
older than now
@@ -282,15 +277,15 @@ public class IcebergExpireSnapshotsAction extends 
BaseIcebergAction {
     }
 
     /**
-     * Parse timestamp string to milliseconds since epoch.
+     * Parse a local datetime in the supplied time zone or a numeric 
epoch-millisecond timestamp.
      * Supports ISO datetime format (yyyy-MM-ddTHH:mm:ss) or milliseconds.
      */
-    private long parseTimestamp(String timestamp) {
+    private long parseTimestamp(String timestamp, ZoneId zone) {
         try {
             // Try ISO datetime format
             LocalDateTime dateTime = LocalDateTime.parse(timestamp,
                     DateTimeFormatter.ISO_LOCAL_DATE_TIME);
-            return dateTime.atZone(ZoneId.systemDefault())
+            return dateTime.atZone(zone)
                 .toInstant().toEpochMilli();
         } catch (DateTimeParseException e) {
             // Try as milliseconds
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsTimeZoneTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsTimeZoneTest.java
new file mode 100644
index 00000000000..001be32e099
--- /dev/null
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/action/IcebergExpireSnapshotsTimeZoneTest.java
@@ -0,0 +1,195 @@
+// 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.connector.iceberg.action;
+
+import org.apache.doris.connector.spi.ConnectorSession;
+import org.apache.doris.connector.spi.DorisConnectorException;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.inmemory.InMemoryCatalog;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.parallel.ResourceLock;
+import org.junit.jupiter.api.parallel.Resources;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.stream.Stream;
+
+/** Tests the snapshot sets retained by local datetime and epoch cutoff 
arguments. */
+@ResourceLock(Resources.TIME_ZONE)
+public class IcebergExpireSnapshotsTimeZoneTest {
+    private TimeZone originalTimeZone;
+
+    @BeforeEach
+    public void rememberDefaultTimeZone() {
+        originalTimeZone = TimeZone.getDefault();
+    }
+
+    @AfterEach
+    public void restoreDefaultTimeZone() {
+        TimeZone.setDefault(originalTimeZone);
+    }
+
+    @ParameterizedTest(name = "JVM {0}, session {1}, cutoff equals second 
snapshot: {3}")
+    @MethodSource("timeZonesAndBoundaries")
+    public void isoAndEpochCutoffsRetainTheSameSnapshotIds(String jvmZone, 
String sessionZone,
+            String expectedZone, boolean cutoffAtSecondSnapshot) throws 
InterruptedException {
+        TimeZone.setDefault(TimeZone.getTimeZone(jvmZone));
+        Table table = threeSnapshots();
+        List<Snapshot> history = snapshotHistory(table);
+        long cutoff = cutoffAtSecondSnapshot
+                ? history.get(1).timestampMillis() : 
history.get(0).timestampMillis() + 1;
+        String localCutoff = localCutoff(cutoff, expectedZone);
+        Set<Long> expected = ImmutableSet.of(history.get(1).snapshotId(), 
history.get(2).snapshotId());
+
+        expire(table, localCutoff, ActionTestTables.session(sessionZone));
+        Assertions.assertEquals(expected, snapshotIds(table),
+                "only snapshots strictly before the session-local cutoff may 
expire");
+
+        // Applying the equivalent instant must preserve exactly the same 
surviving snapshot IDs.
+        expire(table, String.valueOf(cutoff), 
ActionTestTables.session(sessionZone));
+        Assertions.assertEquals(expected, snapshotIds(table));
+    }
+
+    private static Stream<Arguments> timeZonesAndBoundaries() {
+        return Stream.of(
+                new String[] {"UTC", "Asia/Shanghai", "Asia/Shanghai"},
+                new String[] {"UTC", "CST", "Asia/Shanghai"},
+                new String[] {"UTC", "+08:00", "+08:00"},
+                new String[] {"Asia/Shanghai", "UTC", "UTC"},
+                new String[] {"UTC", "-08:00", "-08:00"},
+                new String[] {"UTC", "UTC", "UTC"},
+                new String[] {"Asia/Shanghai", "Asia/Shanghai", 
"Asia/Shanghai"})
+                .flatMap(zones -> Stream.of(
+                        Arguments.of(zones[0], zones[1], zones[2], false),
+                        Arguments.of(zones[0], zones[1], zones[2], true)));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"Asia/Shanghai", "CST", "+08:00", "-08:00", "UTC", 
"America/Los_Angeles"})
+    public void epochCutoffIsIndependentOfTheSessionTimeZone(String 
sessionZone) throws InterruptedException {
+        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
+        Table table = threeSnapshots();
+        List<Snapshot> history = snapshotHistory(table);
+        long cutoff = history.get(0).timestampMillis() + 1;
+
+        expire(table, String.valueOf(cutoff), 
ActionTestTables.session(sessionZone));
+
+        Assertions.assertEquals(ImmutableSet.of(history.get(1).snapshotId(), 
history.get(2).snapshotId()),
+                snapshotIds(table));
+    }
+
+    @ParameterizedTest
+    @NullAndEmptySource
+    @ValueSource(strings = {"   ", "Unknown/Zone"})
+    public void absentOrInvalidSessionTimeZoneUsesUtc(String sessionZone) 
throws InterruptedException {
+        assertUtcFallback(ActionTestTables.session(sessionZone));
+    }
+
+    @Test
+    public void absentSessionUsesUtc() throws InterruptedException {
+        assertUtcFallback(null);
+    }
+
+    private static void assertUtcFallback(ConnectorSession session) throws 
InterruptedException {
+        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
+        Table table = threeSnapshots();
+        List<Snapshot> history = snapshotHistory(table);
+        long cutoff = history.get(0).timestampMillis() + 1;
+
+        expire(table, localCutoff(cutoff, "UTC"), session);
+
+        Assertions.assertEquals(ImmutableSet.of(history.get(1).snapshotId(), 
history.get(2).snapshotId()),
+                snapshotIds(table));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"not-a-time", "2026-11-10 10:00:00", 
"2026-11-10T10:00:00Z", "9223372036854775808"})
+    public void rejectsInvalidOrUnsupportedCutoffFormats(String cutoff) {
+        IcebergExpireSnapshotsAction action = action(cutoff);
+        DorisConnectorException e = 
Assertions.assertThrows(DorisConnectorException.class, action::validate);
+        Assertions.assertEquals("Invalid older_than format. Expected ISO 
datetime "
+                + "(yyyy-MM-ddTHH:mm:ss) or timestamp in milliseconds: " + 
cutoff, e.getMessage());
+    }
+
+    private static IcebergExpireSnapshotsAction action(String cutoff) {
+        return new IcebergExpireSnapshotsAction(ImmutableMap.of("older_than", 
cutoff, "retain_last", "1"),
+                Collections.emptyList(), null);
+    }
+
+    private static void expire(Table table, String cutoff, ConnectorSession 
session) {
+        IcebergExpireSnapshotsAction action = action(cutoff);
+        action.validate();
+        action.execute(table, session);
+        table.refresh();
+    }
+
+    private static String localCutoff(long cutoff, String zone) {
+        return 
Instant.ofEpochMilli(cutoff).atZone(ZoneId.of(zone)).toLocalDateTime()
+                .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
+    }
+
+    private static Table threeSnapshots() throws InterruptedException {
+        InMemoryCatalog catalog = ActionTestTables.freshCatalog();
+        ActionTestTables.createTable(catalog, "cutoff");
+        ActionTestTables.appendSnapshot(catalog, "cutoff", "first.parquet", 
1L);
+        Thread.sleep(5);
+        ActionTestTables.appendSnapshot(catalog, "cutoff", "second.parquet", 
1L);
+        Thread.sleep(5);
+        ActionTestTables.appendSnapshot(catalog, "cutoff", "third.parquet", 
1L);
+        Table table = catalog.loadTable(ActionTestTables.id("cutoff"));
+        List<Snapshot> history = snapshotHistory(table);
+        Assertions.assertEquals(3, history.size());
+        Assertions.assertTrue(history.get(0).timestampMillis() + 1 < 
history.get(1).timestampMillis(),
+                "the fixture needs a cutoff strictly between the first two 
snapshots");
+        Assertions.assertTrue(history.get(1).timestampMillis() < 
history.get(2).timestampMillis());
+        return table;
+    }
+
+    private static List<Snapshot> snapshotHistory(Table table) {
+        List<Snapshot> history = new ArrayList<>();
+        table.snapshots().forEach(history::add);
+        history.sort(Comparator.comparingLong(Snapshot::timestampMillis));
+        return history;
+    }
+
+    private static Set<Long> snapshotIds(Table table) {
+        Set<Long> ids = new HashSet<>();
+        table.snapshots().forEach(snapshot -> ids.add(snapshot.snapshotId()));
+        return ids;
+    }
+}


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

Reply via email to