Copilot commented on code in PR #62490:
URL: https://github.com/apache/doris/pull/62490#discussion_r3083625471


##########
fe/fe-core/src/main/java/org/apache/doris/job/offset/jdbc/JdbcOffset.java:
##########
@@ -48,7 +48,10 @@ public class JdbcOffset implements Offset {
 
     @Override
     public String toSerializedJson() {
-        return null;
+        if (splits == null || splits.isEmpty()) {
+            return null;
+        }
+        return new Gson().toJson(splits);
     }
 

Review Comment:
   `JdbcOffset.toSerializedJson()` now serializes the split objects directly 
(`new Gson().toJson(splits)`), but 
`JdbcSourceOffsetProvider.deserializeOffset()` expects a JSON array of flat 
`Map<String,String>` entries (with `split_id` mixed into the same map). With 
the new format, deserialization will fail (nested objects like 
`startingOffset`/`highWatermark` won’t map to `String`) and can break offset 
persistence/reset paths. Align `toSerializedJson()` with the format that 
`deserializeOffset()` reads (or update `deserializeOffset()` accordingly).
   ```suggestion
           return new Gson().toJson(convertSplitsToSerializedMaps());
       }
   
       private List<Map<String, String>> convertSplitsToSerializedMaps() {
           return splits.stream()
                   .map(this::convertSplitToSerializedMap)
                   .toList();
       }
   
       private Map<String, String> 
convertSplitToSerializedMap(AbstractSourceSplit split) {
           Map<String, Object> rawMap = new ObjectMapper().convertValue(split,
                   new TypeReference<Map<String, Object>>() {
                   });
           Map<String, String> serializedMap = new HashMap<>();
           for (Map.Entry<String, Object> entry : rawMap.entrySet()) {
               if (entry.getValue() == null) {
                   continue;
               }
               if ("splitId".equals(entry.getKey())) {
                   serializedMap.put(JdbcSourceOffsetProvider.SPLIT_ID, 
stringifyOffsetValue(entry.getValue()));
               } else {
                   serializedMap.put(entry.getKey(), 
stringifyOffsetValue(entry.getValue()));
               }
           }
           return serializedMap;
       }
   
       private String stringifyOffsetValue(Object value) {
           if (value == null) {
               return null;
           }
           if (value instanceof String) {
               return (String) value;
           }
           return new Gson().toJson(value);
       }
   ```



##########
fs_brokers/cdc_client/src/main/java/org/apache/doris/cdcclient/source/reader/postgres/PostgresSourceReader.java:
##########
@@ -206,7 +206,16 @@ private PostgresSourceConfig generatePostgresConfig(
         } else if 
(DataSourceConfigKeys.OFFSET_LATEST.equalsIgnoreCase(startupMode)) {
             configFactory.startupOptions(StartupOptions.latest());
         } else if (ConfigUtil.isJson(startupMode)) {
-            throw new RuntimeException("Unsupported json offset " + 
startupMode);
+            Map<String, String> offsetMap = 
ConfigUtil.toStringMap(startupMode);
+            if (offsetMap == null || 
!offsetMap.containsKey(SourceInfo.LSN_KEY)) {
+                throw new RuntimeException("JSON offset for PostgreSQL must 
contain 'lsn' key, got: " + startupMode);
+            }
+            // Ensure ts_usec is present (required by PostgresOffset)
+            if (!offsetMap.containsKey(SourceInfo.TIMESTAMP_USEC_KEY)) {
+                offsetMap.put(SourceInfo.TIMESTAMP_USEC_KEY,
+                        
String.valueOf(Conversions.toEpochMicros(Instant.MIN)));

Review Comment:
   Using `Conversions.toEpochMicros(Instant.MIN)` is very likely to overflow 
`long` (Instant.MIN is ~-1e9 years), producing a wrapped/invalid `ts_usec` 
value. Since this field is only required to be present, use a safe value like 
`0` or `Conversions.toEpochMicros(Instant.EPOCH)` instead.
   ```suggestion
                           
String.valueOf(Conversions.toEpochMicros(Instant.EPOCH)));
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/job/offset/jdbc/JdbcSourceOffsetProvider.java:
##########
@@ -360,7 +361,28 @@ public Offset deserializeOffset(String offset) {
 
     @Override
     public Offset deserializeOffsetProperty(String offset) {
-        // no need cause cdc_stream has offset property
+        if (offset == null || offset.trim().isEmpty()) {
+            return null;
+        }
+        // Named modes: stored in sourceProperties.offset, CDC client reads it 
directly.
+        // Return a placeholder JdbcOffset so validateOffset() passes.
+        if (DataSourceConfigKeys.OFFSET_INITIAL.equalsIgnoreCase(offset)
+                || 
DataSourceConfigKeys.OFFSET_SNAPSHOT.equalsIgnoreCase(offset)
+                || 
DataSourceConfigKeys.OFFSET_EARLIEST.equalsIgnoreCase(offset)
+                || 
DataSourceConfigKeys.OFFSET_LATEST.equalsIgnoreCase(offset)) {
+            return new JdbcOffset(Collections.singletonList(new 
BinlogSplit()));

Review Comment:
   `deserializeOffsetProperty()` returns a placeholder `JdbcOffset` for named 
modes by creating `new BinlogSplit()` with a null `startingOffset`. If this 
offset is then applied via `JdbcSourceOffsetProvider.updateOffset()`, it will 
hit `new HashMap<>(binlogSplit.getStartingOffset())` and throw an NPE. Prefer 
returning `null` for named modes (since ALTER for CDC rejects them anyway), or 
populate an empty/non-null startingOffset map and make `updateOffset()` handle 
null safely.
   ```suggestion
           // Named modes are stored in sourceProperties.offset and interpreted 
directly
           // by the CDC client. Do not create a placeholder JdbcOffset here 
because
           // an empty BinlogSplit would have a null startingOffset and may 
trigger NPEs
           // if later treated as a concrete offset.
           if (DataSourceConfigKeys.OFFSET_INITIAL.equalsIgnoreCase(offset)
                   || 
DataSourceConfigKeys.OFFSET_SNAPSHOT.equalsIgnoreCase(offset)
                   || 
DataSourceConfigKeys.OFFSET_EARLIEST.equalsIgnoreCase(offset)
                   || 
DataSourceConfigKeys.OFFSET_LATEST.equalsIgnoreCase(offset)) {
               return null;
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/insert/streaming/DataSourceConfigValidator.java:
##########
@@ -103,18 +109,51 @@ public static void validateTarget(Map<String, String> 
input) throws IllegalArgum
         }
     }
 
-    private static boolean isValidValue(String key, String value) {
+    private static boolean isValidValue(String key, String value, String 
dataSourceType) {
         if (value == null || value.isEmpty()) {
             return false;
         }
 
-        if (key.equals(DataSourceConfigKeys.OFFSET)
-                && !(value.equals(DataSourceConfigKeys.OFFSET_INITIAL)
-                || value.equals(DataSourceConfigKeys.OFFSET_LATEST)
-                || value.equals(DataSourceConfigKeys.OFFSET_SNAPSHOT))) {
-            return false;
+        if (key.equals(DataSourceConfigKeys.OFFSET)) {
+            return isValidOffset(value, dataSourceType);
         }
         return true;
     }
 
+    /**
+     * Check if the offset value is valid for the given data source type.
+     * Supported: initial, snapshot, latest, JSON binlog/lsn position.
+     * earliest is only supported for MySQL.
+     */
+    public static boolean isValidOffset(String offset, String dataSourceType) {
+        if (offset == null || offset.isEmpty()) {
+            return false;
+        }
+        if (DataSourceConfigKeys.OFFSET_INITIAL.equalsIgnoreCase(offset)
+                || DataSourceConfigKeys.OFFSET_LATEST.equalsIgnoreCase(offset)
+                || 
DataSourceConfigKeys.OFFSET_SNAPSHOT.equalsIgnoreCase(offset)) {
+            return true;
+        }
+        // earliest only for MySQL
+        if (DataSourceConfigKeys.OFFSET_EARLIEST.equalsIgnoreCase(offset)) {
+            return 
DataSourceType.MYSQL.name().equalsIgnoreCase(dataSourceType);
+        }
+        if (isJsonOffset(offset)) {
+            return true;
+        }
+        return false;
+    }
+
+    public static boolean isJsonOffset(String offset) {
+        if (offset == null || offset.trim().isEmpty()) {
+            return false;
+        }
+        try {
+            JsonNode node = OBJECT_MAPPER.readTree(offset);
+            return node.isObject();
+        } catch (Exception e) {
+            return false;
+        }
+    }
+

Review Comment:
   `isValidOffset()` currently treats any JSON object as valid for any data 
source type. This allows values like `{}` or `{"foo":"bar"}` to pass FE 
validation but fail later in BE readers (e.g., MySQL requires `file`+`pos`, 
PostgreSQL requires `lsn`). Consider parsing the JSON here and validating 
required keys per `dataSourceType` to fail fast with a clear error.
   ```suggestion
           JsonNode jsonOffset = parseJsonOffset(offset);
           return isValidJsonOffset(jsonOffset, dataSourceType);
       }
   
       public static boolean isJsonOffset(String offset) {
           return parseJsonOffset(offset) != null;
       }
   
       private static JsonNode parseJsonOffset(String offset) {
           if (offset == null || offset.trim().isEmpty()) {
               return null;
           }
           try {
               JsonNode node = OBJECT_MAPPER.readTree(offset);
               return node.isObject() ? node : null;
           } catch (Exception e) {
               return null;
           }
       }
   
       private static boolean isValidJsonOffset(JsonNode offsetNode, String 
dataSourceType) {
           if (offsetNode == null) {
               return false;
           }
           if (DataSourceType.MYSQL.name().equalsIgnoreCase(dataSourceType)) {
               return hasNonEmptyField(offsetNode, "file") && 
hasNonEmptyField(offsetNode, "pos");
           }
           if 
(DataSourceType.POSTGRESQL.name().equalsIgnoreCase(dataSourceType)) {
               return hasNonEmptyField(offsetNode, "lsn");
           }
           return true;
       }
   
       private static boolean hasNonEmptyField(JsonNode node, String fieldName) 
{
           JsonNode field = node.get(fieldName);
           if (field == null || field.isNull()) {
               return false;
           }
           if (field.isTextual()) {
               return !field.asText().trim().isEmpty();
           }
           return !field.asText().trim().isEmpty();
       }
   ```



##########
regression-test/suites/job_p0/streaming_job/cdc/test_streaming_mysql_job_special_offset_restart_fe.groovy:
##########
@@ -0,0 +1,140 @@
+// 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.
+
+import org.apache.doris.regression.suite.ClusterOptions
+import org.awaitility.Awaitility
+
+import static java.util.concurrent.TimeUnit.SECONDS
+
+suite("test_streaming_mysql_job_special_offset_restart_fe", 
"docker,mysql,external_docker,external_docker_mysql,nondatalake") {
+    def jobName = "test_streaming_mysql_job_special_offset_restart_fe"
+    def options = new ClusterOptions()
+    options.setFeNum(1)
+    // run in cloud and not cloud
+    options.cloudMode = null
+
+    docker(options) {
+        def currentDb = (sql "select database()")[0][0]
+        def table1 = "special_offset_restart_tbl"
+        def mysqlDb = "test_cdc_db"
+
+        sql """DROP JOB IF EXISTS where jobname = '${jobName}'"""
+        sql """drop table if exists ${currentDb}.${table1} force"""
+
+        String enabled = context.config.otherConfigs.get("enableJdbcTest")
+        if (enabled != null && enabled.equalsIgnoreCase("true")) {
+            String mysql_port = 
context.config.otherConfigs.get("mysql_57_port");
+            String externalEnvIp = 
context.config.otherConfigs.get("externalEnvIp")
+            String s3_endpoint = getS3Endpoint()
+            String bucket = getS3BucketName()
+            String driver_url = 
"https://${bucket}.${s3_endpoint}/regression/jdbc_driver/mysql-connector-j-8.4.0.jar";
+
+            // prepare MySQL source table and get binlog position
+            def binlogFile = ""
+            def binlogPos = ""
+            connect("root", "123456", 
"jdbc:mysql://${externalEnvIp}:${mysql_port}") {
+                sql """CREATE DATABASE IF NOT EXISTS ${mysqlDb}"""
+                sql """DROP TABLE IF EXISTS ${mysqlDb}.${table1}"""
+                sql """CREATE TABLE ${mysqlDb}.${table1} (
+                      `id` int NOT NULL,
+                      `name` varchar(100) DEFAULT NULL,
+                      PRIMARY KEY (`id`)
+                    ) ENGINE=InnoDB"""
+                // get current binlog position
+                def masterStatus = sql """SHOW MASTER STATUS"""
+                binlogFile = masterStatus[0][0]
+                binlogPos = masterStatus[0][1].toString()
+                log.info("Binlog position: file=${binlogFile}, 
pos=${binlogPos}")
+                // insert data after this position
+                sql """INSERT INTO ${mysqlDb}.${table1} VALUES (1, 'alice'), 
(2, 'bob')"""
+            }
+
+            // create job with JSON binlog offset
+            def offsetJson = 
"""{"file":"${binlogFile}","pos":"${binlogPos}"}"""
+            log.info("Creating job with offset: ${offsetJson}")
+            sql """CREATE JOB ${jobName}
+                    ON STREAMING
+                    FROM MYSQL (
+                        "jdbc_url" = 
"jdbc:mysql://${externalEnvIp}:${mysql_port}",
+                        "driver_url" = "${driver_url}",
+                        "driver_class" = "com.mysql.cj.jdbc.Driver",
+                        "user" = "root",
+                        "password" = "123456",
+                        "database" = "${mysqlDb}",
+                        "include_tables" = "${table1}",
+                        "offset" = '${offsetJson}'
+                    )
+                    TO DATABASE ${currentDb} (
+                      "table.create.properties.replication_num" = "1"
+                    )
+                """
+
+            // wait for data synced
+            try {
+                Awaitility.await().atMost(300, SECONDS)
+                        .pollInterval(1, SECONDS).until(
+                        {
+                            def jobSuccendCount = sql """ select 
SucceedTaskCount from jobs("type"="insert") where Name = '${jobName}' and 
ExecuteType='STREAMING' """
+                            log.info("jobSuccendCount: " + jobSuccendCount)
+                            jobSuccendCount.size() == 1 && '2' <= 
jobSuccendCount.get(0).get(0)

Review Comment:
   The Awaitility condition compares `SucceedTaskCount` as strings (`'2' <= 
jobSuccendCount.get(0).get(0)`), which is lexicographical and can behave 
incorrectly once counts reach multiple digits (e.g., `'10' < '2'`). Cast to an 
integer before comparing to make the test logic correct and less flaky.
   ```suggestion
                               jobSuccendCount.size() == 1 && 
jobSuccendCount.get(0).get(0).toString().toInteger() >= 2
   ```



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