This is an automated email from the ASF dual-hosted git repository.
jt2594838 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 7b386bf50f7 Fix aligned TsFile LOAD data loss (#19371)
7b386bf50f7 is described below
commit 7b386bf50f7389367e487487cc96d745be208532
Author: Caideyipi <[email protected]>
AuthorDate: Thu Nov 26 11:43:57 2026 +0800
Fix aligned TsFile LOAD data loss (#19371)
* Fix aligned TsFile LOAD data loss
* Fix TsFile LOAD fallback with modifications
* Resolve Sonar findings in aligned TsFile load
* Preserve aligned value chunk order with deletions
* Avoid replaying modified TsFile data at load EOF
* Skip point counts for unmodified TsFiles
* Address aligned LOAD review comments
---
.../org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java | 137 +++
.../IoTDBPipeTypeConversionSemanticIT.java | 118 ++-
.../iotdb/db/i18n/StorageEngineMessages.java | 3 +
.../iotdb/db/i18n/StorageEngineMessages.java | 3 +
.../scan/TsFileInsertionEventScanParser.java | 184 +++-
.../converter/LoadTreeTsFileTabletIterator.java | 704 ++++++++++++++--
...atementDataTypeConvertExecutionVisitorTest.java | 928 +++++++++++++++++++++
7 files changed, 1957 insertions(+), 120 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
index 86d0dccd3ab..44bab351010 100644
---
a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java
@@ -35,6 +35,7 @@ import org.apache.iotdb.it.utils.TsFileGenerator;
import org.apache.iotdb.itbase.category.ClusterIT;
import org.apache.iotdb.itbase.category.LocalStandaloneIT;
import org.apache.iotdb.jdbc.IoTDBSQLException;
+import org.apache.iotdb.pipe.it.dual.TypeConversionSemanticCase;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.tsfile.enums.TSDataType;
@@ -667,6 +668,142 @@ public class IoTDBLoadTsFileIT {
}
}
+ @Test
+ public void testLoadWithAllConflictingAlignedDataTypes() throws Exception {
+ final String database = "root.load.aligned_type_conflict";
+ final String allConflictDevice = database + ".d_all_conflict";
+ final String oneConflictDevice = database + ".d_one_conflict";
+ final String nonAlignedDevice = database + ".na";
+ final File source = new File(tmpDir, "aligned-type-conflict.tsfile");
+ final List<TSDataType> conflictingTargetTypes =
+ Arrays.asList(
+ TSDataType.INT32,
+ TSDataType.INT64,
+ TSDataType.FLOAT,
+ TSDataType.DOUBLE,
+ TSDataType.BLOB,
+ TSDataType.DATE,
+ TSDataType.TIMESTAMP,
+ TSDataType.INT32,
+ TSDataType.INT64);
+ final List<TSDataType> oneConflictTargetTypes =
+ new ArrayList<>(Collections.nCopies(conflictingTargetTypes.size(),
TSDataType.BOOLEAN));
+ oneConflictTargetTypes.set(0, TSDataType.INT32);
+ final List<String> measurements = new ArrayList<>();
+ final List<IMeasurementSchema> sourceSchemas = new ArrayList<>();
+ final List<IMeasurementSchema> allConflictSchemas = new ArrayList<>();
+ final List<IMeasurementSchema> oneConflictSchemas = new ArrayList<>();
+ for (int measurementIndex = 0;
+ measurementIndex < conflictingTargetTypes.size();
+ measurementIndex++) {
+ final String measurement = "s" + measurementIndex;
+ measurements.add(measurement);
+ sourceSchemas.add(new MeasurementSchema(measurement, TSDataType.BOOLEAN,
TSEncoding.PLAIN));
+ allConflictSchemas.add(
+ new MeasurementSchema(measurement,
conflictingTargetTypes.get(measurementIndex)));
+ oneConflictSchemas.add(
+ new MeasurementSchema(measurement,
oneConflictTargetTypes.get(measurementIndex)));
+ }
+ try {
+ try (final Connection connection = EnvFactory.getEnv().getConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute("create database " + database);
+ statement.execute(convert2AlignedSQL(allConflictDevice,
allConflictSchemas));
+ statement.execute(convert2AlignedSQL(oneConflictDevice,
oneConflictSchemas));
+ for (int measurementIndex = 0;
+ measurementIndex < conflictingTargetTypes.size();
+ measurementIndex++) {
+ statement.execute(
+ convert2SQL(
+ nonAlignedDevice, (MeasurementSchema)
allConflictSchemas.get(measurementIndex)));
+ }
+ }
+ try (final TsFileWriter writer = new TsFileWriter(source)) {
+ writer.registerAlignedTimeseries(new Path(allConflictDevice),
sourceSchemas);
+ writer.registerAlignedTimeseries(new Path(oneConflictDevice),
sourceSchemas);
+ writer.registerTimeseries(new Path(nonAlignedDevice), sourceSchemas);
+ writeBooleanRows(writer, allConflictDevice, sourceSchemas, true);
+ writeBooleanRows(writer, oneConflictDevice, sourceSchemas, true);
+ writeBooleanRows(writer, nonAlignedDevice, sourceSchemas, false);
+ }
+
+ try (final Connection connection = EnvFactory.getEnv().getConnection();
+ final Statement statement = connection.createStatement()) {
+ statement.execute(
+ String.format(
+ "load \"%s\" with ('auto-create-schema'='false',
'convert-on-type-mismatch'='true')",
+ source.getAbsolutePath()));
+ for (final String device :
+ Arrays.asList(allConflictDevice, oneConflictDevice,
nonAlignedDevice)) {
+ final List<TSDataType> targetTypes =
+ device.equals(oneConflictDevice) ? oneConflictTargetTypes :
conflictingTargetTypes;
+ try (final ResultSet resultSet =
+ statement.executeQuery(
+ "select "
+ + String.join(",", measurements)
+ + " from "
+ + device
+ + " order by time")) {
+ for (int row = 0; row < 4; row++) {
+ Assert.assertTrue("Missing row " + row + " for " + device,
resultSet.next());
+ Assert.assertEquals(row + 1, resultSet.getLong(1));
+ for (int column = 0; column < measurements.size(); column++) {
+ Assert.assertEquals(
+ "Unexpected value for "
+ + device
+ + "."
+ + measurements.get(column)
+ + " at row "
+ + row,
+ expectedBooleanConversionValue(targetTypes.get(column),
row),
+ resultSet.getString(column + 2));
+ }
+ }
+ Assert.assertFalse(resultSet.next());
+ }
+ }
+ }
+ } finally {
+ try (final Connection connection = EnvFactory.getEnv().getConnection();
+ final Statement statement = connection.createStatement()) {
+ deleteDatabaseIfExists(statement, database);
+ }
+ }
+ }
+
+ private void writeBooleanRows(
+ final TsFileWriter writer,
+ final String device,
+ final List<IMeasurementSchema> schemas,
+ final boolean isAligned)
+ throws Exception {
+ final Tablet tablet = new Tablet(device, schemas, 4);
+ for (int row = 0; row < 4; row++) {
+ tablet.addTimestamp(row, row + 1);
+ for (int column = 0; column < schemas.size(); column++) {
+ tablet.addValue(row, column, row % 3 != 1);
+ }
+ }
+ if (isAligned) {
+ writer.writeAligned(tablet);
+ } else {
+ writer.writeTree(tablet);
+ }
+ }
+
+ private String expectedBooleanConversionValue(final TSDataType targetType,
final int row) {
+ if (targetType == TSDataType.BOOLEAN) {
+ return row % 3 != 1 ? "true" : "false";
+ }
+ for (final TypeConversionSemanticCase conversionCase :
TypeConversionSemanticCase.CASES) {
+ if (conversionCase.sourceType == TSDataType.BOOLEAN
+ && conversionCase.targetType == targetType) {
+ return conversionCase.expectedValues[row %
conversionCase.expectedValues.length];
+ }
+ }
+ throw new IllegalArgumentException("No Boolean conversion expectation for
" + targetType);
+ }
+
// Loading aligned and non-aligned devices extends the bound template and
preserves every point.
@Test
public void testLoadWithExtendTemplate() throws Exception {
diff --git
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/dual/treemodel/auto/enhanced/IoTDBPipeTypeConversionSemanticIT.java
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/dual/treemodel/auto/enhanced/IoTDBPipeTypeConversionSemanticIT.java
index cb4b0cd1e51..f8e2754dd8f 100644
---
a/integration-test/src/test/java/org/apache/iotdb/pipe/it/dual/treemodel/auto/enhanced/IoTDBPipeTypeConversionSemanticIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/pipe/it/dual/treemodel/auto/enhanced/IoTDBPipeTypeConversionSemanticIT.java
@@ -26,6 +26,7 @@ import org.apache.iotdb.itbase.env.BaseEnv;
import org.apache.iotdb.pipe.it.dual.TypeConversionSemanticCase;
import
org.apache.iotdb.pipe.it.dual.treemodel.auto.AbstractPipeTreeModelSharedClusterIT;
+import org.apache.tsfile.enums.TSDataType;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@@ -41,6 +42,12 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
private static final String DEVICE = "root.pipe_type_conversion.d";
private static final String ALIGNED_DEVICE =
"root.pipe_type_conversion.aligned_d";
+ private static final String HISTORY_DEVICE_PREFIX =
"root.pipe_type_conversion.history";
+ private static final String HISTORY_ALIGNED_ALL_CONFLICT_DEVICE =
+ HISTORY_DEVICE_PREFIX + ".d_all_conflict";
+ private static final String HISTORY_ALIGNED_ONE_CONFLICT_DEVICE =
+ HISTORY_DEVICE_PREFIX + ".d_one_conflict";
+ private static final String HISTORY_NON_ALIGNED_DEVICE =
HISTORY_DEVICE_PREFIX + ".na";
private static final List<TypeConversionSemanticCase> ALIGNED_STREAM_CASES =
getCases(
"bool_to_int32",
@@ -53,6 +60,8 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
"int32_to_boolean",
"int32_to_timestamp",
"int32_to_date");
+ private static final List<TypeConversionSemanticCase> ALIGNED_HISTORY_CASES =
+ getBooleanIncompatibleCases();
@Override
protected void setupConfig() {
@@ -66,7 +75,8 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
.getConfig()
.getCommonConfig()
.setDataReplicationFactor(1)
- .setSchemaReplicationFactor(1);
+ .setSchemaReplicationFactor(1)
+ .setAutoCreateSchemaEnabled(false);
}
@Override
@@ -110,6 +120,81 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
60);
}
+ @Test
+ public void testHistoryPipeReceiverTypeConversionForAlignedAllConflicts() {
+ createAlignedTimeseries(
+ senderEnv, HISTORY_ALIGNED_ALL_CONFLICT_DEVICE, ALIGNED_HISTORY_CASES,
true);
+ createAlignedTimeseries(
+ receiverEnv, HISTORY_ALIGNED_ALL_CONFLICT_DEVICE,
ALIGNED_HISTORY_CASES, false);
+ createAlignedTimeseries(
+ senderEnv, HISTORY_ALIGNED_ONE_CONFLICT_DEVICE, ALIGNED_HISTORY_CASES,
true);
+ createAlignedTimeseriesWithOneConflict(receiverEnv,
HISTORY_ALIGNED_ONE_CONFLICT_DEVICE);
+ createTimeseries(senderEnv, HISTORY_NON_ALIGNED_DEVICE,
ALIGNED_HISTORY_CASES, true);
+ createTimeseries(receiverEnv, HISTORY_NON_ALIGNED_DEVICE,
ALIGNED_HISTORY_CASES, false);
+
+ final List<String> insertStatements = new ArrayList<>();
+ insertStatements.addAll(
+ createInsertStatements(HISTORY_ALIGNED_ALL_CONFLICT_DEVICE,
ALIGNED_HISTORY_CASES, true));
+ insertStatements.addAll(
+ createInsertStatements(HISTORY_ALIGNED_ONE_CONFLICT_DEVICE,
ALIGNED_HISTORY_CASES, true));
+ insertStatements.addAll(
+ createInsertStatements(HISTORY_NON_ALIGNED_DEVICE,
ALIGNED_HISTORY_CASES, false));
+ TestUtils.executeNonQueries(senderEnv, insertStatements, null);
+ createHistoryOnlyTsFilePipe();
+
+ final HashSet<String> expectedRows = new
HashSet<>(createExpectedRows(ALIGNED_HISTORY_CASES));
+ final HashSet<String> oneConflictExpectedRows =
+ new HashSet<>(createExpectedRowsForOneConflict(ALIGNED_HISTORY_CASES));
+ for (final String device :
+ List.of(
+ HISTORY_ALIGNED_ONE_CONFLICT_DEVICE,
+ HISTORY_NON_ALIGNED_DEVICE,
+ HISTORY_ALIGNED_ALL_CONFLICT_DEVICE)) {
+ TestUtils.assertDataEventuallyOnEnv(
+ receiverEnv,
+ createQuerySql(device, ALIGNED_HISTORY_CASES),
+ createExpectedHeader(device, ALIGNED_HISTORY_CASES),
+ device.equals(HISTORY_ALIGNED_ONE_CONFLICT_DEVICE)
+ ? oneConflictExpectedRows
+ : expectedRows,
+ 60);
+ }
+ }
+
+ private static void createAlignedTimeseriesWithOneConflict(
+ final BaseEnv env, final String device) {
+ final List<String> measurements = new ArrayList<>();
+ for (int i = 0; i < ALIGNED_HISTORY_CASES.size(); i++) {
+ measurements.add(
+ String.format(
+ "%s %s encoding=PLAIN",
+ ALIGNED_HISTORY_CASES.get(i).measurement,
+ i == 0
+ ? ALIGNED_HISTORY_CASES.get(i).targetType
+ : ALIGNED_HISTORY_CASES.get(i).sourceType));
+ }
+ TestUtils.executeNonQuery(
+ env,
+ String.format("create aligned timeseries %s(%s)", device,
String.join(",", measurements)),
+ null);
+ }
+
+ private void createHistoryOnlyTsFilePipe() {
+ TestUtils.executeNonQuery(
+ senderEnv,
+ String.format(
+ "create pipe aligned_history_type_conversion"
+ + " with source
('source'='iotdb-source','source.path'='%s.**',"
+ +
"'source.inclusion'='data.insert','source.capture.tree'='true',"
+ +
"'source.capture.table'='false','source.history.enable'='true',"
+ + "'source.realtime.enable'='false')"
+ + " with processor ('processor'='do-nothing-processor')"
+ + " with sink
('sink'='iotdb-thrift-sink','sink.node-urls'='%s')",
+ HISTORY_DEVICE_PREFIX,
+ receiverEnv.getDataNodeWrapperList().get(0).getIpAndPortString()),
+ null);
+ }
+
private static void createTimeseries(
final BaseEnv env,
final String device,
@@ -235,6 +320,26 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
return rows;
}
+ private static List<String> createExpectedRowsForOneConflict(
+ final List<TypeConversionSemanticCase> conversionCases) {
+ final List<String> rows = new ArrayList<>();
+ for (int row = 0; row < TypeConversionSemanticCase.ROW_COUNT; row++) {
+ final List<String> values = new ArrayList<>();
+ values.add(Integer.toString(row + 1));
+ for (int measurementIndex = 0;
+ measurementIndex < conversionCases.size();
+ measurementIndex++) {
+ final TypeConversionSemanticCase conversionCase =
conversionCases.get(measurementIndex);
+ values.add(
+ measurementIndex == 0
+ ? conversionCase.expectedValues[row]
+ : conversionCase.sourceSqlValues[row]);
+ }
+ rows.add(String.join(Character.toString(','), values) +
Character.toString(','));
+ }
+ return rows;
+ }
+
private static List<TypeConversionSemanticCase> getCases(final String...
measurements) {
final List<TypeConversionSemanticCase> cases = new ArrayList<>();
for (final String measurement : measurements) {
@@ -243,6 +348,17 @@ public class IoTDBPipeTypeConversionSemanticIT extends
AbstractPipeTreeModelShar
return cases;
}
+ private static List<TypeConversionSemanticCase>
getBooleanIncompatibleCases() {
+ final List<TypeConversionSemanticCase> cases = new ArrayList<>();
+ for (final TypeConversionSemanticCase conversionCase :
TypeConversionSemanticCase.CASES) {
+ if (conversionCase.sourceType == TSDataType.BOOLEAN
+ &&
!conversionCase.targetType.isCompatible(conversionCase.sourceType)) {
+ cases.add(conversionCase);
+ }
+ }
+ return cases;
+ }
+
private static TypeConversionSemanticCase getCase(final String measurement) {
for (final TypeConversionSemanticCase conversionCase :
TypeConversionSemanticCase.CASES) {
if (conversionCase.measurement.equals(measurement)) {
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
index 91802ff30b0..e40a54c0c12 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java
@@ -62,6 +62,9 @@ public final class StorageEngineMessages {
public static final String
EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3 =
"Failed to iterate tablets while loading TsFile.";
+ public static final String
+
EXCEPTION_QUERY_FALLBACK_POINT_COUNT_MISMATCH_FOR_DEVICE_ARG_MEASUREMENT_ARG_EXPECTED_ARG_POINTS_BUT_RECOVERED_ARG_POINTS_0BEC4004
=
+ "Query fallback point count mismatch for device %s, measurement %s:
expected %d points, but recovered %d points.";
public static final String EXCEPTION_USAGE_WALPRINTTOOL_FILE_11D2FB79 =
"Usage: WALPrintTool <file>";
public static final String
MESSAGE_ARG_ARG_GET_FLUSHQUERYLOCK_WRITE_LOCK_687C85BC =
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
index a2429b5438c..532b664dab4 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java
@@ -60,6 +60,9 @@ public final class StorageEngineMessages {
public static final String IS_NOT_SUPPORTED =
" 不受支持";
+ public static final String
+
EXCEPTION_QUERY_FALLBACK_POINT_COUNT_MISMATCH_FOR_DEVICE_ARG_MEASUREMENT_ARG_EXPECTED_ARG_POINTS_BUT_RECOVERED_ARG_POINTS_0BEC4004
=
+ "设备 %s 的测量值 %s 查询回退点数不匹配:预期 %d 个点,但恢复了 %d 个点。";
public static final String
EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3 =
"加载 TsFile 时迭代 tablet 失败。";
public static final String EXCEPTION_USAGE_WALPRINTTOOL_FILE_11D2FB79 =
"用法:WALPrintTool <file>";
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java
index b3c5401eeb4..dadeb90b399 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java
@@ -91,9 +91,30 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
private static final int TS_FILE_INPUT_BUFFER_SIZE_IN_BYTES = 8 * 1024;
+ private record ParserContext(
+ String pipeName,
+ long creationTime,
+ File tsFile,
+ ScanOptions scanOptions,
+ PipeTaskMeta pipeTaskMeta,
+ IAuditEntity entity,
+ ParserOptions parserOptions) {}
+
+ private record ParserOptions(
+ boolean skipIfNoPrivileges,
+ PipeInsertionEvent sourceEvent,
+ boolean isWithMod,
+ TsFileInsertionEventParserMemoryManager memoryManager) {}
+
+ public record ScanOptions(
+ TreePattern pattern, long startTime, long endTime, boolean
trackPointCounts) {}
+
private final long startTime;
private final long endTime;
private final Filter filter;
+ private final boolean trackPointCounts;
+ private final Map<IDeviceID, Map<String, Long>> parsedPointCountsByDevice =
new HashMap<>();
+ private final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice
= new HashMap<>();
private IChunkReader chunkReader;
private BatchData data;
@@ -165,23 +186,39 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
final boolean isWithMod,
final TsFileInsertionEventParserMemoryManager memoryManager)
throws IOException, IllegalPathException {
+ this(
+ new ParserContext(
+ pipeName,
+ creationTime,
+ tsFile,
+ new ScanOptions(pattern, startTime, endTime, false),
+ pipeTaskMeta,
+ entity,
+ new ParserOptions(skipIfNoPrivileges, sourceEvent, isWithMod,
memoryManager)));
+ }
+
+ private TsFileInsertionEventScanParser(final ParserContext parserContext)
+ throws IOException, IllegalPathException {
super(
- tsFile,
- pipeName,
- creationTime,
- pattern,
+ parserContext.tsFile(),
+ parserContext.pipeName(),
+ parserContext.creationTime(),
+ parserContext.scanOptions().pattern(),
null,
- startTime,
- endTime,
- pipeTaskMeta,
- entity,
- skipIfNoPrivileges,
- sourceEvent,
- isWithMod,
- memoryManager);
-
- this.startTime = startTime;
- this.endTime = endTime;
+ parserContext.scanOptions().startTime(),
+ parserContext.scanOptions().endTime(),
+ parserContext.pipeTaskMeta(),
+ parserContext.entity(),
+ parserContext.parserOptions().skipIfNoPrivileges(),
+ parserContext.parserOptions().sourceEvent(),
+ parserContext.parserOptions().isWithMod(),
+ parserContext.parserOptions().memoryManager());
+
+ final ScanOptions scanOptions = parserContext.scanOptions();
+ final ParserOptions parserOptions = parserContext.parserOptions();
+ this.trackPointCounts = scanOptions.trackPointCounts();
+ this.startTime = scanOptions.startTime();
+ this.endTime = scanOptions.endTime();
filter = Objects.nonNull(timeFilterExpression) ?
timeFilterExpression.getFilter() : null;
this.allocatedMemoryBlockForBatchData =
@@ -192,15 +229,16 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
try {
currentModifications =
- isWithMod
- ? ModsOperationUtil.loadModificationsFromTsFile(tsFile)
+ parserOptions.isWithMod()
+ ?
ModsOperationUtil.loadModificationsFromTsFile(parserContext.tsFile())
: PatternTreeMapFactory.getModsPatternTreeMap();
allocatedMemoryBlockForModifications =
allocateTabletMemory(
TsFileInsertionEventScanParser.class.getSimpleName() +
"#modifications",
currentModifications.ramBytesUsed());
- tsFileSequenceReader = createTsFileSequenceReader(tsFile,
!currentModifications.isEmpty());
+ tsFileSequenceReader =
+ createTsFileSequenceReader(parserContext.tsFile(),
!currentModifications.isEmpty());
tsFileSequenceReader.position(tsFileSequenceReader.getDataStartOffset());
prepareData();
@@ -213,6 +251,25 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
}
}
+ public TsFileInsertionEventScanParser(
+ final File tsFile,
+ final PipeTaskMeta pipeTaskMeta,
+ final PipeInsertionEvent sourceEvent,
+ final boolean isWithMod,
+ final TsFileInsertionEventParserMemoryManager memoryManager,
+ final ScanOptions scanOptions)
+ throws IOException, IllegalPathException {
+ this(
+ new ParserContext(
+ null,
+ 0,
+ tsFile,
+ scanOptions,
+ pipeTaskMeta,
+ null,
+ new ParserOptions(false, sourceEvent, isWithMod, memoryManager)));
+ }
+
public TsFileInsertionEventScanParser(
final File tsFile,
final TreePattern pattern,
@@ -244,18 +301,12 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
final TsFileInsertionEventParserMemoryManager memoryManager)
throws IOException, IllegalPathException {
this(
- null,
- 0,
tsFile,
- pattern,
- startTime,
- endTime,
pipeTaskMeta,
- null,
- false,
sourceEvent,
isWithMod,
- memoryManager);
+ memoryManager,
+ new ScanOptions(pattern, startTime, endTime, false));
}
private TsFileSequenceReader createTsFileSequenceReader(
@@ -412,6 +463,20 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
return measurementIds;
}
+ public Map<IDeviceID, Map<String, Long>> getParsedPointCounts() {
+ final Map<IDeviceID, Map<String, Long>> result = new HashMap<>();
+ parsedPointCountsByDevice.forEach(
+ (device, pointCounts) -> result.put(device, new
HashMap<>(pointCounts)));
+ return result;
+ }
+
+ public Map<IDeviceID, Map<String, Long>> getExpectedPointCounts() {
+ final Map<IDeviceID, Map<String, Long>> result = new HashMap<>();
+ expectedPointCountsByDevice.forEach(
+ (device, pointCounts) -> result.put(device, new
HashMap<>(pointCounts)));
+ return result;
+ }
+
private Tablet getNextTablet() {
Tablet tablet = null;
boolean tabletMemoryReserved = false;
@@ -453,6 +518,8 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
final int rowIndex = tablet.getRowSize();
+ recordParsedPointCounts(data);
+ recordExpectedPointCounts(data);
if (putValueToColumns(data, tablet, rowIndex)) {
PipeTabletUtils.putTimestamp(tablet, rowIndex, data.currentTime());
}
@@ -623,6 +690,61 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
return isNeedFillTime;
}
+ private void recordParsedPointCounts(final BatchData batchData) {
+ if (!trackPointCounts) {
+ return;
+ }
+
+ if (batchData.getDataType() == TSDataType.VECTOR) {
+ final TsPrimitiveType[] values = batchData.getVector();
+ for (int column = 0; column < values.length; column++) {
+ if (values[column] != null) {
+
addParsedPointCount(currentMeasurements.get(column).getMeasurementName(), 1);
+ }
+ }
+ return;
+ }
+
+ addParsedPointCount(currentMeasurements.get(0).getMeasurementName(), 1);
+ }
+
+ private void recordExpectedPointCounts(final BatchData batchData) {
+ if (!trackPointCounts || currentModifications.isEmpty()) {
+ return;
+ }
+
+ if (batchData.getDataType() == TSDataType.VECTOR) {
+ final TsPrimitiveType[] values = batchData.getVector();
+ for (int column = 0; column < values.length; column++) {
+ if (values[column] != null
+ && !ModsOperationUtil.isDelete(batchData.currentTime(),
modsInfos.get(column))) {
+
addExpectedPointCount(currentMeasurements.get(column).getMeasurementName());
+ }
+ }
+ return;
+ }
+
+ if (modsInfos.isEmpty()
+ || !ModsOperationUtil.isDelete(batchData.currentTime(),
modsInfos.get(0))) {
+ addExpectedPointCount(currentMeasurements.get(0).getMeasurementName());
+ }
+ }
+
+ private void addParsedPointCount(final String measurement, final long
pointCount) {
+ if (!trackPointCounts || pointCount == 0) {
+ return;
+ }
+ parsedPointCountsByDevice
+ .computeIfAbsent(currentDevice, key -> new HashMap<>())
+ .merge(measurement, pointCount, Long::sum);
+ }
+
+ private void addExpectedPointCount(final String measurement) {
+ expectedPointCountsByDevice
+ .computeIfAbsent(currentDevice, key -> new HashMap<>())
+ .merge(measurement, 1L, Long::sum);
+ }
+
private void moveToNextChunkReader()
throws IOException, IllegalStateException, IllegalPathException {
releaseChunkReader();
@@ -718,11 +840,6 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
final long currentChunkHeaderOffset =
tsFileSequenceReader.position() - 1;
chunkHeader = tsFileSequenceReader.readChunkHeader(marker);
- if (filterChunk(currentChunkHeaderOffset, chunkHeader, true,
marker)) {
- break;
- }
-
- // Increase value index.
final String measurementID =
tabletStringInternPool.intern(chunkHeader.getMeasurementID());
final int valueIndex =
@@ -730,6 +847,10 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
measurementID,
(measurement, index) -> Objects.nonNull(index) ? index +
1 : 0);
+ if (filterChunk(currentChunkHeaderOffset, chunkHeader, true,
marker)) {
+ break;
+ }
+
// Do not record or end current value chunks when there are
empty chunks.
if (chunkHeader.getDataSize() == 0) {
break;
@@ -853,6 +974,7 @@ public class TsFileInsertionEventScanParser extends
TsFileInsertionEventParser {
statistics.getEndTime(),
currentModifications,
false)) {
+ addParsedPointCount(chunkHeader.getMeasurementID(),
statistics.getCount());
tsFileSequenceReader.position(nextMarkerOffset);
return true;
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeTsFileTabletIterator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeTsFileTabletIterator.java
index 7b3b4d7efbd..ee011e1db16 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeTsFileTabletIterator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeTsFileTabletIterator.java
@@ -21,23 +21,41 @@ package org.apache.iotdb.db.storageengine.load.converter;
import org.apache.iotdb.commons.exception.IllegalPathException;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException;
+import org.apache.iotdb.commons.path.PatternTreeMap;
import org.apache.iotdb.commons.pipe.datastructure.pattern.IoTDBTreePattern;
import org.apache.iotdb.commons.pipe.datastructure.pattern.TreePattern;
+import org.apache.iotdb.commons.utils.TestOnly;
import org.apache.iotdb.db.exception.load.LoadAnalyzeInvalidPathException;
import org.apache.iotdb.db.exception.load.LoadRuntimeOutOfMemoryException;
import org.apache.iotdb.db.i18n.StorageEngineMessages;
import
org.apache.iotdb.db.pipe.event.common.tablet.PipeRawTabletInsertionEvent;
import
org.apache.iotdb.db.pipe.event.common.tsfile.parser.query.TsFileInsertionEventQueryParser;
import
org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan.TsFileInsertionEventScanParser;
+import
org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil;
+import
org.apache.iotdb.db.pipe.event.common.tsfile.parser.util.ModsOperationUtil.ModsInfo;
+import org.apache.iotdb.db.storageengine.dataregion.modification.ModEntry;
+import
org.apache.iotdb.db.storageengine.dataregion.modification.ModificationFile;
import
org.apache.iotdb.db.storageengine.load.memory.LoadTsFileParserMemoryManager;
+import org.apache.iotdb.db.utils.datastructure.PatternTreeMapFactory;
import org.apache.iotdb.pipe.api.event.dml.insertion.TabletInsertionEvent;
import org.apache.tsfile.exception.PathParseException;
+import org.apache.tsfile.file.metadata.AbstractAlignedChunkMetadata;
+import org.apache.tsfile.file.metadata.ChunkMetadata;
+import org.apache.tsfile.file.metadata.IChunkMetadata;
import org.apache.tsfile.file.metadata.IDeviceID;
+import org.apache.tsfile.file.metadata.MetadataIndexNode;
import org.apache.tsfile.file.metadata.TimeseriesMetadata;
+import org.apache.tsfile.read.TsFileDeviceIterator;
import org.apache.tsfile.read.TsFileSequenceReader;
import org.apache.tsfile.read.TsFileSequenceReaderTimeseriesMetadataIterator;
+import org.apache.tsfile.read.common.BatchData;
+import org.apache.tsfile.read.common.Chunk;
+import org.apache.tsfile.read.reader.IChunkReader;
+import org.apache.tsfile.read.reader.chunk.AlignedChunkReader;
+import org.apache.tsfile.read.reader.chunk.ChunkReader;
import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.TsPrimitiveType;
import org.apache.tsfile.write.record.Tablet;
import org.apache.tsfile.write.schema.IMeasurementSchema;
import org.slf4j.Logger;
@@ -48,20 +66,22 @@ import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
-import java.util.stream.Collectors;
+import java.util.Set;
import static
org.apache.iotdb.db.storageengine.load.LoadTsFilePathUtils.getValidatedDevicePath;
/**
* Load uses scan parsing first for throughput. If scan parsing hits
corruption, fall back to query
- * parsing for the remaining measurements and devices so later data can still
be loaded. Report any
- * unrecoverable query failure after exhausting the readable data so a partial
load cannot succeed.
+ * parsing for the remaining measurements and devices. At normal EOF,
query-parse devices whose
+ * emitted point counts do not match their TsFile metadata. Report
unrecoverable query failures so a
+ * partial load cannot succeed.
*/
class LoadTreeTsFileTabletIterator
implements Iterable<Pair<Tablet, Boolean>>, Iterator<Pair<Tablet,
Boolean>>, AutoCloseable {
@@ -83,22 +103,108 @@ class LoadTreeTsFileTabletIterator
private final File file;
private final boolean isWithMod;
+ private final ScanParserFactory scanParserFactory;
+ private final QueryParserFactory queryParserFactory;
private final ArrayDeque<QueryTask> pendingQueryTasks = new ArrayDeque<>();
private TsFileInsertionEventScanParser scanParser;
private QueryTask activeQueryTask;
- private TsFileInsertionEventQueryParser activeQueryParser;
+ private QueryParser activeQueryParser;
private Iterator<Pair<Tablet, Boolean>> activeIterator;
private boolean scanInitialized;
private boolean fallbackTriggered;
private RuntimeException unrecoverableQueryFailure;
+ private Boolean hasModifications;
private final Map<IDeviceID, Map<String, Long>>
lastEmittedTimestampsByDevice =
new LinkedHashMap<>();
+ private final Map<IDeviceID, Map<String, Long>> emittedPointCountsByDevice =
+ new LinkedHashMap<>();
+ private final Map<IDeviceID, Map<String, Long>>
expectedQueryFallbackPointCountsByDevice =
+ new LinkedHashMap<>();
+ private final Map<IDeviceID, Map<String, Long>>
queryFallbackPointCountsByDevice =
+ new LinkedHashMap<>();
LoadTreeTsFileTabletIterator(final File file, final boolean isWithMod) {
+ this(
+ file,
+ isWithMod,
+ sourceFile ->
+ new TsFileInsertionEventScanParser(
+ sourceFile,
+ null,
+ null,
+ isWithMod,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ LOAD_TREE_PATTERN, Long.MIN_VALUE, Long.MAX_VALUE, true)));
+ }
+
+ @TestOnly
+ LoadTreeTsFileTabletIterator(
+ final File file, final boolean isWithMod, final ScanParserFactory
scanParserFactory) {
+ this(
+ file,
+ isWithMod,
+ scanParserFactory,
+ (sourceFile, device, measurements, startTime, endTime, withMod) -> {
+ final TsFileInsertionEventQueryParser parser =
+ new TsFileInsertionEventQueryParser(
+ sourceFile,
+ LOAD_TREE_PATTERN,
+ startTime,
+ endTime,
+ Collections.singletonMap(device, measurements),
+ withMod,
+ LoadTsFileParserMemoryManager.getInstance());
+ return new QueryParser() {
+ @Override
+ public Iterator<Pair<Tablet, Boolean>> iterator() {
+ final Iterator<TabletInsertionEvent> tabletIterator =
+ parser.toTabletInsertionEvents().iterator();
+ return new Iterator<Pair<Tablet, Boolean>>() {
+ @Override
+ public boolean hasNext() {
+ return tabletIterator.hasNext();
+ }
+
+ @Override
+ public Pair<Tablet, Boolean> next() {
+ final TabletInsertionEvent event = tabletIterator.next();
+ if (!(event instanceof PipeRawTabletInsertionEvent)) {
+ throw new IllegalStateException(
+ StorageEngineMessages
+
.EXCEPTION_EXPECTED_PIPERAWTABLETINSERTIONEVENT_BUT_GOT_D1D1DD05
+ + event.getClass().getName());
+ }
+
+ final PipeRawTabletInsertionEvent rawTabletInsertionEvent =
+ (PipeRawTabletInsertionEvent) event;
+ return new Pair<>(
+ rawTabletInsertionEvent.convertToTablet(),
+ rawTabletInsertionEvent.isAligned());
+ }
+ };
+ }
+
+ @Override
+ public void close() {
+ parser.close();
+ }
+ };
+ });
+ }
+
+ @TestOnly
+ LoadTreeTsFileTabletIterator(
+ final File file,
+ final boolean isWithMod,
+ final ScanParserFactory scanParserFactory,
+ final QueryParserFactory queryParserFactory) {
this.file = file;
this.isWithMod = isWithMod;
+ this.scanParserFactory = scanParserFactory;
+ this.queryParserFactory = queryParserFactory;
}
@Override
@@ -166,16 +272,7 @@ class LoadTreeTsFileTabletIterator
if (!scanInitialized && !fallbackTriggered) {
scanInitialized = true;
try {
- scanParser =
- new TsFileInsertionEventScanParser(
- file,
- LOAD_TREE_PATTERN,
- Long.MIN_VALUE,
- Long.MAX_VALUE,
- null,
- null,
- isWithMod,
- LoadTsFileParserMemoryManager.getInstance());
+ scanParser = scanParserFactory.create(file);
activeIterator = scanParser.toTabletWithIsAligneds().iterator();
return;
} catch (final Exception e) {
@@ -192,16 +289,45 @@ class LoadTreeTsFileTabletIterator
activateNextQueryParser();
}
- private boolean switchToNextIterator() {
+ private boolean switchToNextIterator() throws IOException {
if (Objects.nonNull(activeQueryParser)) {
closeActiveQueryParser();
return activateNextQueryParser();
}
+ final Map<IDeviceID, Map<String, Long>> parsedPointCounts =
+ Objects.nonNull(scanParser) ? scanParser.getParsedPointCounts() :
Collections.emptyMap();
+ final Map<IDeviceID, Map<String, Long>> expectedPointCounts =
+ Objects.nonNull(scanParser) ? scanParser.getExpectedPointCounts() :
Collections.emptyMap();
closeScanParser();
+ try {
+ enqueueQueryTasksForUnemittedData(parsedPointCounts,
expectedPointCounts);
+ } catch (final Exception e) {
+ if (shouldRethrow(e)) {
+ throw toRuntimeException(e);
+ }
+ unrecoverableQueryFailure = toRuntimeException(e);
+ return false;
+ }
return activateNextQueryParser();
}
+ private void enqueueQueryTasksForUnemittedData(
+ final Map<IDeviceID, Map<String, Long>> parsedPointCounts,
+ final Map<IDeviceID, Map<String, Long>> expectedPointCounts)
+ throws IOException {
+ if (fallbackTriggered) {
+ return;
+ }
+
+ final ArrayDeque<QueryTask> queryTasks =
+ buildQueryTasks(parsedPointCounts, expectedPointCounts);
+ if (!queryTasks.isEmpty()) {
+ fallbackTriggered = true;
+ pendingQueryTasks.addAll(queryTasks);
+ }
+ }
+
private boolean recoverFromIteratorFailure(final Exception e) {
if (shouldRethrow(e)) {
return false;
@@ -233,7 +359,7 @@ class LoadTreeTsFileTabletIterator
closeScanParser();
try {
- pendingQueryTasks.addAll(buildQueryTasks());
+ pendingQueryTasks.addAll(buildQueryTasks(emittedPointCountsByDevice,
null));
} catch (final Exception queryInitException) {
LOGGER.warn(
StorageEngineMessages
@@ -252,26 +378,34 @@ class LoadTreeTsFileTabletIterator
return true;
}
- private ArrayDeque<QueryTask> buildQueryTasks() throws IOException {
- final LinkedHashMap<IDeviceID, List<String>> deviceMeasurementsMap =
- readDeviceMeasurementsInOrder();
- if (deviceMeasurementsMap.isEmpty()) {
- return new ArrayDeque<>();
- }
-
+ private ArrayDeque<QueryTask> buildQueryTasks(
+ final Map<IDeviceID, Map<String, Long>> completedPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>>
scannedExpectedPointCountsByDevice)
+ throws IOException {
final ArrayDeque<QueryTask> tasks = new ArrayDeque<>();
- // Devices and measurements can recur in later chunk groups. The metadata
index order does
- // not describe the scan position, so resume every series from its own
emitted prefix.
- for (final Map.Entry<IDeviceID, List<String>> entry :
deviceMeasurementsMap.entrySet()) {
- addQueryTasks(tasks, entry.getKey(), entry.getValue(), Long.MIN_VALUE,
Long.MAX_VALUE);
- }
+ final boolean containsModifications = hasModifications();
+ final Map<IDeviceID, Map<String, Long>> metadataPointCountsByDevice =
+ readMetadataPointCountsByDevice();
+ final Set<IDeviceID> unverifiableDevices = new HashSet<>();
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice =
+ containsModifications
+ ? Objects.nonNull(scannedExpectedPointCountsByDevice)
+ && pointCountsMatch(completedPointCountsByDevice,
metadataPointCountsByDevice)
+ ? scannedExpectedPointCountsByDevice
+ : readExpectedPointCountsWithMods(metadataPointCountsByDevice,
unverifiableDevices)
+ : metadataPointCountsByDevice;
+ final Map<IDeviceID, Map<String, Long>> progressPointCountsByDevice =
+ containsModifications ? emittedPointCountsByDevice :
completedPointCountsByDevice;
+
+ appendQueryTasksForIncompleteMeasurements(
+ tasks, expectedPointCountsByDevice, progressPointCountsByDevice,
unverifiableDevices);
+ verifyCompletedPointCounts(progressPointCountsByDevice,
expectedPointCountsByDevice);
return tasks;
}
- private LinkedHashMap<IDeviceID, List<String>>
readDeviceMeasurementsInOrder()
- throws IOException {
- final LinkedHashMap<IDeviceID, List<String>> deviceMeasurementsMap = new
LinkedHashMap<>();
+ private Map<IDeviceID, Map<String, Long>> readMetadataPointCountsByDevice()
throws IOException {
+ final Map<IDeviceID, Map<String, Long>> metadataPointCountsByDevice = new
LinkedHashMap<>();
try (final TsFileSequenceReader reader = new
TsFileSequenceReader(file.getAbsolutePath())) {
// iterAllTimeseriesMetadata treats an IOException as the end of
iteration. Use the
// throwing batch iterator so an incomplete metadata index cannot turn a
partial load into a
@@ -281,27 +415,382 @@ class LoadTreeTsFileTabletIterator
while (metadataIterator.hasNext()) {
for (final Map.Entry<IDeviceID, List<TimeseriesMetadata>>
deviceMetadata :
metadataIterator.next().entrySet()) {
- final Map<String, Long> emittedTimestamps =
- lastEmittedTimestampsByDevice.getOrDefault(
- deviceMetadata.getKey(), Collections.emptyMap());
- deviceMeasurementsMap
- .computeIfAbsent(deviceMetadata.getKey(), key -> new
ArrayList<>())
- .addAll(
- deviceMetadata.getValue().stream()
- .filter(
- metadata -> {
- final Long emittedTimestamp =
-
emittedTimestamps.get(metadata.getMeasurementId());
- return !metadata.getMeasurementId().isEmpty()
- && (emittedTimestamp == null
- || emittedTimestamp <
metadata.getStatistics().getEndTime());
- })
- .map(TimeseriesMetadata::getMeasurementId)
- .collect(Collectors.toList()));
+ final IDeviceID device = deviceMetadata.getKey();
+ for (final TimeseriesMetadata metadata : deviceMetadata.getValue()) {
+ final String measurement = metadata.getMeasurementId();
+ if (measurement.isEmpty() || metadata.getStatistics().getCount()
== 0) {
+ continue;
+ }
+
+ metadataPointCountsByDevice
+ .computeIfAbsent(device, key -> new LinkedHashMap<>())
+ .merge(measurement, (long)
metadata.getStatistics().getCount(), Long::sum);
+ }
+ }
+ }
+ }
+
+ return metadataPointCountsByDevice;
+ }
+
+ private void appendQueryTasksForIncompleteMeasurements(
+ final ArrayDeque<QueryTask> tasks,
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>> progressPointCountsByDevice,
+ final Set<IDeviceID> unverifiableDevices)
+ throws IOException {
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ expectedPointCountsByDevice.entrySet()) {
+ final IDeviceID device = deviceEntry.getKey();
+ addQueryTasksForDevice(
+ tasks,
+ device,
+ deviceEntry.getValue(),
+ progressPointCountsByDevice.getOrDefault(device,
Collections.emptyMap()),
+ unverifiableDevices.contains(device));
+ }
+ }
+
+ private void addQueryTasksForDevice(
+ final ArrayDeque<QueryTask> tasks,
+ final IDeviceID device,
+ final Map<String, Long> expectedPointCounts,
+ final Map<String, Long> completedPointCounts,
+ final boolean unverifiable)
+ throws IOException {
+ final List<String> fallbackMeasurements = new ArrayList<>();
+ final Map<String, Long> fallbackPointCounts = new LinkedHashMap<>();
+ for (final Map.Entry<String, Long> measurementEntry :
expectedPointCounts.entrySet()) {
+ final String measurement = measurementEntry.getKey();
+ final long completedPointCount =
completedPointCounts.getOrDefault(measurement, 0L);
+ if (unverifiable) {
+ fallbackMeasurements.add(measurement);
+ fallbackPointCounts.put(
+ measurement, Math.max(0, measurementEntry.getValue() -
completedPointCount));
+ continue;
+ }
+ if (completedPointCount > measurementEntry.getValue()) {
+ throw new IOException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3);
+ }
+ if (completedPointCount < measurementEntry.getValue()) {
+ fallbackMeasurements.add(measurement);
+ fallbackPointCounts.put(measurement, measurementEntry.getValue() -
completedPointCount);
+ }
+ }
+ if (fallbackMeasurements.isEmpty()) {
+ return;
+ }
+
+ expectedQueryFallbackPointCountsByDevice.put(device, fallbackPointCounts);
+ addQueryTasks(tasks, device, fallbackMeasurements, Long.MIN_VALUE,
Long.MAX_VALUE);
+ }
+
+ private void verifyCompletedPointCounts(
+ final Map<IDeviceID, Map<String, Long>> progressPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice)
+ throws IOException {
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ progressPointCountsByDevice.entrySet()) {
+ final Map<String, Long> expectedPointCounts =
+ expectedPointCountsByDevice.getOrDefault(deviceEntry.getKey(),
Collections.emptyMap());
+ for (final Map.Entry<String, Long> measurementEntry :
deviceEntry.getValue().entrySet()) {
+ if (measurementEntry.getValue()
+ > expectedPointCounts.getOrDefault(measurementEntry.getKey(), 0L))
{
+ throw new IOException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3);
}
}
}
- return deviceMeasurementsMap;
+ }
+
+ private boolean pointCountsMatch(
+ final Map<IDeviceID, Map<String, Long>> actualPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice) {
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ actualPointCountsByDevice.entrySet()) {
+ if (!measurementPointCountsMatch(
+ deviceEntry.getValue(),
+ expectedPointCountsByDevice.getOrDefault(deviceEntry.getKey(),
Collections.emptyMap()))) {
+ return false;
+ }
+ }
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ expectedPointCountsByDevice.entrySet()) {
+ if (!measurementPointCountsMatch(
+ deviceEntry.getValue(),
+ actualPointCountsByDevice.getOrDefault(deviceEntry.getKey(),
Collections.emptyMap()))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean measurementPointCountsMatch(
+ final Map<String, Long> actualPointCounts, final Map<String, Long>
expectedPointCounts) {
+ for (final Map.Entry<String, Long> measurementEntry :
actualPointCounts.entrySet()) {
+ if (!Objects.equals(
+ measurementEntry.getValue(),
+ expectedPointCounts.getOrDefault(measurementEntry.getKey(), 0L))) {
+ return false;
+ }
+ }
+ for (final Map.Entry<String, Long> measurementEntry :
expectedPointCounts.entrySet()) {
+ if (!Objects.equals(
+ measurementEntry.getValue(),
+ actualPointCounts.getOrDefault(measurementEntry.getKey(), 0L))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private Map<IDeviceID, Map<String, Long>> readExpectedPointCountsWithMods(
+ final Map<IDeviceID, Map<String, Long>> metadataPointCountsByDevice,
+ final Set<IDeviceID> unverifiableDevices)
+ throws IOException {
+ final PatternTreeMap<ModEntry, PatternTreeMapFactory.ModsSerializer>
modifications =
+ ModsOperationUtil.loadModificationsFromTsFile(file);
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice = new
LinkedHashMap<>();
+ final Map<IDeviceID, Map<String, Long>> parsedPointCountsByDevice = new
LinkedHashMap<>();
+
+ try (final TsFileSequenceReader reader = new
TsFileSequenceReader(file.getAbsolutePath())) {
+ final TsFileDeviceIterator deviceIterator =
reader.getAllDevicesIteratorWithIsAligned();
+ while (deviceIterator.hasNext()) {
+ final Pair<IDeviceID, Boolean> deviceWithAlignment =
deviceIterator.next();
+ final IDeviceID device = deviceWithAlignment.getLeft();
+ try {
+ final MetadataIndexNode metadataIndexNode =
+ deviceIterator.getFirstMeasurementNodeOfCurrentDevice();
+ final List<String> measurements =
+ new ArrayList<>(
+ reader
+ .getTimeseriesMetadataOffsetByDevice(
+ metadataIndexNode, Collections.emptySet(), false)
+ .keySet());
+ measurements.removeIf(String::isEmpty);
+ final List<ModsInfo> modsInfos =
+ ModsOperationUtil.initializeMeasurementMods(
+ device, measurements, modifications, false);
+ final Map<String, Long> parsedPointCounts = new LinkedHashMap<>();
+ final Map<String, Long> expectedPointCounts = new LinkedHashMap<>();
+
+ if (Boolean.TRUE.equals(deviceWithAlignment.getRight())) {
+ countAlignedPoints(
+ reader,
+ reader.getAlignedChunkMetadataByMetadataIndexNode(device,
metadataIndexNode, true),
+ measurements,
+ modsInfos,
+ parsedPointCounts,
+ expectedPointCounts);
+ } else {
+ countNonAlignedPoints(
+ reader, device, measurements, modsInfos, parsedPointCounts,
expectedPointCounts);
+ }
+
+ verifyParsedPointCounts(
+ measurements,
+ parsedPointCounts,
+ metadataPointCountsByDevice.getOrDefault(device,
Collections.emptyMap()));
+ parsedPointCountsByDevice.put(device, parsedPointCounts);
+ expectedPointCountsByDevice.put(device, expectedPointCounts);
+ } catch (final Exception e) {
+ if (shouldRethrow(e)) {
+ throw toRuntimeException(e);
+ }
+ unverifiableDevices.add(device);
+ expectedPointCountsByDevice.put(
+ device, metadataPointCountsByDevice.getOrDefault(device,
Collections.emptyMap()));
+ if (unrecoverableQueryFailure == null) {
+ unrecoverableQueryFailure = toRuntimeException(e);
+ }
+ }
+ }
+ }
+
+ markDevicesWithoutParsedPointCounts(
+ metadataPointCountsByDevice,
+ parsedPointCountsByDevice,
+ expectedPointCountsByDevice,
+ unverifiableDevices);
+ return expectedPointCountsByDevice;
+ }
+
+ private void markDevicesWithoutParsedPointCounts(
+ final Map<IDeviceID, Map<String, Long>> metadataPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>> parsedPointCountsByDevice,
+ final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice,
+ final Set<IDeviceID> unverifiableDevices) {
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ metadataPointCountsByDevice.entrySet()) {
+ final IDeviceID device = deviceEntry.getKey();
+ if (!parsedPointCountsByDevice.containsKey(device)) {
+ unverifiableDevices.add(device);
+ expectedPointCountsByDevice.put(device, deviceEntry.getValue());
+ if (unrecoverableQueryFailure == null) {
+ unrecoverableQueryFailure =
+ toRuntimeException(
+ new IOException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3));
+ }
+ }
+ }
+ }
+
+ private void countAlignedPoints(
+ final TsFileSequenceReader reader,
+ final List<AbstractAlignedChunkMetadata> chunkMetadataList,
+ final List<String> measurements,
+ final List<ModsInfo> modsInfos,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> expectedPointCounts)
+ throws IOException {
+ for (final AbstractAlignedChunkMetadata alignedChunkMetadata :
chunkMetadataList) {
+ countAlignedChunk(
+ reader,
+ alignedChunkMetadata,
+ measurements,
+ modsInfos,
+ parsedPointCounts,
+ expectedPointCounts);
+ }
+ }
+
+ private void countAlignedChunk(
+ final TsFileSequenceReader reader,
+ final AbstractAlignedChunkMetadata alignedChunkMetadata,
+ final List<String> measurements,
+ final List<ModsInfo> modsInfos,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> expectedPointCounts)
+ throws IOException {
+ final List<ChunkMetadata> valueChunkMetadata = new ArrayList<>();
+ for (final IChunkMetadata metadata :
alignedChunkMetadata.getValueChunkMetadataList()) {
+ valueChunkMetadata.add(metadata == null ? null : (ChunkMetadata)
metadata);
+ }
+ if (valueChunkMetadata.size() != measurements.size()) {
+ throw new IOException(
+
StorageEngineMessages.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3);
+ }
+
+ final Chunk timeChunk =
+ reader.readMemChunk((ChunkMetadata)
alignedChunkMetadata.getTimeChunkMetadata());
+ final List<Chunk> valueChunks = new ArrayList<>(valueChunkMetadata.size());
+ boolean chunksTransferredToReader = false;
+ try {
+ for (final ChunkMetadata metadata : valueChunkMetadata) {
+ valueChunks.add(metadata == null ? null :
reader.readMemChunk(metadata));
+ }
+ chunksTransferredToReader = true;
+ countAlignedChunkData(
+ timeChunk, valueChunks, measurements, modsInfos, parsedPointCounts,
expectedPointCounts);
+ } finally {
+ if (!chunksTransferredToReader) {
+ timeChunk.close();
+ valueChunks.forEach(
+ chunk -> {
+ if (chunk != null) {
+ chunk.close();
+ }
+ });
+ }
+ }
+ }
+
+ private void countAlignedChunkData(
+ final Chunk timeChunk,
+ final List<Chunk> valueChunks,
+ final List<String> measurements,
+ final List<ModsInfo> modsInfos,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> expectedPointCounts)
+ throws IOException {
+ try (final IChunkReader chunkReader = new AlignedChunkReader(timeChunk,
valueChunks)) {
+ while (chunkReader.hasNextSatisfiedPage()) {
+ final BatchData pageData = chunkReader.nextPageData();
+ while (pageData.hasCurrent()) {
+ countAlignedPage(
+ pageData, measurements, modsInfos, parsedPointCounts,
expectedPointCounts);
+ pageData.next();
+ }
+ }
+ }
+ }
+
+ private void countAlignedPage(
+ final BatchData pageData,
+ final List<String> measurements,
+ final List<ModsInfo> modsInfos,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> expectedPointCounts)
+ throws IOException {
+ final TsPrimitiveType[] values = pageData.getVector();
+ if (values.length != measurements.size()) {
+ throw new IOException(
+
StorageEngineMessages.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3);
+ }
+ for (int column = 0; column < values.length; column++) {
+ if (values[column] != null) {
+ final String measurement = measurements.get(column);
+ parsedPointCounts.merge(measurement, 1L, Long::sum);
+ if (!ModsOperationUtil.isDelete(pageData.currentTime(),
modsInfos.get(column))) {
+ expectedPointCounts.merge(measurement, 1L, Long::sum);
+ }
+ }
+ }
+ }
+
+ private void countNonAlignedPoints(
+ final TsFileSequenceReader reader,
+ final IDeviceID device,
+ final List<String> measurements,
+ final List<ModsInfo> modsInfos,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> expectedPointCounts)
+ throws IOException {
+ for (int index = 0; index < measurements.size(); index++) {
+ final String measurement = measurements.get(index);
+ for (final ChunkMetadata metadata : reader.getChunkMetadataList(device,
measurement, true)) {
+ try (final IChunkReader chunkReader = new
ChunkReader(reader.readMemChunk(metadata))) {
+ while (chunkReader.hasNextSatisfiedPage()) {
+ final BatchData pageData = chunkReader.nextPageData();
+ while (pageData.hasCurrent()) {
+ parsedPointCounts.merge(measurement, 1L, Long::sum);
+ if (!ModsOperationUtil.isDelete(pageData.currentTime(),
modsInfos.get(index))) {
+ expectedPointCounts.merge(measurement, 1L, Long::sum);
+ }
+ pageData.next();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void verifyParsedPointCounts(
+ final Iterable<String> measurements,
+ final Map<String, Long> parsedPointCounts,
+ final Map<String, Long> metadataPointCounts)
+ throws IOException {
+ for (final String measurement : measurements) {
+ final long parsedPointCount =
parsedPointCounts.getOrDefault(measurement, 0L);
+ final long metadataPointCount =
metadataPointCounts.getOrDefault(measurement, 0L);
+ if (parsedPointCount != metadataPointCount) {
+ throw new IOException(
+ StorageEngineMessages
+
.EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3);
+ }
+ }
+ }
+
+ private boolean hasModifications() throws IOException {
+ if (hasModifications == null) {
+ hasModifications = isWithMod &&
!ModificationFile.readAllModifications(file, true).isEmpty();
+ }
+ return hasModifications;
}
private void addQueryTasks(
@@ -342,39 +831,14 @@ class LoadTreeTsFileTabletIterator
try {
getValidatedDevicePath(activeQueryTask.device);
activeQueryParser =
- new TsFileInsertionEventQueryParser(
+ queryParserFactory.create(
file,
- LOAD_TREE_PATTERN,
+ activeQueryTask.device,
+ activeQueryTask.measurements,
activeQueryTask.startTime,
activeQueryTask.endTime,
- activeQueryTask.toDeviceMeasurementsMap(),
- isWithMod,
- LoadTsFileParserMemoryManager.getInstance());
- final Iterator<TabletInsertionEvent> tabletIterator =
- activeQueryParser.toTabletInsertionEvents().iterator();
- activeIterator =
- new Iterator<Pair<Tablet, Boolean>>() {
- @Override
- public boolean hasNext() {
- return tabletIterator.hasNext();
- }
-
- @Override
- public Pair<Tablet, Boolean> next() {
- final TabletInsertionEvent event = tabletIterator.next();
- if (!(event instanceof PipeRawTabletInsertionEvent)) {
- throw new IllegalStateException(
- StorageEngineMessages
-
.EXCEPTION_EXPECTED_PIPERAWTABLETINSERTIONEVENT_BUT_GOT_D1D1DD05
- + event.getClass().getName());
- }
-
- final PipeRawTabletInsertionEvent rawTabletInsertionEvent =
- (PipeRawTabletInsertionEvent) event;
- return new Pair<>(
- rawTabletInsertionEvent.convertToTablet(),
rawTabletInsertionEvent.isAligned());
- }
- };
+ isWithMod);
+ activeIterator = activeQueryParser.iterator();
return true;
} catch (final Exception e) {
if (shouldRethrow(e)) {
@@ -406,9 +870,24 @@ class LoadTreeTsFileTabletIterator
final IDeviceID device =
IDeviceID.Factory.DEFAULT_FACTORY.create(tablet.getDeviceId());
final Map<String, Long> emittedTimestamps =
lastEmittedTimestampsByDevice.computeIfAbsent(device, key -> new
LinkedHashMap<>());
- final long timestamp = tablet.getTimestamp(tablet.getRowSize() - 1);
- for (final String measurement : extractMeasurementNames(tablet)) {
- emittedTimestamps.merge(measurement, timestamp, Math::max);
+ final Map<String, Long> emittedPointCounts =
+ emittedPointCountsByDevice.computeIfAbsent(device, key -> new
LinkedHashMap<>());
+ final List<String> measurements = extractMeasurementNames(tablet);
+ final Map<String, Long> queryFallbackPointCounts =
+ Objects.nonNull(activeQueryParser)
+ ? queryFallbackPointCountsByDevice.computeIfAbsent(device, key ->
new LinkedHashMap<>())
+ : Collections.emptyMap();
+ for (int column = 0; column < measurements.size(); column++) {
+ final String measurement = measurements.get(column);
+ for (int row = 0; row < tablet.getRowSize(); row++) {
+ if (!tablet.isNull(row, column)) {
+ emittedTimestamps.merge(measurement, tablet.getTimestamp(row),
Math::max);
+ emittedPointCounts.merge(measurement, 1L, Long::sum);
+ if (Objects.nonNull(activeQueryParser)) {
+ queryFallbackPointCounts.merge(measurement, 1L, Long::sum);
+ }
+ }
+ }
}
}
@@ -471,6 +950,7 @@ class LoadTreeTsFileTabletIterator
}
private boolean finishIteration() {
+ verifyQueryFallbackMeasurements();
close();
if (Objects.nonNull(unrecoverableQueryFailure)) {
throw unrecoverableQueryFailure;
@@ -478,6 +958,36 @@ class LoadTreeTsFileTabletIterator
return false;
}
+ private void verifyQueryFallbackMeasurements() {
+ if (Objects.nonNull(unrecoverableQueryFailure)) {
+ return;
+ }
+
+ for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry :
+ expectedQueryFallbackPointCountsByDevice.entrySet()) {
+ final Map<String, Long> queriedPointCounts =
+ queryFallbackPointCountsByDevice.getOrDefault(
+ deviceEntry.getKey(), Collections.emptyMap());
+ for (final Map.Entry<String, Long> measurementEntry :
deviceEntry.getValue().entrySet()) {
+ final long expectedPointCount = measurementEntry.getValue();
+ final long queriedPointCount =
+ queriedPointCounts.getOrDefault(measurementEntry.getKey(), 0L);
+ if (expectedPointCount != queriedPointCount) {
+ unrecoverableQueryFailure =
+ new IllegalStateException(
+ String.format(
+ StorageEngineMessages
+
.EXCEPTION_QUERY_FALLBACK_POINT_COUNT_MISMATCH_FOR_DEVICE_ARG_MEASUREMENT_ARG_EXPECTED_ARG_POINTS_BUT_RECOVERED_ARG_POINTS_0BEC4004,
+ deviceEntry.getKey(),
+ measurementEntry.getKey(),
+ expectedPointCount,
+ queriedPointCount));
+ return;
+ }
+ }
+ }
+ }
+
private void splitOrSkipActiveQueryTask(final Exception failure) {
final QueryTask failedTask = activeQueryTask;
closeActiveQueryParser();
@@ -507,6 +1017,30 @@ class LoadTreeTsFileTabletIterator
return IMeasurementSchema.getMeasurementNameList(tablet.getSchemas());
}
+ @FunctionalInterface
+ interface ScanParserFactory {
+ TsFileInsertionEventScanParser create(File file) throws IOException,
IllegalPathException;
+ }
+
+ @FunctionalInterface
+ interface QueryParserFactory {
+ QueryParser create(
+ File file,
+ IDeviceID device,
+ List<String> measurements,
+ long startTime,
+ long endTime,
+ boolean isWithMod)
+ throws IOException, IllegalPathException;
+ }
+
+ interface QueryParser extends AutoCloseable {
+ Iterator<Pair<Tablet, Boolean>> iterator();
+
+ @Override
+ void close();
+ }
+
private static class QueryTask {
private final IDeviceID device;
private final List<String> measurements;
@@ -524,12 +1058,6 @@ class LoadTreeTsFileTabletIterator
this.endTime = endTime;
}
- private LinkedHashMap<IDeviceID, List<String>> toDeviceMeasurementsMap() {
- final LinkedHashMap<IDeviceID, List<String>> deviceMeasurementsMap = new
LinkedHashMap<>();
- deviceMeasurementsMap.put(device, measurements);
- return deviceMeasurementsMap;
- }
-
private List<QueryTask> split(final long resumeStartTime) {
final int middle = measurements.size() / 2;
if (middle <= 0) {
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeStatementDataTypeConvertExecutionVisitorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeStatementDataTypeConvertExecutionVisitorTest.java
index 2ee8024e2f5..74be6612dfa 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeStatementDataTypeConvertExecutionVisitorTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/load/converter/LoadTreeStatementDataTypeConvertExecutionVisitorTest.java
@@ -22,17 +22,23 @@ package org.apache.iotdb.db.storageengine.load.converter;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.conf.CommonDescriptor;
import
org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException;
+import org.apache.iotdb.commons.path.MeasurementPath;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.commons.pipe.datastructure.pattern.IoTDBTreePattern;
+import org.apache.iotdb.db.i18n.StorageEngineMessages;
import
org.apache.iotdb.db.pipe.event.common.tsfile.parser.scan.TsFileInsertionEventScanParser;
import org.apache.iotdb.db.pipe.resource.PipeDataNodeResourceManager;
import org.apache.iotdb.db.queryengine.plan.statement.Statement;
import
org.apache.iotdb.db.queryengine.plan.statement.crud.InsertMultiTabletsStatement;
import
org.apache.iotdb.db.queryengine.plan.statement.crud.InsertTabletStatement;
import org.apache.iotdb.db.queryengine.plan.statement.crud.LoadTsFileStatement;
+import
org.apache.iotdb.db.storageengine.dataregion.modification.ModificationFile;
+import
org.apache.iotdb.db.storageengine.dataregion.modification.TreeDeletionEntry;
import org.apache.iotdb.db.storageengine.load.memory.LoadTsFileMemoryManager;
+import
org.apache.iotdb.db.storageengine.load.memory.LoadTsFileParserMemoryManager;
import org.apache.iotdb.rpc.TSStatusCode;
+import org.apache.tsfile.common.conf.TSFileDescriptor;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.IMetadataIndexEntry;
import org.apache.tsfile.file.MetaMarker;
@@ -46,9 +52,11 @@ import org.apache.tsfile.read.TsFileSequenceReader;
import org.apache.tsfile.read.common.Path;
import org.apache.tsfile.utils.Pair;
import org.apache.tsfile.write.TsFileWriter;
+import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl;
import org.apache.tsfile.write.record.Tablet;
import org.apache.tsfile.write.schema.IMeasurementSchema;
import org.apache.tsfile.write.schema.MeasurementSchema;
+import org.apache.tsfile.write.writer.TsFileIOWriter;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -57,13 +65,20 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public class LoadTreeStatementDataTypeConvertExecutionVisitorTest {
private static final String DEVICE_0 = "root.sg.d0";
@@ -452,6 +467,654 @@ public class
LoadTreeStatementDataTypeConvertExecutionVisitorTest {
pipeMemoryBefore,
PipeDataNodeResourceManager.memory().getUsedMemorySizeInBytes());
}
+ @Test
+ public void testRecoversMeasurementsWhenScanFinishesWithoutTablet() throws
Exception {
+ tsFile = new File("load-tree-query-fallback-empty-scan.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final TsFileInsertionEventScanParser emptyScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+
when(emptyScanParser.toTabletWithIsAligneds()).thenReturn(Collections.emptyList());
+
when(emptyScanParser.getParsedPointCounts()).thenReturn(Collections.emptyMap());
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ file -> new LoadTreeTsFileTabletIterator(file, true, ignored ->
emptyScanParser));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s0", "0=true", "1=false",
"2=true", "3=false");
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s1", "0=false", "1=true",
"2=false", "3=true");
+ Assert.assertEquals(2, loadedPointData.size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void testRecoversPartiallyScannedAlignedDeviceAtNormalEof() throws
Exception {
+ tsFile = new File("load-tree-query-fallback-partial-scan.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 0);
+ partialTablet.addValue("s0", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Collections.singletonMap("s0", 1L)));
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ file -> new LoadTreeTsFileTabletIterator(file, true, ignored ->
partialScanParser));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s0", "0=true", "1=false",
"2=true", "3=false");
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s1", "0=false", "1=true",
"2=false", "3=true");
+ Assert.assertEquals(2, loadedPointData.size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void testSplitFallbackResumesAfterAlreadyEmittedPoints() throws
Exception {
+ tsFile = new File("load-tree-query-fallback-split-full-range.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 0);
+ partialTablet.addValue("s0", 0, true);
+ partialTablet.addValue("s1", 0, false);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Map.of("s0", 1L, "s1", 1L)));
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(
+ sourceFile,
+ true,
+ ignored -> partialScanParser,
+ (queryFile, device, measurements, startTime, endTime,
isWithMod) -> {
+ if (measurements.size() > 1) {
+ return createPartialThenThrowQueryParser(
+ device.toString(), measurements, startTime);
+ }
+ return createBooleanQueryParser(
+ device.toString(), measurements.get(0), startTime,
endTime);
+ }));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s0", "0=true", "1=false",
"2=true", "3=false");
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s1", "0=false", "1=true",
"2=false", "3=true");
+ Assert.assertEquals(2, loadedPointData.size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void testIncompleteQueryFallbackFailsAndPreservesSource() throws
Exception {
+ tsFile = new File("load-tree-query-fallback-incomplete.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 0);
+ partialTablet.addValue("s0", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Collections.singletonMap("s0", 1L)));
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(
+ sourceFile,
+ true,
+ ignored -> partialScanParser,
+ (queryFile, device, measurements, startTime, endTime,
isWithMod) ->
+ createBooleanQueryParser(
+ device.toString(),
+ measurements.get(0),
+ startTime,
+ endTime,
+ measurements.get(0).equals("s0") ? 2 :
Integer.MAX_VALUE)));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.LOAD_FILE_ERROR.getStatusCode(),
status.get().getCode());
+ Assert.assertEquals(
+ String.format(
+ StorageEngineMessages
+
.EXCEPTION_QUERY_FALLBACK_POINT_COUNT_MISMATCH_FOR_DEVICE_ARG_MEASUREMENT_ARG_EXPECTED_ARG_POINTS_BUT_RECOVERED_ARG_POINTS_0BEC4004,
+ ALIGNED_DEVICE,
+ "s0",
+ 3,
+ 2),
+ status.get().getMessage());
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s0", "0=true",
"1=false", "2=true");
+ assertBooleanSeriesData(
+ loadedPointData, ALIGNED_DEVICE + ".s1", "0=false", "1=true",
"2=false", "3=true");
+ Assert.assertEquals(2, loadedPointData.size());
+ Assert.assertTrue("Incomplete fallback must preserve the source TsFile.",
tsFile.exists());
+ }
+
+ @Test
+ public void
testFailedNormalEofFallbackKeepsSourceWhenDeleteAfterLoadIsEnabled()
+ throws Exception {
+ tsFile = new File("load-tree-query-fallback-failed-keeps-source.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 2);
+ partialTablet.addValue("s0", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Collections.singletonMap("s0", 1L)));
+
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> new
TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()),
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(
+ sourceFile,
+ true,
+ ignored -> partialScanParser,
+ (queryFile, device, measurements, startTime, endTime,
isWithMod) ->
+ createThrowingQueryParser()));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.LOAD_FILE_ERROR.getStatusCode(),
status.get().getCode());
+ Assert.assertTrue("Failed fallback must preserve the source TsFile.",
tsFile.exists());
+ }
+
+ @Test
+ public void testScanParserTracksAlignedPointCounts() throws Exception {
+ tsFile = new File("load-tree-aligned-scan-point-counts.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ try (final TsFileInsertionEventScanParser parser =
+ new TsFileInsertionEventScanParser(
+ tsFile,
+ null,
+ null,
+ true,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ new IoTDBTreePattern(null), Long.MIN_VALUE, Long.MAX_VALUE,
true))) {
+ parser.toTabletWithIsAligneds().forEach(tabletWithIsAligned -> {});
+ final Map<String, Long> pointCounts =
+ parser
+ .getParsedPointCounts()
+ .get(IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE));
+ Assert.assertEquals(Long.valueOf(4), pointCounts.get("s0"));
+ Assert.assertEquals(Long.valueOf(4), pointCounts.get("s1"));
+ }
+ }
+
+ @Test
+ public void testScanParserTracksVisibleAlignedPointCountsWithMods() throws
Exception {
+ tsFile = new
File("load-tree-aligned-scan-visible-point-counts-with-mods.tsfile");
+ writeAlignedBooleanTsFileAcrossChunkGroups(tsFile);
+ try (final ModificationFile modificationFile =
+ new ModificationFile(ModificationFile.getExclusiveMods(tsFile),
false)) {
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s0"),
3, 3));
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s1"),
1, 1));
+ }
+
+ try (final TsFileInsertionEventScanParser parser =
+ new TsFileInsertionEventScanParser(
+ tsFile,
+ null,
+ null,
+ true,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ new IoTDBTreePattern(null), Long.MIN_VALUE, Long.MAX_VALUE,
true))) {
+ parser.toTabletWithIsAligneds().forEach(tabletWithIsAligned -> {});
+ final IDeviceID device =
IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE);
+ Assert.assertEquals(Long.valueOf(3),
parser.getParsedPointCounts().get(device).get("s0"));
+ Assert.assertEquals(Long.valueOf(2),
parser.getParsedPointCounts().get(device).get("s1"));
+ Assert.assertEquals(Long.valueOf(2),
parser.getExpectedPointCounts().get(device).get("s0"));
+ Assert.assertEquals(Long.valueOf(1),
parser.getExpectedPointCounts().get(device).get("s1"));
+ }
+ }
+
+ @Test
+ public void testCompleteModifiedAlignedScanDoesNotReplayDeletedChunks()
throws Exception {
+ tsFile = new File("load-tree-aligned-scan-point-counts-with-mods.tsfile");
+ writeAlignedBooleanTsFileAcrossChunkGroups(tsFile);
+ try (final ModificationFile modificationFile =
+ new ModificationFile(ModificationFile.getExclusiveMods(tsFile),
false)) {
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s0"),
3, 3));
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s1"),
1, 1));
+ }
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(
+ sourceFile,
+ true,
+ file ->
+ new TsFileInsertionEventScanParser(
+ file,
+ null,
+ null,
+ true,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ new IoTDBTreePattern(null), Long.MIN_VALUE,
Long.MAX_VALUE, true)),
+ (file, device, measurements, startTime, endTime,
isWithMod) ->
+ createThrowingQueryParser()));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s0", "0=true",
"1=false");
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s1",
"2=false");
+ assertBooleanSeriesData(loadedPointData, "root.sg.intermediate.other",
"10=true");
+ Assert.assertEquals(3, loadedPointData.size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void
testModifiedAlignedScanPreservesValueChunkOrderAfterSkippingDeletedChunk()
+ throws Exception {
+ tsFile = new File("load-tree-aligned-scan-skipped-value-chunk.tsfile");
+ writeAlignedBooleanTsFileWithMultipleChunksInGroup(tsFile);
+ try (final ModificationFile modificationFile =
+ new ModificationFile(ModificationFile.getExclusiveMods(tsFile),
false)) {
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s0"),
0, 0));
+ }
+
+ final List<Long> visibleTimestamps = new ArrayList<>();
+ try (final TsFileInsertionEventScanParser parser =
+ new TsFileInsertionEventScanParser(
+ tsFile,
+ null,
+ null,
+ true,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ new IoTDBTreePattern(null), Long.MIN_VALUE, Long.MAX_VALUE,
true))) {
+ for (final Pair<Tablet, Boolean> tabletWithIsAligned :
parser.toTabletWithIsAligneds()) {
+ final Tablet tablet = tabletWithIsAligned.getLeft();
+ for (int column = 0; column < tablet.getSchemas().size(); column++) {
+ if
(!"s0".equals(tablet.getSchemas().get(column).getMeasurementName())) {
+ continue;
+ }
+ for (int row = 0; row < tablet.getRowSize(); row++) {
+ if (!tablet.isNull(row, column)) {
+ visibleTimestamps.add(tablet.getTimestamp(row));
+ }
+ }
+ }
+ }
+ }
+
+ Assert.assertEquals(Collections.singletonList(1L), visibleTimestamps);
+ }
+
+ @Test
+ public void
testModifiedAlignedScanVerifiesPointCountsAboveLongCacheBoundary() throws
Exception {
+ tsFile =
File.createTempFile("load-tree-aligned-scan-large-point-counts-with-mods-",
".tsfile");
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.INT64, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.INT64, TSEncoding.PLAIN));
+ try (final TsFileWriter writer = new TsFileWriter(tsFile)) {
+ writer.registerAlignedTimeseries(new PartialPath(ALIGNED_DEVICE),
schemas);
+ writeRows(writer, schemas, ALIGNED_DEVICE, 0, 200, true);
+ }
+ try (final ModificationFile modificationFile =
+ new ModificationFile(ModificationFile.getExclusiveMods(tsFile),
false)) {
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s0"),
0, 0));
+ }
+
+ final Map<String, Map<Long, Long>> loadedPoints = new HashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedLongPoints(statement, loadedPoints);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ });
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ final Map<Long, Long> modifiedSeries = loadedPoints.get(ALIGNED_DEVICE +
".s0");
+ Assert.assertEquals(199, modifiedSeries.size());
+ Assert.assertFalse(modifiedSeries.containsKey(0L));
+ Assert.assertEquals(200, loadedPoints.get(ALIGNED_DEVICE + ".s1").size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void testModifiedAlignedQueryFallbackUsesVisiblePointCounts() throws
Exception {
+ tsFile = new File("load-tree-query-fallback-aligned-mods.tsfile");
+ final long secondGroupOffset =
writeAlignedBooleanTsFileAcrossChunkGroups(tsFile);
+ try (final ModificationFile modificationFile =
+ new ModificationFile(ModificationFile.getExclusiveMods(tsFile),
false)) {
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s0"),
1, 1));
+ modificationFile.write(
+ new TreeDeletionEntry(new MeasurementPath(ALIGNED_DEVICE + ".s1"),
1, 1));
+ }
+ corruptGroupMarker(tsFile, secondGroupOffset);
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ });
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s0", "0=true",
"3=true");
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s1",
"2=false");
+ assertBooleanSeriesData(loadedPointData, "root.sg.intermediate.other",
"10=true");
+ Assert.assertEquals(3, loadedPointData.size());
+ Assert.assertFalse("Successfully loaded TsFile should be deleted.",
tsFile.exists());
+ }
+
+ @Test
+ public void testEofFallbackFailsWhenNoPointsFollowLastEmittedTimestamp()
throws Exception {
+ tsFile = new
File("load-tree-query-fallback-eof-no-resumable-points.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 3);
+ partialTablet.addValue("s0", 0, false);
+ partialTablet.addValue("s1", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Map.of("s0", 1L, "s1", 1L)));
+
+ final List<Long> queryStartTimes = new ArrayList<>();
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(
+ sourceFile,
+ true,
+ ignored -> partialScanParser,
+ (queryFile, device, measurements, startTime, endTime,
isWithMod) -> {
+ queryStartTimes.add(startTime);
+ return createEmptyQueryParser();
+ }));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.LOAD_FILE_ERROR.getStatusCode(),
status.get().getCode());
+ Assert.assertEquals(Collections.singletonList(4L), queryStartTimes);
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s0",
"3=false");
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s1", "3=true");
+ Assert.assertTrue("Failed boundary fallback must preserve the source
TsFile.", tsFile.exists());
+ }
+
+ @Test
+ public void testEofFallbackFailsWhenDuplicateTimestampWouldBeSkipped()
throws Exception {
+ tsFile = new File("load-tree-query-fallback-duplicate-timestamp.tsfile");
+ writeAlignedBooleanTsFileWithDuplicateTimestamp(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 0);
+ partialTablet.addValue("s0", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ when(partialScanParser.toTabletWithIsAligneds())
+ .thenReturn(Collections.singletonList(new Pair<>(partialTablet,
true)));
+ when(partialScanParser.getParsedPointCounts())
+ .thenReturn(
+ Collections.singletonMap(
+ IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE),
+ Collections.singletonMap("s0", 1L)));
+
+ final Map<String, List<String>> loadedPointData = new LinkedHashMap<>();
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> {
+ collectLoadedPointData(statement, loadedPointData);
+ return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
+ },
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(sourceFile, true, ignored ->
partialScanParser));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.LOAD_FILE_ERROR.getStatusCode(),
status.get().getCode());
+ assertBooleanSeriesData(loadedPointData, ALIGNED_DEVICE + ".s0", "0=true",
"1=true");
+ Assert.assertTrue(
+ "Incomplete duplicate-timestamp fallback must preserve the source
TsFile.",
+ tsFile.exists());
+ }
+
+ @Test
+ public void
testCorruptionFallbackFailsWhenNoPointsFollowLastEmittedTimestamp() throws
Exception {
+ tsFile = new
File("load-tree-query-fallback-corrupted-no-resumable-points.tsfile");
+ writeAlignedBooleanTsFile(tsFile);
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final Tablet partialTablet = new Tablet(ALIGNED_DEVICE, schemas, 1);
+ partialTablet.addTimestamp(0, 3);
+ partialTablet.addValue("s0", 0, false);
+ partialTablet.addValue("s1", 0, true);
+
+ final TsFileInsertionEventScanParser partialScanParser =
+ mock(TsFileInsertionEventScanParser.class);
+ final Iterator<Pair<Tablet, Boolean>> partialScanIterator =
+ new Iterator<Pair<Tablet, Boolean>>() {
+ private boolean tabletReturned;
+
+ @Override
+ public boolean hasNext() {
+ if (!tabletReturned) {
+ return true;
+ }
+ throw new IllegalStateException("Forced scan failure after the
last timestamp");
+ }
+
+ @Override
+ public Pair<Tablet, Boolean> next() {
+ if (tabletReturned) {
+ throw new java.util.NoSuchElementException();
+ }
+ tabletReturned = true;
+ return new Pair<>(partialTablet, true);
+ }
+ };
+ when(partialScanParser.toTabletWithIsAligneds()).thenReturn(() ->
partialScanIterator);
+
+ final LoadTreeStatementDataTypeConvertExecutionVisitor visitor =
+ new LoadTreeStatementDataTypeConvertExecutionVisitor(
+ statement -> new
TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()),
+ sourceFile ->
+ new LoadTreeTsFileTabletIterator(sourceFile, true, ignored ->
partialScanParser));
+
+ final Optional<TSStatus> status =
+ visitor.visitLoadFile(
+
LoadTsFileStatement.createUnchecked(tsFile.getAbsolutePath()).setDeleteAfterLoad(true),
+ null);
+
+ Assert.assertTrue(status.isPresent());
+ Assert.assertEquals(TSStatusCode.LOAD_FILE_ERROR.getStatusCode(),
status.get().getCode());
+ Assert.assertTrue(
+ "Incomplete corruption fallback must preserve the source TsFile.",
tsFile.exists());
+ }
+
+ @Test
+ public void testScanParserCountsAlignedPointsAcrossChunkGroupsAndNulls()
throws Exception {
+ tsFile = new
File("load-tree-aligned-scan-point-counts-multiple-chunk-groups.tsfile");
+ writeAlignedBooleanTsFileAcrossChunkGroups(tsFile);
+
+ try (final TsFileInsertionEventScanParser parser =
+ new TsFileInsertionEventScanParser(
+ tsFile,
+ null,
+ null,
+ true,
+ LoadTsFileParserMemoryManager.getInstance(),
+ new TsFileInsertionEventScanParser.ScanOptions(
+ new IoTDBTreePattern(null), Long.MIN_VALUE, Long.MAX_VALUE,
true))) {
+ parser.toTabletWithIsAligneds().forEach(tabletWithIsAligned -> {});
+ final Map<String, Long> pointCounts =
+ parser
+ .getParsedPointCounts()
+ .get(IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE));
+ Assert.assertEquals(Long.valueOf(3), pointCounts.get("s0"));
+ Assert.assertEquals(Long.valueOf(2), pointCounts.get("s1"));
+ }
+ }
+
@Test
public void testFallbackToQueryWhenFirstNonAlignedDeviceIsCorrupted() throws
Exception {
tsFile = new
File("load-tree-query-fallback-corrupted-first-non-aligned-device.tsfile");
@@ -590,6 +1253,241 @@ public class
LoadTreeStatementDataTypeConvertExecutionVisitorTest {
return secondGroupMarkerOffset;
}
+ private void writeAlignedBooleanTsFile(final File file) throws Exception {
+ if (file.exists()) {
+ Assert.assertTrue(file.delete());
+ }
+
+ final List<IMeasurementSchema> schemaList =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ try (final TsFileWriter writer = new TsFileWriter(file)) {
+ writer.registerAlignedTimeseries(new PartialPath(ALIGNED_DEVICE),
schemaList);
+ final Tablet tablet = new Tablet(ALIGNED_DEVICE, schemaList, 4);
+ for (int row = 0; row < 4; ++row) {
+ tablet.addTimestamp(row, row);
+ tablet.addValue("s0", row, row % 2 == 0);
+ tablet.addValue("s1", row, row % 2 != 0);
+ }
+ writer.writeAligned(tablet);
+ }
+ }
+
+ private void writeAlignedBooleanTsFileWithMultipleChunksInGroup(final File
file)
+ throws Exception {
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ try (final TsFileIOWriter writer = new TsFileIOWriter(file)) {
+
writer.startChunkGroup(IDeviceID.Factory.DEFAULT_FACTORY.create(ALIGNED_DEVICE));
+ for (int timestamp = 0; timestamp < 2; timestamp++) {
+ final AlignedChunkWriterImpl chunkWriter = new
AlignedChunkWriterImpl(schemas);
+ chunkWriter.getTimeChunkWriter().write(timestamp);
+ chunkWriter.getValueChunkWriterByIndex(0).write(timestamp, timestamp
== 0, false);
+ chunkWriter.getValueChunkWriterByIndex(1).write(timestamp, timestamp
!= 0, false);
+ chunkWriter.writeToFileWriter(writer);
+ }
+ writer.endChunkGroup();
+ writer.endFile();
+ }
+ }
+
+ private void writeAlignedBooleanTsFileWithDuplicateTimestamp(final File
file) throws Exception {
+ if (file.exists()) {
+ Assert.assertTrue(file.delete());
+ }
+
+ final List<IMeasurementSchema> schemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final boolean previousSetting =
+
TSFileDescriptor.getInstance().getConfig().isAllowNonDecreasingTimestamps();
+ try {
+
TSFileDescriptor.getInstance().getConfig().setAllowNonDecreasingTimestamps(true);
+ try (final TsFileWriter writer = new TsFileWriter(file)) {
+ writer.registerAlignedTimeseries(new PartialPath(ALIGNED_DEVICE),
schemas);
+ final Tablet tablet = new Tablet(ALIGNED_DEVICE, schemas, 3);
+ tablet.addTimestamp(0, 0);
+ tablet.addTimestamp(1, 0);
+ tablet.addTimestamp(2, 1);
+ tablet.addValue("s0", 0, true);
+ tablet.addValue("s0", 1, false);
+ tablet.addValue("s0", 2, true);
+ tablet.addValue("s1", 2, false);
+ writer.writeAligned(tablet);
+ }
+ } finally {
+
TSFileDescriptor.getInstance().getConfig().setAllowNonDecreasingTimestamps(previousSetting);
+ }
+ }
+
+ private long writeAlignedBooleanTsFileAcrossChunkGroups(final File file)
throws Exception {
+ if (file.exists()) {
+ Assert.assertTrue(file.delete());
+ }
+
+ final List<IMeasurementSchema> alignedSchemas =
+ Arrays.asList(
+ new MeasurementSchema("s0", TSDataType.BOOLEAN, TSEncoding.PLAIN),
+ new MeasurementSchema("s1", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ final List<IMeasurementSchema> otherSchemas =
+ Collections.singletonList(new MeasurementSchema("other",
TSDataType.BOOLEAN));
+ final String otherDevice = "root.sg.intermediate";
+ try (final TsFileWriter writer = new TsFileWriter(file)) {
+ writer.registerAlignedTimeseries(new PartialPath(ALIGNED_DEVICE),
alignedSchemas);
+ writer.registerTimeseries(new Path(otherDevice), otherSchemas);
+
+ final Tablet firstAlignedTablet = new Tablet(ALIGNED_DEVICE,
alignedSchemas, 2);
+ firstAlignedTablet.addTimestamp(0, 0);
+ firstAlignedTablet.addValue("s0", 0, true);
+ firstAlignedTablet.addTimestamp(1, 1);
+ firstAlignedTablet.addValue("s0", 1, false);
+ firstAlignedTablet.addValue("s1", 1, true);
+ writer.writeAligned(firstAlignedTablet);
+
+ final Tablet otherTablet = new Tablet(otherDevice, otherSchemas, 1);
+ otherTablet.addTimestamp(0, 10);
+ otherTablet.addValue("other", 0, true);
+ writer.writeTree(otherTablet);
+ writer.flush();
+ final long secondGroupOffset = writer.getIOWriter().getPos();
+
+ final Tablet secondAlignedTablet = new Tablet(ALIGNED_DEVICE,
alignedSchemas, 2);
+ secondAlignedTablet.addTimestamp(0, 2);
+ secondAlignedTablet.addValue("s1", 0, false);
+ secondAlignedTablet.addTimestamp(1, 3);
+ secondAlignedTablet.addValue("s0", 1, true);
+ writer.writeAligned(secondAlignedTablet);
+ return secondGroupOffset;
+ }
+ }
+
+ private static LoadTreeTsFileTabletIterator.QueryParser
createThrowingQueryParser() {
+ return new LoadTreeTsFileTabletIterator.QueryParser() {
+ @Override
+ public Iterator<Pair<Tablet, Boolean>> iterator() {
+ return new Iterator<Pair<Tablet, Boolean>>() {
+ @Override
+ public boolean hasNext() {
+ throw new IllegalStateException("Forced query fallback failure");
+ }
+
+ @Override
+ public Pair<Tablet, Boolean> next() {
+ throw new java.util.NoSuchElementException();
+ }
+ };
+ }
+
+ @Override
+ public void close() {}
+ };
+ }
+
+ private static LoadTreeTsFileTabletIterator.QueryParser
createEmptyQueryParser() {
+ return new LoadTreeTsFileTabletIterator.QueryParser() {
+ @Override
+ public Iterator<Pair<Tablet, Boolean>> iterator() {
+ return Collections.emptyIterator();
+ }
+
+ @Override
+ public void close() {}
+ };
+ }
+
+ private static LoadTreeTsFileTabletIterator.QueryParser
createPartialThenThrowQueryParser(
+ final String device, final List<String> measurements, final long
timestamp) {
+ final List<IMeasurementSchema> schemas = new ArrayList<>();
+ for (final String measurement : measurements) {
+ schemas.add(new MeasurementSchema(measurement, TSDataType.BOOLEAN,
TSEncoding.PLAIN));
+ }
+ final Tablet tablet = new Tablet(device, schemas, 1);
+ tablet.addTimestamp(0, timestamp);
+ for (final String measurement : measurements) {
+ tablet.addValue(measurement, 0, measurement.equals("s0") == (timestamp %
2 == 0));
+ }
+
+ return new LoadTreeTsFileTabletIterator.QueryParser() {
+ @Override
+ public Iterator<Pair<Tablet, Boolean>> iterator() {
+ return new Iterator<Pair<Tablet, Boolean>>() {
+ private int state;
+
+ @Override
+ public boolean hasNext() {
+ if (state == 0) {
+ return true;
+ }
+ if (state == 1) {
+ state++;
+ throw new IllegalStateException("Forced partial query fallback
failure");
+ }
+ return false;
+ }
+
+ @Override
+ public Pair<Tablet, Boolean> next() {
+ if (state != 0) {
+ throw new java.util.NoSuchElementException();
+ }
+ state++;
+ return new Pair<>(tablet, true);
+ }
+ };
+ }
+
+ @Override
+ public void close() {}
+ };
+ }
+
+ private static LoadTreeTsFileTabletIterator.QueryParser
createBooleanQueryParser(
+ final String device, final String measurement, final long startTime,
final long endTime) {
+ return createBooleanQueryParser(device, measurement, startTime, endTime,
Integer.MAX_VALUE);
+ }
+
+ private static LoadTreeTsFileTabletIterator.QueryParser
createBooleanQueryParser(
+ final String device,
+ final String measurement,
+ final long startTime,
+ final long endTime,
+ final int maxPointCount) {
+ final List<IMeasurementSchema> schemas =
+ Collections.singletonList(
+ new MeasurementSchema(measurement, TSDataType.BOOLEAN,
TSEncoding.PLAIN));
+ final Tablet tablet = new Tablet(device, schemas, 4);
+ int row = 0;
+ for (int timestamp = 0; timestamp < 4; timestamp++) {
+ if (timestamp < startTime || timestamp > endTime) {
+ continue;
+ }
+ if (row >= maxPointCount) {
+ break;
+ }
+ tablet.addTimestamp(row, timestamp);
+ tablet.addValue(measurement, row, measurement.equals("s0") == (timestamp
% 2 == 0));
+ row++;
+ }
+
+ final Iterator<Pair<Tablet, Boolean>> tabletIterator =
+ row == 0
+ ? Collections.emptyIterator()
+ : Collections.singletonList(new Pair<>(tablet, true)).iterator();
+ return new LoadTreeTsFileTabletIterator.QueryParser() {
+ @Override
+ public Iterator<Pair<Tablet, Boolean>> iterator() {
+ return tabletIterator;
+ }
+
+ @Override
+ public void close() {}
+ };
+ }
+
private void writeWideAlignedTsFile(
final File file, final String device, final int measurementCount) throws
Exception {
if (file.exists()) {
@@ -719,6 +1617,36 @@ public class
LoadTreeStatementDataTypeConvertExecutionVisitorTest {
}
}
+ private void collectLoadedPointData(
+ final Statement statement, final Map<String, List<String>>
pointDataByTimeseries) {
+ Assert.assertTrue(statement instanceof InsertMultiTabletsStatement);
+ for (final InsertTabletStatement tablet :
+ ((InsertMultiTabletsStatement)
statement).getInsertTabletStatementList()) {
+ for (int row = 0; row < tablet.getRowCount(); row++) {
+ for (int column = 0; column < tablet.getMeasurements().length;
column++) {
+ final String measurement = tablet.getMeasurements()[column];
+ if (measurement != null && !tablet.isNull(row, column)) {
+ Assert.assertEquals(TSDataType.BOOLEAN,
tablet.getDataType(column));
+ pointDataByTimeseries
+ .computeIfAbsent(
+ tablet.getDevicePath().getFullPath() + "." + measurement,
+ key -> new ArrayList<>())
+ .add(tablet.getTimes()[row] + "=" + ((boolean[])
tablet.getColumns()[column])[row]);
+ }
+ }
+ }
+ }
+ }
+
+ private static void assertBooleanSeriesData(
+ final Map<String, List<String>> pointDataByTimeseries,
+ final String timeseries,
+ final String... expectedPointData) {
+ Assert.assertEquals(
+ Arrays.asList(expectedPointData),
+ pointDataByTimeseries.getOrDefault(timeseries,
Collections.emptyList()));
+ }
+
private void collectLoadedPointsByTimeseries(
final Statement statement, final Map<String, Integer>
pointCountByTimeseries) {
Assert.assertTrue(statement instanceof InsertMultiTabletsStatement);