JackieTien97 commented on code in PR #18304:
URL: https://github.com/apache/iotdb/pull/18304#discussion_r3654768802
##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/FileLoaderUtils.java:
##########
@@ -163,6 +165,21 @@ public static TimeseriesMetadata loadTimeSeriesMetadata(
}
return timeSeriesMetadata;
+ } catch (Exception e) {
Review Comment:
[P2] Please preserve non-TsFile failures before wrapping. This try also
covers `context.getPathModifications(...)`; its loader can throw
`MemoryNotEnoughException` while reserving matched-mod memory. For a closed,
healthy file, this catch converts `QUERY_EXECUTION_MEMORY_NOT_ENOUGH` into a
corruption error and loses the original status. Narrow the catch to
reader/deserialization operations or rethrow typed `IoTDBRuntimeException`s
first. The aligned path below has the same issue.
##########
integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBQueryWithCorruptedTsFileIT.java:
##########
@@ -0,0 +1,325 @@
+/*
+ * 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.iotdb.relational.it.query.recent;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.TableLocalStandaloneIT;
+
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.ColumnCategory;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.exception.write.WriteProcessException;
+import org.apache.tsfile.file.metadata.TableSchema;
+import org.apache.tsfile.read.TsFileSequenceReader;
+import org.apache.tsfile.write.TsFileWriter;
+import org.apache.tsfile.write.record.Tablet;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.iotdb.db.it.utils.TestUtils.tableAssertTestFail;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({TableLocalStandaloneIT.class})
+public class IoTDBQueryWithCorruptedTsFileIT {
+ private static final String DATABASE_NAME = "test_corrupted_read_tsfile";
+
+ private static File tmpDir;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ EnvFactory.getEnv().initClusterEnvironment();
+ try (Connection connection = EnvFactory.getEnv().getTableConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE " + DATABASE_NAME);
+ }
+ }
+
+ @Before
+ public void setUpBeforeTest() throws IOException {
+ tmpDir = new File(Files.createTempDirectory("corrupt-tsfile").toUri());
+ }
+
+ @After
+ public void tearDownAfterTest() {
+ deleteTmpDir();
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void testReadTsFileWithCorruptedMetadataIndexNode() throws Exception {
+ File tsFile = new File(tmpDir, "corrupt-meta.tsfile");
+ try (TsFileWriter writer = new TsFileWriter(tsFile)) {
+ generateTable(
+ writer, "table1", Arrays.asList("tag1"), Arrays.asList("s1"),
TSDataType.INT64, 1, 10);
+ }
+
+ // TsFile layout: [Header] [Data] [MetadataIndex Tree] [TsFileMetadata]
[Magic][Size]
+ // ↑ metaOffset ↑
fileMetadataPos
+ //
+ // MetadataIndexNode serialization:
+ // [entryCount (varInt)] [entry1]...[entryN] [endOffset (long, 8B)]
[nodeType (1B)]
+ // nodeType valid values: 0=INTERNAL_DEVICE, 1=LEAF_DEVICE,
2=INTERNAL_MEASUREMENT,
+ // 3=LEAF_MEASUREMENT
+ // nodeType is the LAST byte before TsFileMetadata, i.e. at
fileMetadataPos - 1
+ long metaOffset;
+ long fileMetadataPos;
+ try (TsFileSequenceReader reader = new
TsFileSequenceReader(tsFile.getAbsolutePath())) {
+ metaOffset = reader.readFileMetadata().getMetaOffset();
+ fileMetadataPos = reader.getFileMetadataPos();
+ }
+
+ // Corrupt the nodeType byte to 0xFF (all valid types are 0-3)
+ byte[] fileBytes = Files.readAllBytes(tsFile.toPath());
+ fileBytes[(int) fileMetadataPos - 1] = (byte) 0xFF;
Review Comment:
[P2] `fileMetadataPos - 1` does not locate a device-index node in this
fixture. With two devices, the device root is stored in `TsFileMetadata`; this
byte belongs to the last measurement-index node. The passing IT consequently
reports `READ_TIMESERIES_METADATA`, matching the broad assertion below, and
never exercises `READ_METADATA_INDEX_NODE`/`DeviceCollector`. Force an on-disk
device-index node or locate its offset explicitly, then assert the exact
stage/message.
##########
integration-test/src/test/java/org/apache/iotdb/relational/it/query/recent/IoTDBQueryWithCorruptedTsFileIT.java:
##########
@@ -0,0 +1,325 @@
+/*
+ * 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.iotdb.relational.it.query.recent;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.TableLocalStandaloneIT;
+
+import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.ColumnCategory;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.exception.write.WriteProcessException;
+import org.apache.tsfile.file.metadata.TableSchema;
+import org.apache.tsfile.read.TsFileSequenceReader;
+import org.apache.tsfile.write.TsFileWriter;
+import org.apache.tsfile.write.record.Tablet;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.apache.iotdb.db.it.utils.TestUtils.tableAssertTestFail;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({TableLocalStandaloneIT.class})
+public class IoTDBQueryWithCorruptedTsFileIT {
+ private static final String DATABASE_NAME = "test_corrupted_read_tsfile";
+
+ private static File tmpDir;
+
+ @BeforeClass
+ public static void setUp() throws Exception {
+ EnvFactory.getEnv().initClusterEnvironment();
+ try (Connection connection = EnvFactory.getEnv().getTableConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("CREATE DATABASE " + DATABASE_NAME);
+ }
+ }
+
+ @Before
+ public void setUpBeforeTest() throws IOException {
+ tmpDir = new File(Files.createTempDirectory("corrupt-tsfile").toUri());
+ }
+
+ @After
+ public void tearDownAfterTest() {
+ deleteTmpDir();
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void testReadTsFileWithCorruptedMetadataIndexNode() throws Exception {
+ File tsFile = new File(tmpDir, "corrupt-meta.tsfile");
+ try (TsFileWriter writer = new TsFileWriter(tsFile)) {
+ generateTable(
+ writer, "table1", Arrays.asList("tag1"), Arrays.asList("s1"),
TSDataType.INT64, 1, 10);
+ }
+
+ // TsFile layout: [Header] [Data] [MetadataIndex Tree] [TsFileMetadata]
[Magic][Size]
+ // ↑ metaOffset ↑
fileMetadataPos
+ //
+ // MetadataIndexNode serialization:
+ // [entryCount (varInt)] [entry1]...[entryN] [endOffset (long, 8B)]
[nodeType (1B)]
+ // nodeType valid values: 0=INTERNAL_DEVICE, 1=LEAF_DEVICE,
2=INTERNAL_MEASUREMENT,
+ // 3=LEAF_MEASUREMENT
+ // nodeType is the LAST byte before TsFileMetadata, i.e. at
fileMetadataPos - 1
+ long metaOffset;
+ long fileMetadataPos;
+ try (TsFileSequenceReader reader = new
TsFileSequenceReader(tsFile.getAbsolutePath())) {
+ metaOffset = reader.readFileMetadata().getMetaOffset();
+ fileMetadataPos = reader.getFileMetadataPos();
+ }
+
+ // Corrupt the nodeType byte to 0xFF (all valid types are 0-3)
+ byte[] fileBytes = Files.readAllBytes(tsFile.toPath());
+ fileBytes[(int) fileMetadataPos - 1] = (byte) 0xFF;
+ Files.write(tsFile.toPath(), fileBytes);
+
+ tableAssertTestFail(
+ "SELECT * FROM read_tsfile(PATHS => '" + toSqlPath(tsFile) + "')",
+ "timeseries metadata",
+ DATABASE_NAME);
+ }
+
+ @Test
+ public void testReadTsFileWithCorruptedPageData() throws Exception {
+ File tsFile = new File(tmpDir, "corrupt-page.tsfile");
+ try (TsFileWriter writer = new TsFileWriter(tsFile)) {
+ generateTable(
+ writer, "table1", Arrays.asList("tag1"), Arrays.asList("s1"),
TSDataType.INT64, 1, 100);
+ }
+
+ corruptDataSection(tsFile);
+
+ tableAssertTestFail(
+ "SELECT * FROM read_tsfile(PATHS => '" + toSqlPath(tsFile) + "')",
"TsFile", DATABASE_NAME);
+ }
+
+ @Test
+ public void testNormalQueryWithCorruptedPageData() throws Exception {
+ String tableName = "corrupt_table";
+ // 1. Create table and insert data via session — generates TsFiles in the
data directory
+ try (Connection connection = EnvFactory.getEnv().getTableConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE " + DATABASE_NAME);
+ statement.execute(
+ "CREATE TABLE " + tableName + "(device_id STRING TAG, s1 INT64
FIELD, s2 INT64 FIELD)");
+ for (int i = 1; i <= 200; i++) {
+ statement.execute(
+ "INSERT INTO "
+ + tableName
+ + "(time, device_id, s1, s2) VALUES("
+ + i
+ + ", 'd"
+ + (i % 10)
+ + "', "
+ + i
+ + ", "
+ + (i * 10)
+ + ")");
+ }
+ statement.execute("FLUSH");
+ }
+
+ // 2. Find the generated TsFile in the data directory
+ File sequenceDir =
+ new File(
+ EnvFactory.getEnv().getDataNodeWrapper(0).getDataNodeDir()
+ + File.separator
+ + "data"
+ + File.separator
+ + "sequence");
+ File tsFile = findTsFileRecursively(sequenceDir);
+ if (tsFile == null) {
+ fail("Could not find TsFile in data directory: " +
sequenceDir.getAbsolutePath());
+ }
+
+ // 3. Corrupt the data section of the TsFile
+ corruptDataSection(tsFile);
+
+ // 4. Query — should fail with a corruption message that does NOT include
the file path
+ try (Connection connection = EnvFactory.getEnv().getTableConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE " + DATABASE_NAME);
+ try {
+ statement.execute("SELECT * FROM " + tableName + " ORDER BY time");
+ fail("Expected query on corrupted TsFile to fail");
+ } catch (SQLException e) {
+ assertTrue(
+ "Error message should mention corruption without file path: " +
e.getMessage(),
+ e.getMessage().contains("may be corrupted")
+ || e.getMessage().contains("check the logs"));
+ }
+ }
+ }
+
+ /**
+ * Corrupts a block of bytes in the data section of a TsFile (between the
header and the
+ * MetadataIndex tree). Uses {@link TsFileSequenceReader} to read {@code
metaOffset} from
+ * TsFileMetadata, so corruption reliably hits compressed page data rather
than metadata.
+ *
+ * <p>TsFile layout: [Header] [Data chunks] [MetadataIndex Tree]
[TsFileMetadata] [Magic][Size] ↑
+ * metaOffset
+ */
+ private static void corruptDataSection(File tsFile) throws IOException {
+ long metaOffset;
+ try (TsFileSequenceReader reader = new
TsFileSequenceReader(tsFile.getAbsolutePath())) {
+ metaOffset = reader.readFileMetadata().getMetaOffset();
+ }
+
+ byte[] fileBytes = Files.readAllBytes(tsFile.toPath());
+ int magicLen = TSFileConfig.MAGIC_STRING.getBytes().length;
+ int dataStart = magicLen + Byte.BYTES;
+ int dataEnd = (int) metaOffset;
+ // Corrupt bytes in the middle of the data section — XOR 512 bytes to
ensure decompression fails
+ int middle = dataStart + (dataEnd - dataStart) / 2;
Review Comment:
[P2] The midpoint is not a page-data boundary. In the current run both this
and the normal-query case corrupt a chunk header and report `READ_CHUNK_DATA`,
so `DECODE_PAGE_DATA` is untested and layout/compressor changes can alter the
failure stage. Please locate a concrete page payload, fully consume the
`ResultSet`, and assert the exact stage-specific message/log.
##########
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/FileLoaderUtils.java:
##########
@@ -469,25 +501,66 @@ public static List<IChunkMetadata>
loadChunkMetadataList(ITimeSeriesMetadata tim
* IOException will be thrown
*/
public static List<IPageReader> loadPageReaderList(
- IChunkMetadata chunkMetaData, Filter globalTimeFilter, List<TSDataType>
targetDataTypeList)
+ IChunkMetadata chunkMetaData,
+ Filter globalTimeFilter,
+ List<TSDataType> targetDataTypeList,
+ FragmentInstanceContext context)
throws IOException {
checkArgument(
chunkMetaData != null,
DataNodeQueryMessages.EXCEPTION_CAN_QUOTE_T_INIT_NULL_CHUNKMETA_15C12BEE);
IChunkLoader chunkLoader = chunkMetaData.getChunkLoader();
- IChunkReader chunkReader;
+ File tsFile = null;
+ if (chunkLoader instanceof DiskChunkLoader) {
+ tsFile = ((DiskChunkLoader) chunkLoader).getTsFile();
+ } else if (chunkLoader instanceof DiskAlignedChunkLoader) {
+ tsFile = ((DiskAlignedChunkLoader) chunkLoader).getTsFile();
+ }
+ final IChunkReader chunkReader;
try {
chunkReader = chunkLoader.getChunkReader(chunkMetaData,
globalTimeFilter);
} catch (ChunkTypeInconsistentException e) {
// if the chunk in tsfile is a value chunk of aligned series but
registered series is
// non-aligned, we should skip all data of this chunk.
return Collections.emptyList();
+ } catch (Exception e) {
+ if (tsFile == null) {
+ throw e;
+ }
+ throw new CorruptedTsFileException(
+ tsFile,
+ CorruptedTsFileException.Stage.READ_CHUNK_DATA,
+ context.isExternalTsFileScan()
+ ? String.format(
+ DataNodeQueryMessages
+
.EXCEPTION_FAILED_TO_READ_CHUNK_DATA_FROM_TSFILE_ARG_B88F2496,
+ tsFile)
+ : DataNodeQueryMessages
+
.EXCEPTION_FAILED_TO_READ_CHUNK_DATA_THE_TSFILE_MAY_BE_CORRUPTED_PLEASE_CHECK_THE_LOGS_FOR_THE_CORRUPTED_FILE_PATH_F0FFE629,
+ e);
}
if (chunkMetaData.isDataTypeModifiedAndCannotUseStatistics()) {
chunkReader.markDataTypeModifiedAndCannotUseStatistics();
}
- return chunkReader.loadPageReaderList();
+ try {
+ return chunkReader.loadPageReaderList();
Review Comment:
[P2] For current disk readers this catch is unreachable: `ChunkReader` and
`AbstractAlignedChunkReader` build page readers in constructors called by
`getChunkReader()` above, while `AbstractChunkReader.loadPageReaderList()` only
returns the prebuilt list. Page-header construction (and aligned time-page
decompression) is therefore reported as `READ_CHUNK_DATA`, never
`LOAD_PAGE_READER`. Please move the stage boundary to where construction occurs
or remove/collapse this stage, and add an exact-stage test.
--
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]