This is an automated email from the ASF dual-hosted git repository. Caideyipi pushed a commit to branch codex/fix-aligned-load-conflict in repository https://gitbox.apache.org/repos/asf/iotdb.git
commit f40292393adf3256fd38a86619fb213742031ca1 Author: Caideyipi <[email protected]> AuthorDate: Mon Nov 23 18:59:08 2026 +0800 Fix aligned TsFile LOAD data loss --- .../org/apache/iotdb/db/it/IoTDBLoadTsFileIT.java | 137 ++++ .../IoTDBPipeTypeConversionSemanticIT.java | 118 +++- .../scan/TsFileInsertionEventScanParser.java | 97 +++ .../converter/LoadTreeTsFileTabletIterator.java | 356 +++++++--- ...atementDataTypeConvertExecutionVisitorTest.java | 757 +++++++++++++++++++++ 5 files changed, 1372 insertions(+), 93 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/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..cab635f699d 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 @@ -94,6 +94,8 @@ public class TsFileInsertionEventScanParser extends TsFileInsertionEventParser { 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 IChunkReader chunkReader; private BatchData data; @@ -165,6 +167,37 @@ public class TsFileInsertionEventScanParser extends TsFileInsertionEventParser { final boolean isWithMod, final TsFileInsertionEventParserMemoryManager memoryManager) throws IOException, IllegalPathException { + this( + pipeName, + creationTime, + tsFile, + pattern, + startTime, + endTime, + pipeTaskMeta, + entity, + skipIfNoPrivileges, + sourceEvent, + isWithMod, + memoryManager, + false); + } + + private TsFileInsertionEventScanParser( + final String pipeName, + final long creationTime, + final File tsFile, + final TreePattern pattern, + final long startTime, + final long endTime, + final PipeTaskMeta pipeTaskMeta, + final IAuditEntity entity, + final boolean skipIfNoPrivileges, + final PipeInsertionEvent sourceEvent, + final boolean isWithMod, + final TsFileInsertionEventParserMemoryManager memoryManager, + final boolean trackPointCounts) + throws IOException, IllegalPathException { super( tsFile, pipeName, @@ -180,6 +213,7 @@ public class TsFileInsertionEventScanParser extends TsFileInsertionEventParser { isWithMod, memoryManager); + this.trackPointCounts = trackPointCounts; this.startTime = startTime; this.endTime = endTime; filter = Objects.nonNull(timeFilterExpression) ? timeFilterExpression.getFilter() : null; @@ -213,6 +247,33 @@ public class TsFileInsertionEventScanParser extends TsFileInsertionEventParser { } } + public TsFileInsertionEventScanParser( + final File tsFile, + final TreePattern pattern, + final long startTime, + final long endTime, + final PipeTaskMeta pipeTaskMeta, + final PipeInsertionEvent sourceEvent, + final boolean isWithMod, + final TsFileInsertionEventParserMemoryManager memoryManager, + final boolean trackPointCounts) + throws IOException, IllegalPathException { + this( + null, + 0, + tsFile, + pattern, + startTime, + endTime, + pipeTaskMeta, + null, + false, + sourceEvent, + isWithMod, + memoryManager, + trackPointCounts); + } + public TsFileInsertionEventScanParser( final File tsFile, final TreePattern pattern, @@ -412,6 +473,13 @@ 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; + } + private Tablet getNextTablet() { Tablet tablet = null; boolean tabletMemoryReserved = false; @@ -453,6 +521,7 @@ public class TsFileInsertionEventScanParser extends TsFileInsertionEventParser { final int rowIndex = tablet.getRowSize(); + recordParsedPointCounts(data); if (putValueToColumns(data, tablet, rowIndex)) { PipeTabletUtils.putTimestamp(tablet, rowIndex, data.currentTime()); } @@ -623,6 +692,33 @@ 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 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 moveToNextChunkReader() throws IOException, IllegalStateException, IllegalPathException { releaseChunkReader(); @@ -853,6 +949,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..a77eb106d27 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 @@ -23,12 +23,14 @@ import org.apache.iotdb.commons.exception.IllegalPathException; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeOutOfMemoryCriticalException; 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.storageengine.dataregion.modification.ModificationFile; import org.apache.iotdb.db.storageengine.load.memory.LoadTsFileParserMemoryManager; import org.apache.iotdb.pipe.api.event.dml.insertion.TabletInsertionEvent; @@ -54,14 +56,14 @@ import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; -import java.util.stream.Collectors; 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 +85,110 @@ 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, + LOAD_TREE_PATTERN, + Long.MIN_VALUE, + Long.MAX_VALUE, + null, + null, + isWithMod, + LoadTsFileParserMemoryManager.getInstance(), + 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 +256,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 +273,40 @@ 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(); closeScanParser(); + try { + enqueueQueryTasksForUnemittedData(parsedPointCounts); + } 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) throws IOException { + if (fallbackTriggered) { + return; + } + + final ArrayDeque<QueryTask> queryTasks = buildQueryTasks(parsedPointCounts); + if (!queryTasks.isEmpty()) { + fallbackTriggered = true; + pendingQueryTasks.addAll(queryTasks); + } + } + private boolean recoverFromIteratorFailure(final Exception e) { if (shouldRethrow(e)) { return false; @@ -233,7 +338,7 @@ class LoadTreeTsFileTabletIterator closeScanParser(); try { - pendingQueryTasks.addAll(buildQueryTasks()); + pendingQueryTasks.addAll(buildQueryTasks(emittedPointCountsByDevice)); } catch (final Exception queryInitException) { LOGGER.warn( StorageEngineMessages @@ -252,26 +357,11 @@ 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) 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); - } - - return tasks; - } - - private LinkedHashMap<IDeviceID, List<String>> readDeviceMeasurementsInOrder() - throws IOException { - final LinkedHashMap<IDeviceID, List<String>> deviceMeasurementsMap = new LinkedHashMap<>(); + final boolean hasModifications = hasModifications(); + final Map<IDeviceID, Map<String, Long>> expectedPointCountsByDevice = 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 +371,76 @@ 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; + } + + expectedPointCountsByDevice + .computeIfAbsent(device, key -> new LinkedHashMap<>()) + .merge(measurement, (long) metadata.getStatistics().getCount(), Long::sum); + } + } + } + } + + for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry : + expectedPointCountsByDevice.entrySet()) { + final Map<String, Long> completedPointCounts = + completedPointCountsByDevice.getOrDefault(deviceEntry.getKey(), Collections.emptyMap()); + final List<String> fallbackMeasurements = new ArrayList<>(); + final Map<String, Long> fallbackPointCounts = new LinkedHashMap<>(); + for (final Map.Entry<String, Long> measurementEntry : deviceEntry.getValue().entrySet()) { + final long completedPointCount = + completedPointCounts.getOrDefault(measurementEntry.getKey(), 0L); + if (completedPointCount > measurementEntry.getValue()) { + throw new IOException( + StorageEngineMessages + .EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3); + } + if (completedPointCount < measurementEntry.getValue()) { + if (hasModifications) { + throw new IOException( + StorageEngineMessages + .EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3); + } + fallbackMeasurements.add(measurementEntry.getKey()); + fallbackPointCounts.put( + measurementEntry.getKey(), measurementEntry.getValue() - completedPointCount); + } + } + if (fallbackMeasurements.isEmpty()) { + continue; + } + + expectedQueryFallbackPointCountsByDevice.put(deviceEntry.getKey(), fallbackPointCounts); + addQueryTasks( + tasks, deviceEntry.getKey(), fallbackMeasurements, Long.MIN_VALUE, Long.MAX_VALUE); + } + + for (final Map.Entry<IDeviceID, Map<String, Long>> deviceEntry : + completedPointCountsByDevice.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; + return tasks; + } + + private boolean hasModifications() throws IOException { + if (hasModifications == null) { + hasModifications = isWithMod && !ModificationFile.readAllModifications(file, true).isEmpty(); + } + return hasModifications; } private void addQueryTasks( @@ -342,39 +481,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 +520,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 +600,7 @@ class LoadTreeTsFileTabletIterator } private boolean finishIteration() { + verifyQueryFallbackMeasurements(); close(); if (Objects.nonNull(unrecoverableQueryFailure)) { throw unrecoverableQueryFailure; @@ -478,6 +608,30 @@ 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()) { + if (!Objects.equals( + measurementEntry.getValue(), + queriedPointCounts.getOrDefault(measurementEntry.getKey(), 0L))) { + unrecoverableQueryFailure = + new IllegalStateException( + StorageEngineMessages + .EXCEPTION_FAILED_TO_ITERATE_TABLETS_WHILE_LOADING_TSFILE_4E6289F3); + return; + } + } + } + } + private void splitOrSkipActiveQueryTask(final Exception failure) { final QueryTask failedTask = activeQueryTask; closeActiveQueryParser(); @@ -507,6 +661,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 +702,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..eaf7f98df82 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,6 +22,7 @@ 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.pipe.event.common.tsfile.parser.scan.TsFileInsertionEventScanParser; @@ -30,9 +31,13 @@ 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; @@ -57,13 +62,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 +464,509 @@ 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()); + 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, + new IoTDBTreePattern(null), + Long.MIN_VALUE, + Long.MAX_VALUE, + null, + null, + true, + LoadTsFileParserMemoryManager.getInstance(), + 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 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, + new IoTDBTreePattern(null), + Long.MIN_VALUE, + Long.MAX_VALUE, + null, + null, + true, + LoadTsFileParserMemoryManager.getInstance(), + 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 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, + new IoTDBTreePattern(null), + Long.MIN_VALUE, + Long.MAX_VALUE, + null, + null, + true, + LoadTsFileParserMemoryManager.getInstance(), + 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 +1105,218 @@ 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 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 void 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); + + 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); + } + } + + 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 +1446,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);
