diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/query/IoTDBSeriesScanDefectIT.java b/integration-test/src/test/java/org/apache/iotdb/db/it/query/IoTDBSeriesScanDefectIT.java new file mode 100644 index 0000000000000..fa25602218700 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/query/IoTDBSeriesScanDefectIT.java @@ -0,0 +1,445 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.it.query; + +import org.apache.iotdb.isession.ISession; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.env.cluster.config.MppCommonConfig; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.ClusterIT; +import org.apache.iotdb.itbase.category.LocalStandaloneIT; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; + +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.write.record.Tablet; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.apache.iotdb.db.it.utils.TestUtils.executeNonQuery; +import static org.apache.iotdb.db.it.utils.TestUtils.prepareData; +import static org.apache.iotdb.db.it.utils.TestUtils.resultSetEqualTest; + +/** + * End-to-end regression ITs reproducing the 8 production-reachable scan defects (D1, D3, D4, D5, + * D7, D9, D10, D11). Each test asserts the correct SQL result. + */ +@RunWith(IoTDBTestRunner.class) +@Category({LocalStandaloneIT.class, ClusterIT.class}) +public class IoTDBSeriesScanDefectIT { + + private static final int BLOCKER_ROW_COUNT = 3_000; + private static final int BLOCKER_STRING_LENGTH = 256; + + @BeforeClass + public static void setUp() { + EnvFactory.getEnv() + .getConfig() + .getCommonConfig() + .setEnableSeqSpaceCompaction(false) + .setEnableUnseqSpaceCompaction(false) + .setEnableCrossSpaceCompaction(false) + .setMaxNumberOfPointsInPage(3) + .setDataRegionGroupExtensionPolicy("CUSTOM") + .setDefaultDataRegionGroupNumPerDatabase(1); + if (EnvFactory.getEnv().getConfig().getDataNodeCommonConfig() instanceof MppCommonConfig) { + Properties properties = new Properties(); + properties.setProperty("flush_thread_count", "1"); + ((MppCommonConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig()) + .updateProperties(properties); + } + EnvFactory.getEnv().initClusterEnvironment(); + } + + @AfterClass + public static void tearDown() { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + /** + * D1a: Value-column deletion applied to a flushing unseq memtable must take effect when that + * memtable is merged with an overlapping closed seq file via PriorityMergeReader. + */ + @Test + public void testD1aValueDeletionOfFlushingMemoryTableIsAppliedWhenMerged() throws Exception { + prepareData( + new String[] { + "CREATE DATABASE root.d1a", + "CREATE ALIGNED TIMESERIES root.d1a.d1(s0 INT64, s1 INT64)", + "CREATE TIMESERIES root.d1a.blocker.s0 WITH DATATYPE=TEXT, ENCODING=PLAIN, COMPRESSOR=LZMA2", + // Closed seq file [2, 3]; s1 keeps the file alive after s0 is deleted on [1, 2] + "INSERT INTO root.d1a.d1(time, s0, s1) ALIGNED VALUES (2, 200, 99), (3, 300, 300)", + "FLUSH root.d1a", + // Unseq memtable [1, 2] overlapping closed seq file at timestamp 2 + "INSERT INTO root.d1a.d1(time, s0, s1) ALIGNED VALUES (1, 10, 1), (2, 20, 2)" + }); + // Populate seq memtable on blocker so FLUSH root.d1a TRUE occupies the sole flush thread + insertBlockerData("root.d1a.blocker", 1, BLOCKER_ROW_COUNT); + + runDeleteAndQueryWhileFlushing( + "FLUSH root.d1a TRUE", + "FLUSH root.d1a FALSE", + "DELETE FROM root.d1a.d1.s0 WHERE time >= 1 AND time <= 2", + "SELECT s0, s1 FROM root.d1a.d1 WHERE time <= 2", + "Time,root.d1a.d1.s0,root.d1a.d1.s1,", + new String[] {"1,null,1,", "2,null,2,"}); + } + + /** + * D1b: Value-column deletion applied to a flushing memtable containing two non-overlapping sorted + * TVLists (OrderedMultiAlignedTVListIterator) must take effect. + */ + @Test + public void testD1bValueDeletionOfMemoryTableIsAppliedWithTwoTVLists() throws Exception { + prepareData( + new String[] { + "CREATE DATABASE root.d1b", + "CREATE ALIGNED TIMESERIES root.d1b.d1(s0 INT64, s1 INT64)", + "CREATE TIMESERIES root.d1b.blocker.s0 WITH DATATYPE=TEXT, ENCODING=PLAIN, COMPRESSOR=LZMA2", + // Seed blocker seq file at high timestamp so the large blocker write lands in UNSEQ + "INSERT INTO root.d1b.blocker(time, s0) VALUES (1000000, 'seed')", + "FLUSH root.d1b" + }); + // Populate unseq memtable on blocker before lowering tvlist_sort_threshold + insertBlockerData("root.d1b.blocker", 1, BLOCKER_ROW_COUNT); + + try { + executeSql("SET CONFIGURATION \"tvlist_sort_threshold\"=\"1\""); + // Two separate inserts force two non-overlapping sorted TVLists in d1's seq memtable + prepareData( + new String[] { + "INSERT INTO root.d1b.d1(time, s0, s1) ALIGNED VALUES (1, 10, 1)", + "INSERT INTO root.d1b.d1(time, s0, s1) ALIGNED VALUES (2, 20, 2)" + }); + executeSql("SET CONFIGURATION \"tvlist_sort_threshold\"=\"0\""); + + runDeleteAndQueryWhileFlushing( + "FLUSH root.d1b FALSE", + "FLUSH root.d1b TRUE", + "DELETE FROM root.d1b.d1.s0 WHERE time >= 1 AND time <= 2", + "SELECT s0, s1 FROM root.d1b.d1 WHERE time <= 2", + "Time,root.d1b.d1.s0,root.d1b.d1.s1,", + new String[] {"1,null,1,", "2,null,2,"}); + } finally { + executeSql("SET CONFIGURATION \"tvlist_sort_threshold\"=\"0\""); + } + } + + /** + * D3: After a leading seq file's series chunk is completely deleted via mods, OFFSET must not + * skip an overlapping unseq chunk without unpacking the subsequent seq file. + */ + @Test + public void testD3OffsetDoesNotSkipAChunkThatOverlapsUnpackedData() { + prepareOverlappingAfterChunklessFile("root.d3"); + resultSetEqualTest( + "SELECT s0 FROM root.d3.d1 LIMIT 2 OFFSET 2", "Time,root.d3.d1.s0,", new String[] {"4,4,"}); + } + + /** + * D4: Tree-model wildcard aligned scan with OFFSET must not count rows whose values were all + * deleted. + */ + @Test + public void testD4OffsetCountsRowsWithoutValues() { + prepareData( + new String[] { + "CREATE DATABASE root.d4", + "CREATE ALIGNED TIMESERIES root.d4.d1(s0 INT64, s1 INT64)", + // Page 1: (1, 1, null), (2, null, 2), (3, 3, null); Page 2: (4, 4, null), (5, 5, null) + "INSERT INTO root.d4.d1(time, s0) ALIGNED VALUES (1, 1), (3, 3), (4, 4), (5, 5)", + "INSERT INTO root.d4.d1(time, s1) ALIGNED VALUES (2, 2)", + "FLUSH root.d4", + "DELETE FROM root.d4.d1.s1 WHERE time >= 1 AND time <= 5" + }); + resultSetEqualTest( + "SELECT * FROM root.d4.d1 LIMIT 5 OFFSET 3", + "Time,root.d4.d1.s0,root.d4.d1.s1,", + new String[] {"5,5,null,"}); + } + + /** + * D5: A pushed-down value filter such as {@code s0 != 173} must not match a row whose {@code s0} + * value was deleted (making it null). + */ + @Test + public void testD5PushDownFilterIsAppliedToDeletedValues() { + prepareData( + new String[] { + "CREATE DATABASE root.d5", + "CREATE ALIGNED TIMESERIES root.d5.d1(s0 INT64, s1 INT64)", + "INSERT INTO root.d5.d1(time, s0, s1) ALIGNED VALUES (1, 10, 1), (2, 20, 2), (3, 30, 3)", + "FLUSH root.d5", + "DELETE FROM root.d5.d1.s0 WHERE time = 2" + }); + resultSetEqualTest( + "SELECT s0, s1 FROM root.d5.d1 WHERE s0 != 173", + "Time,root.d5.d1.s0,root.d5.d1.s1,", + new String[] {"1,10,1,", "3,30,3,"}); + } + + /** + * D7: After a leading seq file's series chunk is completely deleted via mods, aggregation must + * not apply statistics independently to both overlapping chunks (double-counting timestamp 3). + */ + @Test + public void testD7StatisticsOfOverlappingChunksAreNotUsedAfterChunklessFile() { + prepareOverlappingAfterChunklessFile("root.d7"); + resultSetEqualTest( + "SELECT COUNT(s0), SUM(s0) FROM root.d7.d1", + "COUNT(root.d7.d1.s0),SUM(root.d7.d1.s0),", + new String[] {"3,54.0,"}); + } + + /** + * D9 (2 columns -> drop 1): COUNT_TIME(*) on an aligned tree device must not count timestamps + * that have no values in any remaining queried column. + */ + @Test + public void testD9TimeStatisticsDoNotCountRowsWithoutQueriedValuesTwoColumns() { + prepareData( + new String[] { + "CREATE DATABASE root.d9a", + "CREATE ALIGNED TIMESERIES root.d9a.d1(s0 INT64, s1 INT64)", + "INSERT INTO root.d9a.d1(time, s0) ALIGNED VALUES (1, 1), (3, 3)", + "INSERT INTO root.d9a.d1(time, s1) ALIGNED VALUES (2, 2)", + "FLUSH root.d9a" + }); + executeNonQuery("DELETE TIMESERIES root.d9a.d1.s1"); + resultSetEqualTest( + "SELECT COUNT_TIME(*) FROM root.d9a.d1", + new String[] {"count_time(*)"}, + new String[] {"2,"}); + } + + /** + * D9 (3 columns -> drop 1, leaving 2 sparse columns): COUNT_TIME(*) must not count timestamps + * that only had values in the dropped column. + */ + @Test + public void testD9TimeStatisticsDoNotCountRowsWithoutQueriedValuesThreeColumns() { + prepareData( + new String[] { + "CREATE DATABASE root.d9b", + "CREATE ALIGNED TIMESERIES root.d9b.d2(s0 INT64, s1 INT64, s2 INT64)", + "INSERT INTO root.d9b.d2(time, s0) ALIGNED VALUES (1, 1)", + "INSERT INTO root.d9b.d2(time, s1) ALIGNED VALUES (2, 2)", + "INSERT INTO root.d9b.d2(time, s2) ALIGNED VALUES (3, 3)", + "FLUSH root.d9b" + }); + executeNonQuery("DELETE TIMESERIES root.d9b.d2.s2"); + resultSetEqualTest( + "SELECT COUNT_TIME(*) FROM root.d9b.d2", + new String[] {"count_time(*)"}, + new String[] {"2,"}); + } + + /** + * D10 (2 columns): COUNT_TIME(*) must not count timestamps whose values were all deleted via + * single-column DELETE. + */ + @Test + public void testD10TimeStatisticsDoNotCountRowsWhoseValuesWereAllDeletedTwoColumns() { + prepareData( + new String[] { + "CREATE DATABASE root.d10a", + "CREATE ALIGNED TIMESERIES root.d10a.d1(s0 INT64, s1 INT64)", + "INSERT INTO root.d10a.d1(time, s0) ALIGNED VALUES (1, 1), (3, 3)", + "INSERT INTO root.d10a.d1(time, s1) ALIGNED VALUES (2, 2)", + "FLUSH root.d10a", + "DELETE FROM root.d10a.d1.s1 WHERE time >= 1 AND time <= 3" + }); + resultSetEqualTest( + "SELECT COUNT_TIME(*) FROM root.d10a.d1", + new String[] {"count_time(*)"}, + new String[] {"2,"}); + } + + /** + * D10 (3 columns): COUNT_TIME(*) must not count timestamps whose values were all deleted when 2 + * sparse columns remain. + */ + @Test + public void testD10TimeStatisticsDoNotCountRowsWhoseValuesWereAllDeletedThreeColumns() { + prepareData( + new String[] { + "CREATE DATABASE root.d10b", + "CREATE ALIGNED TIMESERIES root.d10b.d2(s0 INT64, s1 INT64, s2 INT64)", + "INSERT INTO root.d10b.d2(time, s0) ALIGNED VALUES (1, 1)", + "INSERT INTO root.d10b.d2(time, s1) ALIGNED VALUES (2, 2)", + "INSERT INTO root.d10b.d2(time, s2) ALIGNED VALUES (3, 3)", + "FLUSH root.d10b", + "DELETE FROM root.d10b.d2.s2 WHERE time >= 1 AND time <= 3" + }); + resultSetEqualTest( + "SELECT COUNT_TIME(*) FROM root.d10b.d2", + new String[] {"count_time(*)"}, + new String[] {"2,"}); + } + + /** + * D11: Deleting timestamp 1 across {@code d1.*} drops {@code s1}'s entire value page (which only + * contained timestamp 1) without marking page 1 modified; COUNT_TIME(*) must not count row 1. + */ + @Test + public void testD11TimeStatisticsDoNotCountADeletedRowOfADroppedValuePage() { + prepareData( + new String[] { + "CREATE DATABASE root.d11", + "CREATE ALIGNED TIMESERIES root.d11.d1(s0 INT64, s1 INT64)", + // Page 1: (1, null, 1), (2, 2, null), (3, 3, null); Page 2: (4, 4, null) + "INSERT INTO root.d11.d1(time, s1) ALIGNED VALUES (1, 1)", + "INSERT INTO root.d11.d1(time, s0) ALIGNED VALUES (2, 2), (3, 3), (4, 4)", + "FLUSH root.d11", + "DELETE FROM root.d11.d1.* WHERE time = 1" + }); + resultSetEqualTest( + "SELECT COUNT_TIME(*) FROM root.d11.d1", + new String[] {"count_time(*)"}, + new String[] {"3,"}); + } + + private static void prepareOverlappingAfterChunklessFile(String database) { + prepareData( + new String[] { + "CREATE DATABASE " + database, + "CREATE TIMESERIES " + database + ".d1.s0 WITH DATATYPE=INT64", + "CREATE TIMESERIES " + database + ".d1.s1 WITH DATATYPE=INT64", + // File A (seq): s0 and s1 at t=1,2; s1 keeps File A on disk after s0 is deleted + "INSERT INTO " + database + ".d1(time, s0, s1) VALUES (1, 1, 1), (2, 2, 2)", + "FLUSH " + database, + "DELETE FROM " + database + ".d1.s0 WHERE time <= 2", + // File B (seq): s0 at t=3,4 + "INSERT INTO " + database + ".d1(time, s0) VALUES (3, 3), (4, 4)", + "FLUSH " + database, + // File U (unseq): s0 at t=2,3 overlapping File A's end and File B's start + "INSERT INTO " + database + ".d1(time, s0) VALUES (2, 20), (3, 30)", + "FLUSH " + database + }); + } + + private static void insertBlockerData(String device, long startTime, int rowCount) + throws IoTDBConnectionException, StatementExecutionException { + List schemas = + Collections.singletonList(new MeasurementSchema("s0", TSDataType.TEXT)); + Random random = new Random(42L); + char[] chars = new char[BLOCKER_STRING_LENGTH]; + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.open(); + Tablet tablet = new Tablet(device, schemas); + for (int i = 0; i < rowCount; i++) { + int rowIndex = tablet.getRowSize(); + if (rowIndex == tablet.getMaxRowNumber()) { + session.insertTablet(tablet); + tablet.reset(); + rowIndex = 0; + } + for (int c = 0; c < BLOCKER_STRING_LENGTH; c++) { + chars[c] = (char) ('!' + random.nextInt(94)); + } + tablet.addTimestamp(rowIndex, startTime + i); + tablet.addValue(rowIndex, 0, new String(chars)); + } + if (tablet.getRowSize() > 0) { + session.insertTablet(tablet); + } + } + } + + private static void runDeleteAndQueryWhileFlushing( + String blockerFlushSql, + String targetFlushSql, + String deleteSql, + String querySql, + String expectedHeader, + String[] expectedRows) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blockerFlushFuture = null; + Future targetFlushFuture = null; + try { + blockerFlushFuture = + executor.submit( + () -> { + executeSqlUnchecked(blockerFlushSql); + return null; + }); + // Allow the blocker FLUSH RPC to acquire the sole flush thread + Thread.sleep(200); + targetFlushFuture = + executor.submit( + () -> { + executeSqlUnchecked(targetFlushSql); + return null; + }); + // Allow the target FLUSH RPC to move d1's working memtable into flushingMemTables + Thread.sleep(300); + + executeSql(deleteSql); + resultSetEqualTest(querySql, expectedHeader, expectedRows); + } finally { + try { + if (blockerFlushFuture != null) { + blockerFlushFuture.get(60, TimeUnit.SECONDS); + } + } finally { + try { + if (targetFlushFuture != null) { + targetFlushFuture.get(60, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + } + } + } + } + + private static void executeSql(String sql) throws SQLException { + try (Connection connection = EnvFactory.getEnv().getConnection(); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static void executeSqlUnchecked(String sql) { + try { + executeSql(sql); + } catch (SQLException e) { + throw new RuntimeException("Failed to execute SQL: " + sql, e); + } + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java index c6a0d4878969f..c6f6fd890afe4 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java @@ -445,9 +445,6 @@ public class IoTDBConfig implements DefaultEncodingProvider { */ private int tvListSortThreshold = 0; - /** Enable streaming query mem chunk */ - private boolean streamingQueryMemChunk = true; - /** Enable inner space compaction for sequence files */ private volatile boolean enableSeqSpaceCompaction = true; @@ -2536,14 +2533,6 @@ public void setTVListSortThreshold(int tvListSortThreshold) { this.tvListSortThreshold = tvListSortThreshold; } - public boolean isStreamingQueryMemChunk() { - return streamingQueryMemChunk; - } - - public void setStreamingQueryMemChunk(boolean streamingQueryMemChunk) { - this.streamingQueryMemChunk = streamingQueryMemChunk; - } - public boolean isRpcThriftCompressionEnable() { return rpcThriftCompressionEnable; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/TreeAggregator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/TreeAggregator.java index 89db2107c68ce..f2abc213793f3 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/TreeAggregator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/aggregation/TreeAggregator.java @@ -126,6 +126,15 @@ public void processStatistics(Statistics timeStatistics, Statistics[] valueStati } } + public boolean usesTimeStatistics() { + for (InputLocation[] inputLocations : inputLocationList) { + if (inputLocations[0].getValueColumnIndex() == -1) { + return true; + } + } + return false; + } + public TSDataType[] getOutputType() { if (step.isOutputPartial()) { return accumulator.getIntermediateType(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AbstractSeriesAggregationScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AbstractSeriesAggregationScanOperator.java index 3f9db7bc1655b..52e5b25cceb2c 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AbstractSeriesAggregationScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AbstractSeriesAggregationScanOperator.java @@ -72,6 +72,8 @@ public abstract class AbstractSeriesAggregationScanOperator extends AbstractData /** Some special data types(like BLOB) cannot use statistics. */ protected final boolean canUseStatistics; + private final boolean hasTimeStatisticsAggregator; + @SuppressWarnings("squid:S107") protected AbstractSeriesAggregationScanOperator( PlanNodeId sourceId, @@ -99,6 +101,14 @@ protected AbstractSeriesAggregationScanOperator( this.maxReturnSize = maxReturnSize; this.outputEndTime = outputEndTime; this.canUseStatistics = canUseStatistics; + boolean usesTimeStatistics = false; + for (TreeAggregator aggregator : aggregators) { + if (aggregator.usesTimeStatistics()) { + usesTimeStatistics = true; + break; + } + } + this.hasTimeStatisticsAggregator = usesTimeStatistics; } @Override @@ -282,7 +292,10 @@ protected boolean readAndCalcFromFile() throws IOException { if (!b.get()) { break; } - if (canUseStatistics && seriesScanUtil.canUseCurrentFileStatistics()) { + if (canUseStatistics + && (hasTimeStatisticsAggregator + ? seriesScanUtil.canUseCurrentFileTimeStatistics() + : seriesScanUtil.canUseCurrentFileStatistics())) { Statistics fileTimeStatistics = seriesScanUtil.currentFileTimeStatistics(); if (fileTimeStatistics.getStartTime() > curTimeRange.getMax()) { if (ascending) { @@ -330,7 +343,10 @@ protected boolean readAndCalcFromChunk() throws IOException { if (!b.get()) { break; } - if (canUseStatistics && seriesScanUtil.canUseCurrentChunkStatistics()) { + if (canUseStatistics + && (hasTimeStatisticsAggregator + ? seriesScanUtil.canUseCurrentChunkTimeStatistics() + : seriesScanUtil.canUseCurrentChunkStatistics())) { Statistics chunkTimeStatistics = seriesScanUtil.currentChunkTimeStatistics(); if (chunkTimeStatistics.getStartTime() > curTimeRange.getMax()) { if (ascending) { @@ -372,7 +388,10 @@ protected boolean readAndCalcFromPage() throws IOException { long start = System.nanoTime(); try { while (System.nanoTime() - start < leftRuntimeOfOneNextCall && seriesScanUtil.hasNextPage()) { - if (canUseStatistics && seriesScanUtil.canUseCurrentPageStatistics()) { + if (canUseStatistics + && (hasTimeStatisticsAggregator + ? seriesScanUtil.canUseCurrentPageTimeStatistics() + : seriesScanUtil.canUseCurrentPageStatistics())) { Statistics pageTimeStatistics = seriesScanUtil.currentPageTimeStatistics(); // There is no more eligible points in current time range if (pageTimeStatistics.getStartTime() > curTimeRange.getMax()) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanUtil.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanUtil.java index 0bcc23abac354..40a3628e0b7cc 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanUtil.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanUtil.java @@ -33,6 +33,7 @@ import org.apache.tsfile.enums.TSDataType; import org.apache.tsfile.file.metadata.AbstractAlignedTimeSeriesMetadata; import org.apache.tsfile.file.metadata.IMetadata; +import org.apache.tsfile.file.metadata.statistics.Statistics; import org.apache.tsfile.read.common.block.TsBlock; import org.apache.tsfile.read.reader.IPointReader; import org.apache.tsfile.write.schema.IMeasurementSchema; @@ -45,12 +46,6 @@ public class AlignedSeriesScanUtil extends SeriesScanUtil { private final List dataTypes; - // only used for limit and offset push down optimizer, if we select all columns from aligned - // device, we can use statistics to skip. - // it's only exact while using limit & offset push down - // for table scan, it should always be true - private final boolean queryAllSensors; - // for table model, it will be false // for tree model, it will be true private final boolean ignoreAllNullRows; @@ -78,7 +73,6 @@ public AlignedSeriesScanUtil( : seriesPath.getSchemaList().stream() .map(IMeasurementSchema::getType) .collect(Collectors.toList()); - this.queryAllSensors = queryAllSensors; this.ignoreAllNullRows = context.isIgnoreAllNullRows(); } @@ -115,9 +109,90 @@ protected IPointReader getPointReader(TsBlock tsBlock) { return new TsBlockAlignedRowPointReader(tsBlock); } + @Override + public boolean canUseCurrentFileTimeStatistics() { + return canUseCurrentFileStatistics() && canUseAlignedTimeStatistics(firstTimeSeriesMetadata); + } + + @Override + public boolean canUseCurrentChunkTimeStatistics() { + return canUseCurrentChunkStatistics() && canUseAlignedTimeStatistics(firstChunkMetadata); + } + + @Override + public boolean canUseCurrentPageTimeStatistics() throws IOException { + return canUseCurrentPageStatistics() + && firstPageReader != null + && !(firstPageReader instanceof LazyMemVersionPageReader) + && canUseAlignedTimeStatistics(firstPageReader.getPageReader()); + } + + @Override + @SuppressWarnings("squid:S3740") + public Statistics currentFileTimeStatistics() { + return getAlignedTimeStatistics(firstTimeSeriesMetadata, super.currentFileTimeStatistics()); + } + + @Override + @SuppressWarnings("squid:S3740") + public Statistics currentChunkTimeStatistics() { + return getAlignedTimeStatistics(firstChunkMetadata, super.currentChunkTimeStatistics()); + } + + @Override + @SuppressWarnings("squid:S3740") + public Statistics currentPageTimeStatistics() { + if (firstPageReader == null || firstPageReader instanceof LazyMemVersionPageReader) { + return super.currentPageTimeStatistics(); + } + return getAlignedTimeStatistics( + firstPageReader.getPageReader(), super.currentPageTimeStatistics()); + } + + private boolean canUseAlignedTimeStatistics(IMetadata metadata) { + if (!ignoreAllNullRows || metadata == null) { + return true; + } + return timeAllSelected(metadata) || hasAtMostOneNonNullMeasurement(metadata); + } + + private boolean hasAtMostOneNonNullMeasurement(IMetadata metadata) { + int nonNullCount = 0; + for (int i = 0, count = metadata.getMeasurementCount(); i < count; i++) { + Statistics valueStats = metadata.getMeasurementStatistics(i).orElse(null); + if (valueStats != null && !valueStats.isEmpty() && ++nonNullCount > 1) { + return false; + } + } + return true; + } + + @SuppressWarnings("squid:S3740") + private Statistics getAlignedTimeStatistics(IMetadata metadata, Statistics timeStatistics) { + if (!ignoreAllNullRows || metadata == null || timeStatistics == null) { + return timeStatistics; + } + int measurementCount = metadata.getMeasurementCount(); + if (measurementCount <= 0) { + return timeStatistics; + } + Statistics singleNonNullMeasurementStatistics = null; + int nonNullCount = 0; + for (int i = 0; i < measurementCount; i++) { + Statistics valueStats = metadata.getMeasurementStatistics(i).orElse(null); + if (valueStats != null && !valueStats.isEmpty()) { + if (++nonNullCount > 1) { + return timeStatistics; + } + singleNonNullMeasurementStatistics = valueStats; + } + } + return nonNullCount == 1 ? singleNonNullMeasurementStatistics : timeStatistics; + } + @Override protected boolean timeAllSelected(IMetadata metadata) { - if (queryAllSensors || metadata.getMeasurementCount() == 0) { + if (!ignoreAllNullRows || metadata.getMeasurementCount() == 0) { return true; } return metadata.timeAllSelected(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/SeriesScanUtil.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/SeriesScanUtil.java index 74feb66abecdc..3df56dab81988 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/SeriesScanUtil.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/SeriesScanUtil.java @@ -69,6 +69,7 @@ import org.apache.tsfile.read.filter.basic.Filter; import org.apache.tsfile.read.reader.IPageReader; import org.apache.tsfile.read.reader.IPointReader; +import org.apache.tsfile.read.reader.page.AbstractAlignedPageReader; import org.apache.tsfile.read.reader.page.AlignedPageReader; import org.apache.tsfile.read.reader.page.TablePageReader; import org.apache.tsfile.read.reader.series.PaginationController; @@ -119,16 +120,16 @@ public class SeriesScanUtil implements Accountable { private int curUnseqFileIndex; // TimeSeriesMetadata cache - private ITimeSeriesMetadata firstTimeSeriesMetadata; + protected ITimeSeriesMetadata firstTimeSeriesMetadata; private final List seqTimeSeriesMetadata; private final PriorityQueue unSeqTimeSeriesMetadata; // chunk cache - private IChunkMetadata firstChunkMetadata; + protected IChunkMetadata firstChunkMetadata; private final PriorityQueue cachedChunkMetadata; // page cache - private IVersionPageReader firstPageReader; + protected IVersionPageReader firstPageReader; private final List seqPageReaders; private final PriorityQueue unSeqPageReaders; @@ -347,6 +348,10 @@ public boolean canUseCurrentFileStatistics() { && filterAllSatisfy(scanOptions.getPushDownFilter(), firstTimeSeriesMetadata); } + public boolean canUseCurrentFileTimeStatistics() { + return canUseCurrentFileStatistics(); + } + /** * Returns false when the time range cannot contain any row that may still qualify for TopK, so * the caller can skip decoding the whole file/chunk/page. @@ -482,30 +487,27 @@ private void initFirstChunkMetadata() throws IOException { /* * try to unpack all overlapped TimeSeriesMetadata to cachedChunkMetadata */ - unpackAllOverlappedTsFilesToTimeSeriesMetadata( - orderUtils.getOverlapCheckTime(firstTimeSeriesMetadata.getStatistics())); - unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata( - orderUtils.getOverlapCheckTime(firstTimeSeriesMetadata.getStatistics()), true); - } else { - /* - * first time series metadata is already unpacked, consume cached ChunkMetadata - */ - while (!cachedChunkMetadata.isEmpty()) { - firstChunkMetadata = cachedChunkMetadata.peek(); - unpackAllOverlappedTsFilesToTimeSeriesMetadata( - orderUtils.getOverlapCheckTime(firstChunkMetadata.getStatistics())); - unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata( - orderUtils.getOverlapCheckTime(firstChunkMetadata.getStatistics()), false); - if (firstChunkMetadata.equals(cachedChunkMetadata.peek())) { - firstChunkMetadata = cachedChunkMetadata.poll(); - break; - } + long endpointTime = orderUtils.getOverlapCheckTime(firstTimeSeriesMetadata.getStatistics()); + unpackAllOverlappedTsFilesToTimeSeriesMetadata(endpointTime); + unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(endpointTime); + } + + /* + * first time series metadata is already unpacked, consume cached ChunkMetadata + */ + while (!cachedChunkMetadata.isEmpty()) { + firstChunkMetadata = cachedChunkMetadata.peek(); + long endpointTime = orderUtils.getOverlapCheckTime(firstChunkMetadata.getStatistics()); + unpackAllOverlappedTsFilesToTimeSeriesMetadata(endpointTime); + unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(endpointTime); + if (firstChunkMetadata.equals(cachedChunkMetadata.peek())) { + firstChunkMetadata = cachedChunkMetadata.poll(); + break; } } } - private void unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata( - long endpointTime, boolean init) { + private void unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(long endpointTime) { while (!seqTimeSeriesMetadata.isEmpty() && orderUtils.isOverlapped(endpointTime, seqTimeSeriesMetadata.get(0).getStatistics())) { unpackOneTimeSeriesMetadata(seqTimeSeriesMetadata.remove(0)); @@ -520,10 +522,6 @@ private void unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata( unpackOneTimeSeriesMetadata(firstTimeSeriesMetadata); firstTimeSeriesMetadata = null; } - - if (init && firstChunkMetadata == null && !cachedChunkMetadata.isEmpty()) { - firstChunkMetadata = cachedChunkMetadata.poll(); - } } protected void unpackOneTimeSeriesMetadata(ITimeSeriesMetadata timeSeriesMetadata) { @@ -550,6 +548,10 @@ public boolean canUseCurrentChunkStatistics() { && filterAllSatisfy(scanOptions.getPushDownFilter(), firstChunkMetadata); } + public boolean canUseCurrentChunkTimeStatistics() { + return canUseCurrentChunkStatistics(); + } + @SuppressWarnings("squid:S3740") public Statistics currentChunkTimeStatistics() { return firstChunkMetadata.getTimeStatistics(); @@ -654,7 +656,7 @@ private boolean firstPageOverlapped() throws IOException { long endpointTime = orderUtils.getOverlapCheckTime(firstPageReader.getStatistics()); unpackAllOverlappedTsFilesToTimeSeriesMetadata(endpointTime); - unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(endpointTime, false); + unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(endpointTime); unpackAllOverlappedChunkMetadataToPageReaders(endpointTime, false); return (!seqPageReaders.isEmpty() @@ -706,8 +708,7 @@ private void unpackOneChunkMetaData(IChunkMetadata chunkMetaData) throws IOExcep } else { tsFile = null; } - if ((chunkLoader instanceof MemChunkLoader) - && ((MemChunkLoader) chunkLoader).isStreamingQueryMemChunk()) { + if (chunkLoader instanceof MemChunkLoader) { unpackOneFakeMemChunkMetaData( chunkMetaData, (MemChunkLoader) chunkLoader, timestampInFileName); return; @@ -871,6 +872,10 @@ public boolean canUseCurrentPageStatistics() throws IOException { && filterAllSatisfy(scanOptions.getPushDownFilter(), firstPageReader.getPageReader()); } + public boolean canUseCurrentPageTimeStatistics() throws IOException { + return canUseCurrentPageStatistics(); + } + @SuppressWarnings("squid:S3740") public Statistics currentPageTimeStatistics() { if (firstPageReader == null) { @@ -933,9 +938,9 @@ public TsBlock nextPage() throws IOException { return null; } - firstPageReader.addPushDownFilter(scanOptions.getPushDownFilter()); - + Filter pushDownFilter = scanOptions.getPushDownFilter(); if (firstPageReader instanceof LazyMemVersionPageReader) { + firstPageReader.addPushDownFilter(pushDownFilter); firstPageReader.setLimitOffset(paginationController); LazyMemVersionPageReader lazyMemVersionPageReader = (LazyMemVersionPageReader) firstPageReader; @@ -953,6 +958,23 @@ public TsBlock nextPage() throws IOException { return tsBlock == null ? null : getTransferedDataTypeTsBlock(tsBlock); } + // Modified aligned page readers evaluate pushDownFilter.allSatisfy(...) against pre-deletion + // statistics, which can skip row-level filtering for values deleted to null. Decode the page + // with deletions applied first, then apply pushDownFilter and pagination on the TsBlock. + if (pushDownFilter != null + && firstPageReader.isModified() + && firstPageReader.getPageReader() instanceof AbstractAlignedPageReader) { + TsBlock tsBlock = firstPageReader.getAllSatisfiedPageData(orderUtils.getAscending()); + firstPageReader = null; + if (tsBlock == null || tsBlock.isEmpty()) { + return tsBlock; + } + tsBlock = getTransferedDataTypeTsBlock(tsBlock); + return applyPushDownFilterAndPagination(tsBlock, pushDownFilter); + } + + firstPageReader.addPushDownFilter(pushDownFilter); + TsBlock tsBlock; if (orderUtils.getAscending()) { firstPageReader.setLimitOffset(paginationController); @@ -969,6 +991,20 @@ public TsBlock nextPage() throws IOException { } } + private TsBlock applyPushDownFilterAndPagination(TsBlock tsBlock, Filter pushDownFilter) { + TsBlockBuilder builder = new TsBlockBuilder(getTsDataTypeList()); + if (this.context.isVerbose()) { + return TsBlockUtil.applyFilterAndLimitOffsetToTsBlock( + tsBlock, + builder, + pushDownFilter, + paginationController, + this.context.getQueryStatistics()::addFilteredRowsOfRowLevel); + } + return TsBlockUtil.applyFilterAndLimitOffsetToTsBlock( + tsBlock, builder, pushDownFilter, paginationController); + } + private TsBlock filterAndPaginateCachedBlock(TsBlock tsBlock) { tsBlock = applyRuntimeFilterToTsBlock(tsBlock); if (tsBlock == null || tsBlock.isEmpty()) { @@ -1147,7 +1183,7 @@ private boolean hasNextOverlappedPage() throws IOException { // unpack all overlapped data for the first timeValuePair unpackAllOverlappedTsFilesToTimeSeriesMetadata(timeValuePair.getTimestamp()); unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata( - timeValuePair.getTimestamp(), false); + timeValuePair.getTimestamp()); unpackAllOverlappedChunkMetadataToPageReaders(timeValuePair.getTimestamp(), false); unpackAllOverlappedUnseqPageReadersToMergeReader(); @@ -1331,7 +1367,7 @@ private void initFirstPageReader() throws IOException { if (firstPageReader != null) { long overlapCheckTime = orderUtils.getOverlapCheckTime(firstPageReader.getStatistics()); unpackAllOverlappedTsFilesToTimeSeriesMetadata(overlapCheckTime); - unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(overlapCheckTime, false); + unpackAllOverlappedTimeSeriesMetadataToCachedChunkMetadata(overlapCheckTime); unpackAllOverlappedChunkMetadataToPageReaders(overlapCheckTime, false); // this page after unpacking must be the first page diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/utils/ResourceByPathUtils.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/utils/ResourceByPathUtils.java index f72711387249b..94138f1c7795b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/utils/ResourceByPathUtils.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/schemaengine/schemaregion/utils/ResourceByPathUtils.java @@ -25,7 +25,6 @@ import org.apache.iotdb.commons.path.AlignedFullPath; import org.apache.iotdb.commons.path.IFullPath; import org.apache.iotdb.commons.path.NonAlignedFullPath; -import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.i18n.DataNodeSchemaMessages; import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext; import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext; @@ -421,9 +420,7 @@ public AbstractAlignedTimeSeriesMetadata generateTimeSeriesMetadata( timeTimeSeriesMetadata.setMeasurementId(""); timeTimeSeriesMetadata.setTsDataType(TSDataType.VECTOR); - boolean useFakeStatistics = - !readOnlyMemChunk.isEmpty() - && IoTDBDescriptor.getInstance().getConfig().isStreamingQueryMemChunk(); + boolean useFakeStatistics = !readOnlyMemChunk.isEmpty(); long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; Statistics timeStatistics = @@ -476,31 +473,13 @@ public AbstractAlignedTimeSeriesMetadata generateTimeSeriesMetadata( for (ReadOnlyMemChunk memChunk : readOnlyMemChunk) { if (!memChunk.isEmpty()) { memChunk.sortTvLists(); - if (useFakeStatistics) { - memChunk.initChunkMetaFromTVListsWithFakeStatistics(); - startTime = Math.min(startTime, memChunk.getChunkMetaData().getStartTime()); - endTime = Math.max(endTime, memChunk.getChunkMetaData().getEndTime()); - } else { - memChunk.initChunkMetaFromTvLists(globalTimeFilter); - } + memChunk.initChunkMetaFromTVListsWithFakeStatistics(); + startTime = Math.min(startTime, memChunk.getChunkMetaData().getStartTime()); + endTime = Math.max(endTime, memChunk.getChunkMetaData().getEndTime()); AbstractAlignedChunkMetadata alignedChunkMetadata = (AbstractAlignedChunkMetadata) memChunk.getChunkMetaData(); isTable = isTable || (alignedChunkMetadata instanceof TableDeviceChunkMetadata); rewriteStatistics(alignedChunkMetadata, measurementMap); - if (!useFakeStatistics) { - timeStatistics.mergeStatistics( - alignedChunkMetadata.getTimeChunkMetadata().getStatistics()); - for (int i = 0; i < valueTimeSeriesMetadataList.size(); i++) { - if (alignedChunkMetadata.getValueChunkMetadataList().get(i) != null) { - exist[i] = true; - valueTimeSeriesMetadataList - .get(i) - .getStatistics() - .mergeStatistics( - alignedChunkMetadata.getValueChunkMetadataList().get(i).getStatistics()); - } - } - } } } @@ -725,9 +704,7 @@ public ITimeSeriesMetadata generateTimeSeriesMetadata( List readOnlyMemChunk, List chunkMetadataList, Filter globalTimeFilter) { - boolean useFakeStatistics = - !readOnlyMemChunk.isEmpty() - && IoTDBDescriptor.getInstance().getConfig().isStreamingQueryMemChunk(); + boolean useFakeStatistics = !readOnlyMemChunk.isEmpty(); TimeseriesMetadata timeSeriesMetadata = new TimeseriesMetadata(); timeSeriesMetadata.setMeasurementId(fullPath.getMeasurementSchema().getMeasurementName()); timeSeriesMetadata.setTsDataType(fullPath.getMeasurementSchema().getType()); @@ -781,14 +758,9 @@ public ITimeSeriesMetadata generateTimeSeriesMetadata( memChunk.setChunkMetadata(rewritedChunkMetadata); memChunk.getChunkMetaData().setDataTypeModifiedAndCannotUseStatistics(true); } - if (useFakeStatistics) { - memChunk.initChunkMetaFromTVListsWithFakeStatistics(); - startTime = Math.min(startTime, memChunk.getChunkMetaData().getStartTime()); - endTime = Math.max(endTime, memChunk.getChunkMetaData().getEndTime()); - } else { - memChunk.initChunkMetaFromTvLists(globalTimeFilter); - seriesStatistics.mergeStatistics(memChunk.getChunkMetaData().getStatistics()); - } + memChunk.initChunkMetaFromTVListsWithFakeStatistics(); + startTime = Math.min(startTime, memChunk.getChunkMetaData().getStartTime()); + endTime = Math.max(endTime, memChunk.getChunkMetaData().getEndTime()); } } if (useFakeStatistics) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/AlignedReadOnlyMemChunk.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/AlignedReadOnlyMemChunk.java index 7235cd9afe762..85bace0a36f39 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/AlignedReadOnlyMemChunk.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/AlignedReadOnlyMemChunk.java @@ -291,7 +291,7 @@ public void initChunkMetaFromTVListsWithFakeStatistics() { context.isIgnoreAllNullRows() ? new AlignedChunkMetadata(timeChunkMetadata, valueChunkMetadataList) : new TableDeviceChunkMetadata(timeChunkMetadata, valueChunkMetadataList); - alignedChunkMetadata.setChunkLoader(new MemAlignedChunkLoader(context, this, true)); + alignedChunkMetadata.setChunkLoader(new MemAlignedChunkLoader(context, this)); alignedChunkMetadata.setVersion(Long.MAX_VALUE); // By setting Modified to true, we can prevent these fake statistics from being used. alignedChunkMetadata.setModified(true); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/ReadOnlyMemChunk.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/ReadOnlyMemChunk.java index bb2b5f704e5b1..e6e67a49c6461 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/ReadOnlyMemChunk.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/memtable/ReadOnlyMemChunk.java @@ -211,7 +211,7 @@ public void initChunkMetaFromTVListsWithFakeStatistics() { pageStatisticsList.add(generateFakeStatistics(dataType, pageStartTime, pageEndTime)); } - cachedMetaData.setChunkLoader(new MemChunkLoader(context, this, true)); + cachedMetaData.setChunkLoader(new MemChunkLoader(context, this)); cachedMetaData.setVersion(Long.MAX_VALUE); // By setting Modified to true, we can prevent these fake statistics from being used. cachedMetaData.setModified(true); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/DiskAlignedChunkLoader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/DiskAlignedChunkLoader.java index 06c43821c2b0d..9f73f05af0e30 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/DiskAlignedChunkLoader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/DiskAlignedChunkLoader.java @@ -25,17 +25,23 @@ import org.apache.iotdb.db.storageengine.buffer.ChunkCache; import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileID; import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource; +import org.apache.iotdb.db.utils.ModificationUtils; import org.apache.tsfile.enums.TSDataType; 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.statistics.Statistics; import org.apache.tsfile.read.common.Chunk; +import org.apache.tsfile.read.common.TimeRange; import org.apache.tsfile.read.controller.IChunkLoader; import org.apache.tsfile.read.filter.basic.Filter; import org.apache.tsfile.read.reader.IChunkReader; +import org.apache.tsfile.read.reader.IPageReader; import org.apache.tsfile.read.reader.chunk.AlignedChunkReader; import org.apache.tsfile.read.reader.chunk.TableChunkReader; +import org.apache.tsfile.read.reader.page.AlignedPageReader; +import org.apache.tsfile.read.reader.page.ValuePageReader; import java.io.File; import java.io.IOException; @@ -55,14 +61,26 @@ public class DiskAlignedChunkLoader implements IChunkLoader { // for tree model, it will be true private final boolean ignoreAllNullRows; + // deletions for value columns whose metadata were removed to null before loading this chunk + private final List removedValueColumnDeletions; + private static final SeriesScanCostMetricSet SERIES_SCAN_COST_METRIC_SET = SeriesScanCostMetricSet.getInstance(); public DiskAlignedChunkLoader( QueryContext context, TsFileResource resource, boolean ignoreAllNullRows) { + this(context, resource, ignoreAllNullRows, null); + } + + public DiskAlignedChunkLoader( + QueryContext context, + TsFileResource resource, + boolean ignoreAllNullRows, + List removedValueColumnDeletions) { this.context = context; this.resource = resource; this.ignoreAllNullRows = ignoreAllNullRows; + this.removedValueColumnDeletions = removedValueColumnDeletions; } @Override @@ -130,6 +148,13 @@ public IChunkReader getChunkReader(IChunkMetadata chunkMetaData, Filter globalTi timeChunk, valueChunkList, globalTimeFilter, filterRowsRecorder) : new TableChunkReader( timeChunk, valueChunkList, globalTimeFilter, filterRowsRecorder); + if (ignoreAllNullRows) { + markDeletedPagesModified( + chunkReader.loadPageReaderList(), + timeChunk, + valueChunkList, + alignedChunkMetadata.isModified()); + } if (timeChunk.getEncryptParam() != null && timeChunk.getEncryptParam().isTdePageAead()) { context.getQueryChunkReaders().retain(chunkReader, chunkReader.loadPageReaderList()); } @@ -153,6 +178,81 @@ public IChunkReader getChunkReader(IChunkMetadata chunkMetaData, Filter globalTi } } + private void markDeletedPagesModified( + List pageReaderList, + Chunk timeChunk, + List valueChunkList, + boolean chunkModified) { + List timeDeletions = timeChunk.getDeleteIntervalList(); + boolean hasTimeDeletions = timeDeletions != null && !timeDeletions.isEmpty(); + boolean hasRemovedValueDeletions = + removedValueColumnDeletions != null && !removedValueColumnDeletions.isEmpty(); + boolean hasNullValueChunk = false; + boolean hasValueChunkDeletions = false; + for (Chunk valueChunk : valueChunkList) { + if (valueChunk == null) { + hasNullValueChunk = true; + } else if (valueChunk.getDeleteIntervalList() != null + && !valueChunk.getDeleteIntervalList().isEmpty()) { + hasValueChunkDeletions = true; + } + } + if (!hasTimeDeletions + && !hasRemovedValueDeletions + && !hasValueChunkDeletions + && !(chunkModified && hasNullValueChunk && removedValueColumnDeletions == null)) { + return; + } + for (IPageReader pageReader : pageReaderList) { + if (pageReader.isModified() || !(pageReader instanceof AlignedPageReader)) { + continue; + } + AlignedPageReader alignedPageReader = (AlignedPageReader) pageReader; + Statistics timeStats = alignedPageReader.getTimeStatistics(); + long pageStart = timeStats.getStartTime(); + long pageEnd = timeStats.getEndTime(); + if ((hasTimeDeletions && hasOverlap(timeDeletions, pageStart, pageEnd)) + || (hasRemovedValueDeletions + && hasOverlap(removedValueColumnDeletions, pageStart, pageEnd)) + || (chunkModified && hasNullValueChunk && removedValueColumnDeletions == null) + || hasDroppedValuePageDeletion(alignedPageReader, valueChunkList, pageStart, pageEnd)) { + alignedPageReader.setModified(true); + } + } + } + + private static boolean hasDroppedValuePageDeletion( + AlignedPageReader alignedPageReader, + List valueChunkList, + long pageStart, + long pageEnd) { + List valuePageReaders = alignedPageReader.getValuePageReaderList(); + int size = Math.min(valueChunkList.size(), valuePageReaders.size()); + for (int i = 0; i < size; i++) { + if (valuePageReaders.get(i) != null) { + continue; + } + Chunk valueChunk = valueChunkList.get(i); + if (valueChunk != null + && hasOverlap(valueChunk.getDeleteIntervalList(), pageStart, pageEnd)) { + return true; + } + } + return false; + } + + private static boolean hasOverlap(List deletions, long startTime, long endTime) { + if (deletions == null || deletions.isEmpty()) { + return false; + } + for (TimeRange range : deletions) { + if (ModificationUtils.overlap(startTime, endTime, range.getMin(), range.getMax())) { + return true; + } + } + return false; + } + public TsFileID getTsFileID() { return resource.getTsFileID(); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoader.java index da01964ae3954..f06657b6454f4 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoader.java @@ -35,11 +35,6 @@ public MemAlignedChunkLoader(QueryContext context, AlignedReadOnlyMemChunk chunk super(context, chunk); } - public MemAlignedChunkLoader( - QueryContext context, AlignedReadOnlyMemChunk chunk, boolean streamingQueryMemChunk) { - super(context, chunk, streamingQueryMemChunk); - } - @Override public IChunkReader getChunkReader(IChunkMetadata chunkMetaData, Filter globalTimeFilter) { long startTime = System.nanoTime(); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedPageReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedPageReader.java index a673bb6efb140..a248bed53d45f 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedPageReader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedPageReader.java @@ -214,6 +214,11 @@ public Optional> getMeasurementStatistics( return pageMetadata.getMeasurementStatistics(measurementIndex); } + @Override + public int getMeasurementCount() { + return tsDataTypes.size(); + } + @Override public boolean hasNullValue(int measurementIndex) { return pageMetadata.hasNullValue(measurementIndex); diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoader.java index e441e21b1791e..48138909f68aa 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoader.java @@ -36,20 +36,13 @@ public class MemChunkLoader implements IChunkLoader { protected final QueryContext context; protected final ReadOnlyMemChunk chunk; - protected final boolean streamingQueryMemChunk; protected static final SeriesScanCostMetricSet SERIES_SCAN_COST_METRIC_SET = SeriesScanCostMetricSet.getInstance(); public MemChunkLoader(QueryContext context, ReadOnlyMemChunk chunk) { - this(context, chunk, false); - } - - public MemChunkLoader( - QueryContext context, ReadOnlyMemChunk chunk, boolean streamingQueryMemChunk) { this.context = context; this.chunk = chunk; - this.streamingQueryMemChunk = streamingQueryMemChunk; } @Override @@ -78,8 +71,4 @@ public IChunkReader getChunkReader(IChunkMetadata chunkMetaData, Filter globalTi public ReadOnlyMemChunk getReadOnlyMemChunk() { return chunk; } - - public boolean isStreamingQueryMemChunk() { - return streamingQueryMemChunk; - } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/AlignedPageMetadata.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/AlignedPageMetadata.java index c06ec112be038..ec28efdcdcf8d 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/AlignedPageMetadata.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/AlignedPageMetadata.java @@ -52,7 +52,14 @@ public Statistics getTimeStatistics() { public Optional> getMeasurementStatistics( int measurementIndex) { return Optional.ofNullable( - measurementIndex >= valueStatistics.length ? null : valueStatistics[measurementIndex]); + valueStatistics == null || measurementIndex >= valueStatistics.length + ? null + : valueStatistics[measurementIndex]); + } + + @Override + public int getMeasurementCount() { + return valueStatistics == null ? 0 : valueStatistics.length; } @Override diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/DiskAlignedChunkMetadataLoader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/DiskAlignedChunkMetadataLoader.java index 30dba656940b3..569d581f6da3d 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/DiskAlignedChunkMetadataLoader.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/DiskAlignedChunkMetadataLoader.java @@ -31,12 +31,14 @@ import org.apache.tsfile.file.metadata.AbstractAlignedTimeSeriesMetadata; import org.apache.tsfile.file.metadata.IChunkMetadata; import org.apache.tsfile.file.metadata.ITimeSeriesMetadata; +import org.apache.tsfile.read.common.TimeRange; import org.apache.tsfile.read.controller.IChunkMetadataLoader; import org.apache.tsfile.read.filter.basic.Filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import static org.apache.iotdb.db.queryengine.metric.SeriesScanCostMetricSet.CHUNK_METADATA_FILTER_ALIGNED_DISK; @@ -134,8 +136,13 @@ public List loadChunkMetadataList(ITimeSeriesMetadata timeSeries if (chunkMetadata.needSetChunkLoader()) { chunkMetadata.setVersion(resource.getVersion()); chunkMetadata.setClosed(resource.isClosed()); + List removedValueColumnDeletions = + ignoreAllNullRows + ? collectRemovedValueColumnDeletions(chunkMetadata) + : Collections.emptyList(); chunkMetadata.setChunkLoader( - new DiskAlignedChunkLoader(context, resource, ignoreAllNullRows)); + new DiskAlignedChunkLoader( + context, resource, ignoreAllNullRows, removedValueColumnDeletions)); } }); @@ -145,4 +152,34 @@ public List loadChunkMetadataList(ITimeSeriesMetadata timeSeries LOAD_CHUNK_METADATA_LIST_ALIGNED_DISK, System.nanoTime() - t1); } } + + private List collectRemovedValueColumnDeletions( + AbstractAlignedChunkMetadata chunkMetadata) { + List valueChunkMetadataList = chunkMetadata.getValueChunkMetadataList(); + long chunkStart = chunkMetadata.getStartTime(); + long chunkEnd = chunkMetadata.getEndTime(); + List deletions = null; + for (int i = 0, + size = Math.min(valueChunkMetadataList.size(), valueColumnsModifications.size()); + i < size; + i++) { + if (valueChunkMetadataList.get(i) != null) { + continue; + } + List mods = valueColumnsModifications.get(i); + if (mods == null || mods.isEmpty()) { + continue; + } + for (ModEntry mod : mods) { + TimeRange range = mod.getTimeRange(); + if (ModificationUtils.overlap(chunkStart, chunkEnd, range.getMin(), range.getMax())) { + if (deletions == null) { + deletions = new ArrayList<>(); + } + deletions.add(range); + } + } + } + return deletions == null ? Collections.emptyList() : deletions; + } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/ModificationUtils.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/ModificationUtils.java index e6dd6170ae6e4..ca4ad79f8b5d8 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/ModificationUtils.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/ModificationUtils.java @@ -108,7 +108,7 @@ public static void modifyAlignedChunkMetaData( // the whole aligned path need to be removed, only set to be true if all the sub sensors // are deleted // the whole aligned path is modified, set to be true if any sub sensor is modified - return areAllValueColumnsDeleted(alignedChunkMetadata, false); + return areAllValueColumnsDeleted(alignedChunkMetadata, false, null, false); }); } @@ -127,8 +127,25 @@ private static void modifyValueColumns( } } + private static boolean hasOverlappingModification( + List modifications, long startTime, long endTime) { + if (modifications == null || modifications.isEmpty()) { + return false; + } + for (ModEntry modification : modifications) { + TimeRange range = modification.getTimeRange(); + if (overlap(startTime, endTime, range.getMin(), range.getMax())) { + return true; + } + } + return false; + } + private static boolean areAllValueColumnsDeleted( - AbstractAlignedChunkMetadata alignedChunkMetadata, boolean modified) { + AbstractAlignedChunkMetadata alignedChunkMetadata, + boolean modified, + List> valueColumnsModifications, + boolean ignoreAllNullRows) { // the whole aligned path need to be removed, only set to be true if all the sub sensors // are deleted and ignoreAllNullRows is true @@ -137,6 +154,16 @@ private static boolean areAllValueColumnsDeleted( for (int i = 0; i < valueChunkMetadataList.size(); i++) { IChunkMetadata valueChunkMetadata = valueChunkMetadataList.get(i); if (valueChunkMetadata == null) { + if (ignoreAllNullRows + && !modified + && valueColumnsModifications != null + && i < valueColumnsModifications.size() + && hasOverlappingModification( + valueColumnsModifications.get(i), + alignedChunkMetadata.getStartTime(), + alignedChunkMetadata.getEndTime())) { + modified = true; + } continue; } // current sub sensor's chunk metadata is completely removed @@ -146,6 +173,9 @@ private static boolean areAllValueColumnsDeleted( if (range.contains(valueChunkMetadata.getStartTime(), valueChunkMetadata.getEndTime())) { valueChunkMetadataList.set(i, null); currentRemoved = true; + if (ignoreAllNullRows) { + modified = true; + } break; } else { if (overlap( @@ -213,7 +243,8 @@ public static void modifyAlignedChunkMetaData( } boolean allValueColumnsAreDeleted = - areAllValueColumnsDeleted(alignedChunkMetadata, modified); + areAllValueColumnsDeleted( + alignedChunkMetadata, modified, valueColumnsModifications, ignoreAllNullRows); return ignoreAllNullRows && allValueColumnsAreDeleted; }); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/AlignedTVList.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/AlignedTVList.java index 0052497b922b6..d6a315e9cac3f 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/AlignedTVList.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/AlignedTVList.java @@ -2114,6 +2114,8 @@ public class AlignedTVListIterator extends TVListIterator implements AlignedPoin // remember the selected index of last not-null value for each column during prepareNext phase private final int[] selectedIndices; + // remember whether each column of the prepared row is deleted by valueColumnsDeletionList + private final boolean[] deletedColumns; private boolean findValidRow; private boolean lastRowComplete = false; @@ -2161,6 +2163,8 @@ public AlignedTVListIterator( Type.fromTsDataType(dataType))) .collect(Collectors.toList()); this.selectedIndices = new int[dataTypeList.size()]; + this.deletedColumns = + valueColumnsDeletionList == null ? null : new boolean[dataTypeList.size()]; timeDeleteCursor[0] = (timeColumnDeletion == null || scanOrder.isAscending()) ? 0 @@ -2176,6 +2180,23 @@ public AlignedTVListIterator( } } + @Override + public void reset() { + super.reset(); + timeDeleteCursor[0] = + (timeColumnDeletion == null || scanOrder.isAscending()) + ? 0 + : (timeColumnDeletion.size() - 1); + for (int i = 0; i < valueColumnDeleteCursor.size(); i++) { + List valueColumnDeletions = + valueColumnsDeletionList == null ? null : valueColumnsDeletionList.get(i); + valueColumnDeleteCursor.get(i)[0] = + (valueColumnDeletions == null || scanOrder.isAscending()) + ? 0 + : (valueColumnDeletions.size() - 1); + } + } + @Override @SuppressWarnings("java:S6541") protected void prepareNext() { @@ -2248,23 +2269,25 @@ && getTime(getScanOrderIndex(index + 1)) == getTime(getScanOrderIndex(index))) { // valueColumnsDeletionList is set when AlignedTVList iterator is created by // MemPointIterator.single method. Otherwise, it is checked by // MergeSortMultiAlignedTVListIterator or OrderedMultiAlignedTVListIterator. - if (ignoreAllNullRows) { - BitMap bitMap = null; + if (valueColumnsDeletionList != null || ignoreAllNullRows) { + boolean hasNonNull = false; time = getTime(getScanOrderIndex(index)); for (int columnIndex = 0; columnIndex < dataTypeList.size(); columnIndex++) { - if (selectedIndices[columnIndex] == -1 - || (valueColumnsDeletionList != null + boolean isDeleted = + valueColumnsDeletionList != null && isPointDeleted( time, valueColumnsDeletionList.get(columnIndex), valueColumnDeleteCursor.get(columnIndex), - scanOrder))) { - bitMap = - bitMap == null ? BitMap.createBitMapDynamically(dataTypeList.size()) : bitMap; - bitMap.mark(columnIndex); + scanOrder); + if (deletedColumns != null) { + deletedColumns[columnIndex] = isDeleted; + } + if (selectedIndices[columnIndex] != -1 && !isDeleted) { + hasNonNull = true; } } - if (bitMap != null && bitMap.isAllMarked()) { + if (ignoreAllNullRows && !dataTypeList.isEmpty() && !hasNonNull) { findValidRow = false; index++; continue; @@ -2295,7 +2318,10 @@ public TimeValuePair nextTimeValuePair() { TsPrimitiveType[] vector = new TsPrimitiveType[dataTypeList.size()]; boolean complete = true; for (int columnIndex = 0; columnIndex < dataTypeList.size(); columnIndex++) { - TsPrimitiveType val = getPrimitiveTypeObject(selectedIndices[columnIndex], columnIndex); + TsPrimitiveType val = + (deletedColumns != null && deletedColumns[columnIndex]) + ? null + : getPrimitiveTypeObject(selectedIndices[columnIndex], columnIndex); vector[columnIndex] = val; if (complete && (val == null @@ -2320,12 +2346,15 @@ public boolean isLastRowComplete() { @Override public TimeValuePair currentTimeValuePair() { - if (!hasCurrent()) { + if (!hasNextTimeValuePair()) { return null; } TsPrimitiveType[] vector = new TsPrimitiveType[dataTypeList.size()]; for (int columnIndex = 0; columnIndex < dataTypeList.size(); columnIndex++) { - vector[columnIndex] = getPrimitiveTypeObject(selectedIndices[columnIndex], columnIndex); + vector[columnIndex] = + (deletedColumns != null && deletedColumns[columnIndex]) + ? null + : getPrimitiveTypeObject(selectedIndices[columnIndex], columnIndex); } return new TimeValuePair( getTime(getScanOrderIndex(index)), @@ -2417,7 +2446,11 @@ public TsBlock nextBatch() { LazyBitMap timeInvalidInfo = null; LazyBitMap timeDuplicatedInfo = null; - int[] deleteCursor = {0}; + int[] deleteCursor = { + (timeColumnDeletion == null || scanOrder.isAscending()) + ? 0 + : (timeColumnDeletion.size() - 1) + }; int startIndex = index; boolean isVerbose = this.getQueryContext().isVerbose(); @@ -2473,7 +2506,16 @@ public TsBlock nextBatch() { for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { int validColumnIndex = columnIndexList.get(columnIndex); - deleteCursor = new int[] {0}; + List valueColumnDeletions = + Objects.isNull(valueColumnsDeletionList) + ? null + : valueColumnsDeletionList.get(columnIndex); + deleteCursor = + new int[] { + (valueColumnDeletions == null || scanOrder.isAscending()) + ? 0 + : (valueColumnDeletions.size() - 1) + }; // Pair of Time and Index Pair lastValidPointIndexForTimeDupCheck = null; if (Objects.nonNull(timeDuplicatedInfo)) { diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/OrderedMultiAlignedTVListIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/OrderedMultiAlignedTVListIterator.java index e6b5afb6ec396..06ba247b052f1 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/OrderedMultiAlignedTVListIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/OrderedMultiAlignedTVListIterator.java @@ -98,7 +98,7 @@ && isPointDeleted( bitMap.mark(columnIndex); } } - if (ignoreAllNullRows && bitMap.isAllMarked()) { + if (ignoreAllNullRows && !tsDataTypeList.isEmpty() && bitMap.isAllMarked()) { iterator.next(); hasNext = false; } @@ -146,7 +146,7 @@ public void encodeBatch(IChunkWriter chunkWriter, BatchEncodeInfo encodeInfo, lo @Override protected int currentIteratorIndex(int columnIndex) { - return iteratorIndex; + return bitMap.isMarked(columnIndex) ? -1 : iteratorIndex; } @Override diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanFuzzDriver.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanFuzzDriver.java new file mode 100644 index 0000000000000..f5a931b83f094 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanFuzzDriver.java @@ -0,0 +1,530 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.db.queryengine.execution.operator.source.SeriesScanUtil; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Row; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.statistics.Statistics; +import org.apache.tsfile.read.common.block.TsBlock; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Ways of driving a {@link SeriesScanUtil}. Each one mirrors the call sequence of one production + * caller, so that the scan is exercised exactly the way an operator exercises it. + */ +public final class SeriesScanFuzzDriver { + + private SeriesScanFuzzDriver() { + // utility class + } + + /** A scan may yield with Optional.empty(), but it may not keep yielding forever. */ + private static final int MAX_YIELDS_IN_A_ROW = 2000; + + /** hasNextPage() must not keep announcing pages that nextPage() does not deliver. */ + private static final int MAX_EMPTY_PAGES_IN_A_ROW = 2000; + + private static final class YieldGuard { + private int yieldsInARow; + + Optional check(Optional result) { + if (result.isPresent()) { + yieldsInARow = 0; + } else if (++yieldsInARow > MAX_YIELDS_IN_A_ROW) { + throw new IllegalStateException( + "scan stopped progressing: a hasNext* call returned Optional.empty() " + + yieldsInARow + + " times in a row"); + } + return result; + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // rows + ///////////////////////////////////////////////////////////////////////////////////////////////// + + public static List rowsOf(TsBlock block, int columnCount) { + List rows = new ArrayList<>(); + if (block == null) { + return rows; + } + for (int i = 0; i < block.getPositionCount(); i++) { + Object[] values = new Object[columnCount]; + for (int c = 0; c < columnCount; c++) { + Column column = block.getColumn(c); + values[c] = column.isNull(i) ? null : column.getTsPrimitiveType(i).getValue(); + } + rows.add(new Row(block.getTimeByIndex(i), values)); + } + return rows; + } + + /** The first position where the two row lists differ, or null when they are equal. */ + public static String firstDifference(List expected, List actual) { + int common = Math.min(expected.size(), actual.size()); + for (int i = 0; i < common; i++) { + Row expectedRow = expected.get(i); + Row actualRow = actual.get(i); + if (expectedRow.time != actualRow.time || !sameValues(expectedRow.values, actualRow.values)) { + return "row " + i + ": expected " + expectedRow + " but got " + actualRow; + } + } + if (expected.size() != actual.size()) { + return "row count: expected " + + expected.size() + + " but got " + + actual.size() + + (expected.size() > common ? "; first missing " + expected.get(common) : "") + + (actual.size() > common ? "; first extra " + actual.get(common) : ""); + } + return null; + } + + private static boolean sameValues(Object[] expected, Object[] actual) { + if (expected.length != actual.length) { + return false; + } + for (int i = 0; i < expected.length; i++) { + Object expectedValue = expected[i]; + Object actualValue = actual[i]; + if (expectedValue == null || actualValue == null) { + if (expectedValue != actualValue) { + return false; + } + } else if (expectedValue instanceof Double || expectedValue instanceof Float) { + if (((Number) expectedValue).doubleValue() != ((Number) actualValue).doubleValue()) { + return false; + } + } else if (!expectedValue.equals(actualValue)) { + return false; + } + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // driver 1: AbstractSeriesScanOperator + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Same loop as {@code AbstractSeriesScanOperator#hasNext}: pages first, then chunks, then files. + */ + public static List scanLikeSeriesScanOperator(SeriesScanUtil util, int columnCount) + throws IOException { + List rows = new ArrayList<>(); + YieldGuard guard = new YieldGuard(); + int emptyPagesInARow = 0; + while (true) { + if (util.hasNextPage()) { + TsBlock block = util.nextPage(); + List blockRows = rowsOf(block, columnCount); + if (blockRows.isEmpty()) { + if (++emptyPagesInARow > MAX_EMPTY_PAGES_IN_A_ROW) { + throw new IllegalStateException( + "hasNextPage() keeps returning true while nextPage() returns no row"); + } + } else { + emptyPagesInARow = 0; + rows.addAll(blockRows); + } + continue; + } + Optional hasNextChunk = guard.check(util.hasNextChunk()); + if (!hasNextChunk.isPresent() || hasNextChunk.get()) { + continue; + } + Optional hasNextFile = guard.check(util.hasNextFile()); + if (!hasNextFile.isPresent() || hasNextFile.get()) { + continue; + } + return rows; + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // driver 2: file -> chunk -> page, checking every "statistics are usable" claim in place + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Walks files, chunks and pages explicitly. Whenever the scan claims that the statistics of the + * current chunk or page are usable, those statistics are compared with the raw rows that the same + * chunk or page actually yields. Nothing is skipped, so the returned rows are the full result of + * the scan. + * + *

Only meaningful without limit and offset, because pagination truncates what a page yields. + */ + public static List scanCheckingStatistics( + SeriesScanUtil util, List types, List problems) throws IOException { + List rows = new ArrayList<>(); + YieldGuard guard = new YieldGuard(); + while (true) { + Optional hasNextFile = guard.check(util.hasNextFile()); + if (!hasNextFile.isPresent()) { + continue; + } + if (!hasNextFile.get()) { + return rows; + } + // hasNextChunk() reports false as soon as the current file has no chunk left, even when a + // later file has some: the aggregation operator then comes back to hasNextFile(). + while (true) { + Optional hasNextChunk = guard.check(util.hasNextChunk()); + if (!hasNextChunk.isPresent()) { + continue; + } + if (!hasNextChunk.get()) { + break; + } + boolean chunkUsable = util.canUseCurrentChunkStatistics(); + boolean chunkTimeUsable = util.canUseCurrentChunkTimeStatistics(); + Agg chunkStatistics = chunkUsable ? readChunkStatistics(util, types) : null; + Agg chunkRaw = new Agg(types); + while (util.hasNextPage()) { + boolean pageUsable = util.canUseCurrentPageStatistics(); + boolean pageTimeUsable = util.canUseCurrentPageTimeStatistics(); + Agg pageStatistics = pageUsable ? readPageStatistics(util, types) : null; + Agg pageRaw = new Agg(types); + List pageRows = rowsOf(util.nextPage(), types.size()); + pageRows.forEach(pageRaw::addRow); + if (pageUsable) { + String mismatch = + pageTimeUsable + ? pageStatistics.mismatch(pageRaw) + : pageStatistics.mismatchValues(pageRaw); + if (mismatch != null) { + problems.add("page statistics claimed usable but " + mismatch); + } + } + rows.addAll(pageRows); + chunkRaw.add(pageRaw); + } + if (chunkUsable) { + String mismatch = + chunkTimeUsable + ? chunkStatistics.mismatch(chunkRaw) + : chunkStatistics.mismatchValues(chunkRaw); + if (mismatch != null) { + problems.add("chunk statistics claimed usable but " + mismatch); + } + } + } + } + } + + /** The statistics the aggregation operator would use instead of reading the current chunk. */ + public static Agg readChunkStatistics(SeriesScanUtil util, List types) { + Agg result = new Agg(types); + result.addTimeStatistics(util.currentChunkTimeStatistics()); + for (int c = 0; c < types.size(); c++) { + result.addValueStatistics(c, util.currentChunkStatistics(c)); + } + return result; + } + + /** The statistics the aggregation operator would use instead of reading the current page. */ + public static Agg readPageStatistics(SeriesScanUtil util, List types) { + Agg result = new Agg(types); + result.addTimeStatistics(util.currentPageTimeStatistics()); + for (int c = 0; c < types.size(); c++) { + result.addValueStatistics(c, util.currentPageStatistics(c)); + } + return result; + } + + /** The statistics the aggregation operator would use instead of reading the current file. */ + public static Agg readFileStatistics(SeriesScanUtil util, List types) { + Agg result = new Agg(types); + result.addTimeStatistics(util.currentFileTimeStatistics()); + for (int c = 0; c < types.size(); c++) { + result.addValueStatistics(c, util.currentFileStatistics(c)); + } + return result; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // driver 3: AbstractSeriesAggregationScanOperator, which skips what statistics can replace + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * Same decisions as {@code AbstractSeriesAggregationScanOperator} for a window covering every + * timestamp: use the file, chunk or page statistics whenever the scan says they are usable, and + * skip the data; otherwise aggregate the raw rows. Returns the aggregate obtained this way. + */ + public static Agg aggregateLikeAggregationScanOperator( + SeriesScanUtil util, List types) throws IOException { + Agg total = new Agg(types); + YieldGuard guard = new YieldGuard(); + while (true) { + if (util.hasNextPage()) { + if (util.canUseCurrentPageTimeStatistics()) { + total.add(readPageStatistics(util, types)); + util.skipCurrentPage(); + } else { + for (Row row : rowsOf(util.nextPage(), types.size())) { + total.addRow(row); + } + } + continue; + } + Optional hasNextChunk = guard.check(util.hasNextChunk()); + if (!hasNextChunk.isPresent() || hasNextChunk.get()) { + if (hasNextChunk.isPresent() + && hasNextChunk.get() + && util.canUseCurrentChunkTimeStatistics()) { + total.add(readChunkStatistics(util, types)); + util.skipCurrentChunk(); + } + continue; + } + Optional hasNextFile = guard.check(util.hasNextFile()); + if (!hasNextFile.isPresent() || hasNextFile.get()) { + if (hasNextFile.isPresent() + && hasNextFile.get() + && util.canUseCurrentFileTimeStatistics()) { + total.add(readFileStatistics(util, types)); + util.skipCurrentFile(); + } + continue; + } + return total; + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // aggregate used to compare statistics with raw rows + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** Count, min and max of the time column, and count, min, max and sum of every value column. */ + public static final class Agg { + private final List types; + private long timeCount; + private long minTime = Long.MAX_VALUE; + private long maxTime = Long.MIN_VALUE; + private final long[] count; + private final Object[] min; + private final Object[] max; + private final double[] sum; + private final boolean[] ordered; + + public Agg(List types) { + this.types = types; + this.count = new long[types.size()]; + this.min = new Object[types.size()]; + this.max = new Object[types.size()]; + this.sum = new double[types.size()]; + this.ordered = new boolean[types.size()]; + for (int c = 0; c < types.size(); c++) { + ordered[c] = isOrdered(types.get(c)); + } + } + + private static boolean isOrdered(TSDataType type) { + switch (type) { + case INT32: + case INT64: + case FLOAT: + case DOUBLE: + return true; + default: + return false; + } + } + + public void addRow(Row row) { + timeCount++; + minTime = Math.min(minTime, row.time); + maxTime = Math.max(maxTime, row.time); + for (int c = 0; c < types.size(); c++) { + Object value = row.values[c]; + if (value == null) { + continue; + } + count[c]++; + if (ordered[c]) { + min[c] = min[c] == null ? value : lesser(min[c], value); + max[c] = max[c] == null ? value : greater(max[c], value); + sum[c] += ((Number) value).doubleValue(); + } + } + } + + public void addTimeStatistics(Statistics statistics) { + if (statistics == null || statistics.isEmpty()) { + return; + } + timeCount += statistics.getCount(); + minTime = Math.min(minTime, statistics.getStartTime()); + maxTime = Math.max(maxTime, statistics.getEndTime()); + } + + public void addValueStatistics(int column, Statistics statistics) { + if (statistics == null || statistics.isEmpty()) { + return; + } + count[column] += statistics.getCount(); + if (ordered[column]) { + Object statisticsMin = statistics.getMinValue(); + Object statisticsMax = statistics.getMaxValue(); + min[column] = min[column] == null ? statisticsMin : lesser(min[column], statisticsMin); + max[column] = max[column] == null ? statisticsMax : greater(max[column], statisticsMax); + sum[column] += statistics.getSumDoubleValue(); + } + } + + public void add(Agg other) { + timeCount += other.timeCount; + minTime = Math.min(minTime, other.minTime); + maxTime = Math.max(maxTime, other.maxTime); + for (int c = 0; c < types.size(); c++) { + count[c] += other.count[c]; + if (ordered[c]) { + min[c] = + other.min[c] == null + ? min[c] + : min[c] == null ? other.min[c] : lesser(min[c], other.min[c]); + max[c] = + other.max[c] == null + ? max[c] + : max[c] == null ? other.max[c] : greater(max[c], other.max[c]); + sum[c] += other.sum[c]; + } + } + } + + @SuppressWarnings("unchecked") + private static Object lesser(Object a, Object b) { + return ((Comparable) a).compareTo(b) <= 0 ? a : b; + } + + @SuppressWarnings("unchecked") + private static Object greater(Object a, Object b) { + return ((Comparable) a).compareTo(b) >= 0 ? a : b; + } + + /** Why {@code raw} (or any other aggregate) differs from this one; null when they agree. */ + public String mismatch(Agg other) { + StringBuilder sb = new StringBuilder(); + if (timeCount != other.timeCount) { + sb.append("time count ") + .append(timeCount) + .append(" != ") + .append(other.timeCount) + .append("; "); + } + if (timeCount > 0 && (minTime != other.minTime || maxTime != other.maxTime)) { + sb.append("time range [") + .append(minTime) + .append(", ") + .append(maxTime) + .append("] != [") + .append(other.minTime) + .append(", ") + .append(other.maxTime) + .append("]; "); + } + appendValueMismatches(other, sb); + return sb.length() == 0 ? null : sb.toString(); + } + + /** Why value-column aggregates differ from {@code other}; ignores time-column count/range. */ + public String mismatchValues(Agg other) { + StringBuilder sb = new StringBuilder(); + appendValueMismatches(other, sb); + return sb.length() == 0 ? null : sb.toString(); + } + + private void appendValueMismatches(Agg other, StringBuilder sb) { + for (int c = 0; c < types.size(); c++) { + if (count[c] != other.count[c]) { + sb.append("column ") + .append(c) + .append(" count ") + .append(count[c]) + .append(" != ") + .append(other.count[c]) + .append("; "); + } + if (!ordered[c] || count[c] == 0) { + continue; + } + if (min[c] != other.min[c] && (min[c] == null || !min[c].equals(other.min[c]))) { + sb.append("column ") + .append(c) + .append(" min ") + .append(min[c]) + .append(" != ") + .append(other.min[c]) + .append("; "); + } + if (max[c] != other.max[c] && (max[c] == null || !max[c].equals(other.max[c]))) { + sb.append("column ") + .append(c) + .append(" max ") + .append(max[c]) + .append(" != ") + .append(other.max[c]) + .append("; "); + } + if (Math.abs(sum[c] - other.sum[c]) > 1e-6 * Math.max(1.0, Math.abs(sum[c]))) { + sb.append("column ") + .append(c) + .append(" sum ") + .append(sum[c]) + .append(" != ") + .append(other.sum[c]) + .append("; "); + } + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("rows=") + .append(timeCount) + .append(" time=[") + .append(minTime) + .append(", ") + .append(maxTime) + .append(']'); + for (int c = 0; c < types.size(); c++) { + sb.append(" col").append(c).append("{count=").append(count[c]); + if (ordered[c]) { + sb.append(", min=") + .append(min[c]) + .append(", max=") + .append(max[c]) + .append(", sum=") + .append(sum[c]); + } + sb.append('}'); + } + return sb.toString(); + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanKnownIssues.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanKnownIssues.java new file mode 100644 index 0000000000000..71d958a5763d0 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanKnownIssues.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.FileNode; + +/** + * Shapes of scenarios that exercise non-production states not expected to pass. {@code + * SeriesScanUtilFuzzTest} leaves them out by default; {@code scan_strict=1} runs them anyway. + */ +public final class SeriesScanKnownIssues { + + /** Whether every check has to run, non-production shapes included. */ + public static final boolean STRICT = option("scan_strict", 0) == 1; + + private SeriesScanKnownIssues() { + // utility class + } + + /** + * MEMORY_CHUNKS_OF_ONE_FILE_UNORDERED: two memory tables in a single open file share one + * MergeReaderPriority. Unreachable in production because DirectFlushPolicy closes the + * TsFileProcessor immediately rather than calling asyncFlush(). + */ + public static boolean memoryChunksOfOneFileUnordered(SeriesScanScenario scenario) { + for (FileNode file : scenario.files) { + if (file.memChunks.size() > 1) { + return true; + } + } + return false; + } + + /** Scenarios skipped by default; every driver is skipped for them. */ + public static boolean scenarioHitsKnownDefect(SeriesScanScenario scenario) { + return !STRICT && memoryChunksOfOneFileUnordered(scenario); + } + + /** Scenarios whose statistics checks are skipped by default. */ + public static boolean statisticsHitKnownDefect(SeriesScanScenario scenario) { + return !STRICT && scenarioHitsKnownDefect(scenario); + } + + /** Surefire does not forward -D options to the test JVM, so the environment is read as well. */ + private static int option(String name, int defaultValue) { + String value = System.getProperty(name); + if (value == null) { + value = System.getenv(name); + } + return value == null ? defaultValue : Integer.parseInt(value.trim()); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanMaterializer.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanMaterializer.java new file mode 100644 index 0000000000000..7796694e2991b --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanMaterializer.java @@ -0,0 +1,666 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.commons.conf.IoTDBConstant; +import org.apache.iotdb.commons.exception.IllegalPathException; +import org.apache.iotdb.commons.path.AlignedFullPath; +import org.apache.iotdb.commons.path.AlignedPath; +import org.apache.iotdb.commons.path.IFullPath; +import org.apache.iotdb.commons.path.MeasurementPath; +import org.apache.iotdb.commons.path.NonAlignedFullPath; +import org.apache.iotdb.commons.path.PartialPath; +import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.FileNode; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.MemChunk; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Row; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Source; +import org.apache.iotdb.db.storageengine.buffer.BloomFilterCache; +import org.apache.iotdb.db.storageengine.buffer.ChunkCache; +import org.apache.iotdb.db.storageengine.buffer.TimeSeriesMetadataCache; +import org.apache.iotdb.db.storageengine.dataregion.memtable.AlignedReadOnlyMemChunk; +import org.apache.iotdb.db.storageengine.dataregion.memtable.ReadOnlyMemChunk; +import org.apache.iotdb.db.storageengine.dataregion.modification.ModificationFile; +import org.apache.iotdb.db.storageengine.dataregion.modification.TreeDeletionEntry; +import org.apache.iotdb.db.storageengine.dataregion.read.control.FileReaderManager; +import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource; +import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResourceStatus; +import org.apache.iotdb.db.storageengine.dataregion.tsfile.generator.TsFileNameGenerator; +import org.apache.iotdb.db.utils.datastructure.AlignedTVList; +import org.apache.iotdb.db.utils.datastructure.TVList; + +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.common.conf.TSFileDescriptor; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.AlignedChunkMetadata; +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.TableDeviceChunkMetadata; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.apache.tsfile.read.common.TimeRange; +import org.apache.tsfile.utils.Binary; +import org.apache.tsfile.write.chunk.AlignedChunkWriterImpl; +import org.apache.tsfile.write.chunk.ChunkWriterImpl; +import org.apache.tsfile.write.page.PageWriter; +import org.apache.tsfile.write.page.TimePageWriter; +import org.apache.tsfile.write.page.ValuePageWriter; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.apache.tsfile.write.schema.VectorMeasurementSchema; +import org.apache.tsfile.write.writer.RestorableTsFileIOWriter; +import org.apache.tsfile.write.writer.TsFileIOWriter; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.apache.tsfile.common.constant.TsFileConstant.TIME_COLUMN_ID; +import static org.apache.tsfile.read.common.TimeRange.sortAndMerge; + +/** + * Turns a {@link SeriesScanScenario} into what the storage engine hands to a scan: closed TsFiles + * with their modification files, and snapshots of open files holding flushed chunks and memory + * chunks. + */ +public final class SeriesScanMaterializer { + + public static final String DATABASE = "root.sg_scan"; + public static final String DEVICE = DATABASE + ".d1"; + public static final IDeviceID DEVICE_ID = IDeviceID.Factory.DEFAULT_FACTORY.create(DEVICE); + public static final String MEASUREMENT = "s0"; + + private static final TSEncoding[] NUMERIC_ENCODINGS = { + TSEncoding.PLAIN, TSEncoding.RLE, TSEncoding.TS_2DIFF, TSEncoding.GORILLA + }; + private static final CompressionType[] COMPRESSIONS = { + CompressionType.UNCOMPRESSED, CompressionType.SNAPPY, CompressionType.LZ4 + }; + + private SeriesScanMaterializer() { + // utility class + } + + /** Everything a scan needs, plus what has to be released afterwards. */ + public static final class Handle implements AutoCloseable { + public final SeriesScanScenario scenario; + public final FragmentInstanceContext context; + + /** The scanned path: the queried sensors, in the queried order. */ + public final IFullPath path; + + /** + * The queried sensors, which is what a memory chunk is described by (see {@code + * ResourceByPathUtils#getMeasurementSchema}); its column index list then maps them to the + * stored columns. + */ + public final VectorMeasurementSchema vectorSchema; + + private final Path dir; + private final List seqResources = new ArrayList<>(); + private final List unseqResources = new ArrayList<>(); + + /** Writers of open files that hold flushed chunks. They stay open until the scan is done. */ + private final List openWriters = new ArrayList<>(); + + private final int oldMaxPointsInPage; + + private Handle( + SeriesScanScenario scenario, + FragmentInstanceContext context, + Path dir, + int oldMaxPointsInPage) { + this.scenario = scenario; + this.context = context; + this.dir = dir; + this.oldMaxPointsInPage = oldMaxPointsInPage; + List queriedSchemas = new ArrayList<>(); + for (int storedColumn : scenario.queriedColumns) { + queriedSchemas.add( + new MeasurementSchema( + measurement(storedColumn), scenario.storedTypes.get(storedColumn))); + } + this.path = + scenario.aligned() + ? new AlignedFullPath(DEVICE_ID, measurements(), queriedSchemas) + : new NonAlignedFullPath(DEVICE_ID, queriedSchemas.get(0)); + List queriedTypes = new ArrayList<>(); + List plainEncodings = new ArrayList<>(); + for (int column = 0; column < scenario.columnCount(); column++) { + queriedTypes.add(scenario.columnType(column)); + // PLAIN keeps float and double values exact, which the oracle relies on. + plainEncodings.add(TSEncoding.PLAIN); + } + this.vectorSchema = + new VectorMeasurementSchema( + AlignedPath.VECTOR_PLACEHOLDER, + measurements().toArray(new String[0]), + queriedTypes.toArray(new TSDataType[0]), + plainEncodings.toArray(new TSEncoding[0])); + } + + public List seqResources() { + return seqResources; + } + + public List unseqResources() { + return unseqResources; + } + + /** The sensors the scan reads, in the order of the value columns it returns. */ + public List measurements() { + List result = new ArrayList<>(); + for (int storedColumn : scenario.queriedColumns) { + result.add(measurement(storedColumn)); + } + return result; + } + + @Override + public void close() throws Exception { + for (RestorableTsFileIOWriter writer : openWriters) { + writer.close(); + } + FileReaderManager.getInstance().closeAndRemoveAllOpenedReaders(); + ChunkCache.getInstance().clear(); + TimeSeriesMetadataCache.getInstance().clear(); + BloomFilterCache.getInstance().clear(); + TSFileDescriptor.getInstance().getConfig().setMaxNumberOfPointsInPage(oldMaxPointsInPage); + try (Stream paths = Files.walk(dir)) { + paths.sorted(Comparator.reverseOrder()).forEach(SeriesScanMaterializer::deleteQuietly); + } + } + } + + public static String measurement(int storedColumn) { + return "s" + storedColumn; + } + + private static void deleteQuietly(Path path) { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + // a leftover temporary file is harmless + } + } + + public static Handle materialize(SeriesScanScenario scenario, FragmentInstanceContext context) + throws Exception { + int oldMaxPointsInPage = + TSFileDescriptor.getInstance().getConfig().getMaxNumberOfPointsInPage(); + // A small page bound makes memory chunks split into several fake pages and bounds the batch + // the merge reader produces, both of which need very large inputs with the default value. + if (scenario.config.smallPage) { + TSFileDescriptor.getInstance().getConfig().setMaxNumberOfPointsInPage(2); + } + Path dir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "scan-"); + Handle handle = new Handle(scenario, context, dir, oldMaxPointsInPage); + try { + for (int i = 0; i < scenario.files.size(); i++) { + FileNode file = scenario.files.get(i); + Path fileDir = + dir.resolve("data") + .resolve(DATABASE) + .resolve(file.seq ? "sequence" : "unsequence") + .resolve("0") + .resolve("0"); + Files.createDirectories(fileDir); + File tsFile = + new File( + TsFileNameGenerator.generateNewTsFilePath( + fileDir.toString(), file.fileTimestamp, file.version, 0, 0)); + TsFileResource resource = new TsFileResource(tsFile); + resource.setVersion(file.version); + if (file.open) { + buildOpenFile(handle, file, resource); + } else { + writeClosedFile(handle, file, resource, i); + } + } + } catch (Exception e) { + handle.close(); + throw e; + } + // The storage engine hands sequence files over in time order, the file still being written + // last. The generator creates them in a different order on purpose (versions are independent). + List seq = handle.seqResources(); + seq.sort( + (a, b) -> { + if (a.isClosed() != b.isClosed()) { + return a.isClosed() ? -1 : 1; + } + if (!a.isClosed()) { + return Long.compare(a.getVersion(), b.getVersion()); + } + return Long.compare( + a.getStartTime(DEVICE_ID).orElse(Long.MAX_VALUE), + b.getStartTime(DEVICE_ID).orElse(Long.MAX_VALUE)); + }); + return handle; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // closed files + ///////////////////////////////////////////////////////////////////////////////////////////////// + + private static void writeClosedFile( + Handle handle, FileNode file, TsFileResource resource, int fileIndex) + throws IOException, IllegalPathException { + try (TsFileIOWriter writer = new TsFileIOWriter(resource.getTsFile())) { + writeChunks(handle, writer, file.diskChunks, fileIndex); + writer.endFile(); + } + // a file without any row for the device simply has no entry in the device index + List rows = SeriesScanScenario.rowsOf(file); + if (!rows.isEmpty()) { + updateTimes(resource, rows); + } + resource.setStatusForTest(TsFileResourceStatus.NORMAL); + writeMods(handle, file, resource); + (file.seq ? handle.seqResources() : handle.unseqResources()).add(resource); + } + + /** Writes one chunk group holding the chunks, if any. */ + private static void writeChunks( + Handle handle, TsFileIOWriter writer, List chunks, int fileIndex) throws IOException { + if (chunks.isEmpty()) { + return; + } + writer.startChunkGroup(DEVICE_ID); + boolean[] present = presentColumns(handle.scenario, chunks); + for (Source chunk : chunks) { + if (handle.scenario.aligned()) { + writeAlignedChunk(handle, writer, chunk, fileIndex, present); + } else { + writeNonAlignedChunk(handle, writer, chunk, fileIndex); + } + } + writer.endChunkGroup(); + } + + /** The device index of the resource spans every row it holds. */ + private static void updateTimes(TsFileResource resource, List rows) { + resource.updateStartTime(DEVICE_ID, rows.get(0).time); + resource.updateEndTime(DEVICE_ID, rows.get(rows.size() - 1).time); + } + + /** + * Columns that exist in the chunk group. A flush writes every row of every column the device has + * written since the file was created, with a null bitmap where the value is missing, so a column + * is either present in every chunk group of the file or in none of them. Deciding that per chunk + * instead would misalign the chunk lists and break the reader, which pairs the chunks of the + * value columns with the chunks of the time column by index. + */ + private static boolean[] presentColumns(SeriesScanScenario scenario, List chunks) { + boolean[] present = new boolean[scenario.storedTypes.size()]; + for (Source chunk : chunks) { + for (Row row : chunk.rows()) { + for (int c = 0; c < present.length; c++) { + present[c] |= row.values[c] != null; + } + } + } + return present; + } + + private static void writeNonAlignedChunk( + Handle handle, TsFileIOWriter writer, Source chunk, int fileIndex) throws IOException { + TSDataType type = handle.scenario.storedTypes.get(0); + TSEncoding encoding = + type == TSDataType.STRING || type == TSDataType.BOOLEAN + ? TSEncoding.PLAIN + : NUMERIC_ENCODINGS[fileIndex % NUMERIC_ENCODINGS.length]; + ChunkWriterImpl chunkWriter = + new ChunkWriterImpl( + new MeasurementSchema( + MEASUREMENT, type, encoding, COMPRESSIONS[fileIndex % COMPRESSIONS.length])); + PageWriter pageWriter = chunkWriter.getPageWriter(); + for (List page : chunk.pages) { + for (Row row : page) { + writePoint(pageWriter, row.time, row.values[0], type); + } + chunkWriter.sealCurrentPage(); + } + chunkWriter.writeToFileWriter(writer); + } + + private static void writeAlignedChunk( + Handle handle, TsFileIOWriter writer, Source chunk, int fileIndex, boolean[] present) + throws IOException { + SeriesScanScenario scenario = handle.scenario; + TSFileConfig config = TSFileDescriptor.getInstance().getConfig(); + MeasurementSchema timeSchema = + new MeasurementSchema( + TIME_COLUMN_ID, + config.getTimeSeriesDataType(), + TSEncoding.valueOf(config.getTimeEncoder()), + COMPRESSIONS[fileIndex % COMPRESSIONS.length]); + List valueSchemas = new ArrayList<>(); + for (int c = 0; c < present.length; c++) { + if (present[c]) { + TSDataType type = scenario.storedTypes.get(c); + TSEncoding encoding = + type == TSDataType.STRING || type == TSDataType.BOOLEAN + ? TSEncoding.PLAIN + : NUMERIC_ENCODINGS[(fileIndex + c) % NUMERIC_ENCODINGS.length]; + valueSchemas.add( + new MeasurementSchema( + measurement(c), + type, + encoding, + COMPRESSIONS[(fileIndex + c) % COMPRESSIONS.length])); + } + } + AlignedChunkWriterImpl chunkWriter = new AlignedChunkWriterImpl(timeSchema, valueSchemas); + for (List page : chunk.pages) { + TimePageWriter timePageWriter = chunkWriter.getTimeChunkWriter().getPageWriter(); + for (Row row : page) { + timePageWriter.write(row.time); + } + chunkWriter.getTimeChunkWriter().sealCurrentPage(); + int written = 0; + for (int c = 0; c < present.length; c++) { + if (!present[c]) { + continue; + } + ValuePageWriter valuePageWriter = + chunkWriter.getValueChunkWriterList().get(written++).getPageWriter(); + for (Row row : page) { + writeValue(valuePageWriter, row.time, row.values[c], scenario.storedTypes.get(c)); + } + chunkWriter.getValueChunkWriterList().get(written - 1).sealCurrentPage(); + } + } + chunkWriter.writeToFileWriter(writer); + } + + private static void writePoint(PageWriter pageWriter, long time, Object value, TSDataType type) { + switch (type) { + case INT32: + pageWriter.write(time, (Integer) value); + break; + case INT64: + pageWriter.write(time, (Long) value); + break; + case FLOAT: + pageWriter.write(time, (Float) value); + break; + case DOUBLE: + pageWriter.write(time, (Double) value); + break; + case BOOLEAN: + pageWriter.write(time, (Boolean) value); + break; + case STRING: + case TEXT: + case BLOB: + pageWriter.write(time, (Binary) value); + break; + default: + throw new UnsupportedOperationException("Unsupported type " + type); + } + } + + private static void writeValue( + ValuePageWriter pageWriter, long time, Object value, TSDataType type) { + switch (type) { + case INT32: + pageWriter.write(time, value == null ? 0 : (Integer) value, value == null); + break; + case INT64: + pageWriter.write(time, value == null ? 0L : (Long) value, value == null); + break; + case FLOAT: + pageWriter.write(time, value == null ? 0f : (Float) value, value == null); + break; + case DOUBLE: + pageWriter.write(time, value == null ? 0d : (Double) value, value == null); + break; + case BOOLEAN: + pageWriter.write(time, value != null && (Boolean) value, value == null); + break; + case STRING: + case TEXT: + case BLOB: + pageWriter.write(time, value == null ? Binary.EMPTY_VALUE : (Binary) value, value == null); + break; + default: + throw new UnsupportedOperationException("Unsupported type " + type); + } + } + + private static void writeMods(Handle handle, FileNode file, TsFileResource resource) + throws IOException, IllegalPathException { + SeriesScanScenario scenario = handle.scenario; + boolean hasValueDeletion = + scenario.aligned() && file.valueDeletions.stream().anyMatch(range -> !range.isEmpty()); + if (file.timeDeletions.isEmpty() && !hasValueDeletion) { + return; + } + try (ModificationFile modFile = resource.getModFileForWrite()) { + for (TimeRange range : file.timeDeletions) { + modFile.write( + new TreeDeletionEntry( + wholeRowDeletionPath(scenario.aligned()), range.getMin(), range.getMax())); + } + if (scenario.aligned()) { + for (int c = 0; c < scenario.storedTypes.size() && c < file.valueDeletions.size(); c++) { + for (TimeRange range : file.valueDeletions.get(c)) { + modFile.write( + new TreeDeletionEntry( + deletionPath(measurement(c)), range.getMin(), range.getMax())); + } + } + } + } + } + + /** + * Same construction as CompactionPathUtils#getPath: the device path plus the measurement. It + * survives the trip through the modification file, which a plain path with an empty measurement + * does not: TreeDeletionEntry re-splits the path on "." and Java drops trailing empty strings. + */ + private static MeasurementPath deletionPath(String measurement) throws IllegalPathException { + return new PartialPath(DEVICE.split("\\.")).concatAsMeasurementPath(measurement); + } + + /** + * The entry that deletes whole rows, as the storage engine writes it (see {@code + * CompactionUtils#convertTtlToDeletion}): "device.*" for an aligned device, whose "*" also + * matches the time column, or the series itself otherwise. + */ + private static MeasurementPath wholeRowDeletionPath(boolean aligned) throws IllegalPathException { + return aligned + ? new MeasurementPath(DEVICE_ID, IoTDBConstant.ONE_LEVEL_PATH_WILDCARD) + : deletionPath(MEASUREMENT); + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // open files: flushed chunks and memory chunks + ///////////////////////////////////////////////////////////////////////////////////////////////// + + private static void buildOpenFile(Handle handle, FileNode file, TsFileResource origin) + throws Exception { + updateTimes(origin, SeriesScanScenario.rowsOf(file)); + + List flushedChunkMetadata = new ArrayList<>(); + if (!file.diskChunks.isEmpty()) { + // The writer stays open, like the one of a file that is still being written to; its + // flushed chunks can be read at their offsets all the same. + RestorableTsFileIOWriter writer = new RestorableTsFileIOWriter(origin.getTsFile()); + handle.openWriters.add(writer); + writeChunks(handle, writer, file.diskChunks, (int) file.version); + writer.makeMetadataVisible(); + flushedChunkMetadata = visibleChunkMetadata(handle, writer); + } + List memChunks = new ArrayList<>(); + for (int index = 0; index < file.memChunks.size(); index++) { + memChunks.add(buildMemChunk(handle, file, index)); + } + // The same shape as TsFileProcessor#query: the path maps to the flushed chunk metadata, which + // may be empty, and to the memory chunks. + Map> memChunkMap = new HashMap<>(); + memChunkMap.put(handle.path, memChunks); + Map> chunkMetadataMap = new HashMap<>(); + chunkMetadataMap.put(handle.path, flushedChunkMetadata); + TsFileResource snapshot = new TsFileResource(memChunkMap, chunkMetadataMap, origin); + (file.seq ? handle.seqResources() : handle.unseqResources()).add(snapshot); + } + + /** + * Same assembly as ResourceByPathUtils#getVisibleMetadataListFromWriter: one entry per chunk of + * the time column, whose value chunk list follows the queried sensors. + */ + private static List visibleChunkMetadata( + Handle handle, RestorableTsFileIOWriter writer) { + SeriesScanScenario scenario = handle.scenario; + if (!scenario.aligned()) { + return new ArrayList<>( + writer.getVisibleMetadataList(DEVICE_ID, MEASUREMENT, scenario.storedTypes.get(0))); + } + List> valueChunkMetadataList = new ArrayList<>(); + for (int column = 0; column < scenario.columnCount(); column++) { + String measurement = measurement(scenario.queriedColumns.get(column)); + valueChunkMetadataList.add( + writer.getVisibleMetadataList(DEVICE_ID, measurement, scenario.columnType(column))); + } + List result = new ArrayList<>(); + List timeChunkMetadataList = + writer.getVisibleMetadataList(DEVICE_ID, AlignedPath.VECTOR_PLACEHOLDER, TSDataType.VECTOR); + for (int i = 0; i < timeChunkMetadataList.size(); i++) { + List valueChunkMetadata = new ArrayList<>(); + // false when none of the queried sensors has a point in this chunk + boolean exists = false; + for (List chunkMetadata : valueChunkMetadataList) { + boolean currentExists = + i < chunkMetadata.size() && chunkMetadata.get(i).getNumOfPoints() > 0; + exists |= currentExists; + valueChunkMetadata.add(currentExists ? chunkMetadata.get(i) : null); + } + if (!scenario.ignoreAllNullRows() || exists) { + result.add( + scenario.ignoreAllNullRows() + ? new AlignedChunkMetadata(timeChunkMetadataList.get(i), valueChunkMetadata) + : new TableDeviceChunkMetadata(timeChunkMetadataList.get(i), valueChunkMetadata)); + } + } + return result; + } + + /** + * The deletions a query on memory table {@code index} sees. A flushing memory table is immutable, + * so a deletion that arrives meanwhile is only recorded (see {@code + * TsFileProcessor#deleteDataInMemory}); {@code ModificationUtils#getModificationsForMemtable} + * then hands it to that memory table and to every older one. + */ + private static ReadOnlyMemChunk buildMemChunk(Handle handle, FileNode file, int index) + throws Exception { + MemChunk memChunk = file.memChunks.get(index); + SeriesScanScenario scenario = handle.scenario; + int storedCount = scenario.storedTypes.size(); + List timeDeletions = new ArrayList<>(); + List> valueDeletions = new ArrayList<>(); + for (int c = 0; c < storedCount; c++) { + valueDeletions.add(new ArrayList<>()); + } + for (int newer = index; newer < file.memChunks.size(); newer++) { + MemChunk source = file.memChunks.get(newer); + timeDeletions.addAll(source.timeDeletions); + for (int c = 0; c < storedCount && c < source.valueDeletions.size(); c++) { + valueDeletions.get(c).addAll(source.valueDeletions.get(c)); + } + } + timeDeletions = sortAndMerge(timeDeletions); + for (int c = 0; c < valueDeletions.size(); c++) { + valueDeletions.set(c, sortAndMerge(valueDeletions.get(c))); + } + + Map tvListQueryMap = new LinkedHashMap<>(); + if (!scenario.aligned()) { + TSDataType type = scenario.storedTypes.get(0); + for (Source tvList : memChunk.tvLists) { + TVList list = TVList.newList(type); + for (Row row : tvList.rows()) { + putPoint(list, row.time, row.values[0], type); + } + list.sort(); + tvListQueryMap.put(list, list.rowCount()); + } + return new ReadOnlyMemChunk( + handle.context, MEASUREMENT, type, TSEncoding.PLAIN, tvListQueryMap, null, timeDeletions); + } + for (Source tvList : memChunk.tvLists) { + AlignedTVList list = AlignedTVList.newAlignedList(new ArrayList<>(scenario.storedTypes)); + for (Row row : tvList.rows()) { + list.putAlignedValue(row.time, row.values); + } + list.sort(); + tvListQueryMap.put(list, list.rowCount()); + } + List> queriedValueDeletions = new ArrayList<>(scenario.columnCount()); + for (int c = 0; c < scenario.columnCount(); c++) { + queriedValueDeletions.add(valueDeletions.get(scenario.queriedColumns.get(c))); + } + return new AlignedReadOnlyMemChunk( + handle.context, + new ArrayList<>(scenario.queriedColumns), + handle.vectorSchema, + tvListQueryMap, + timeDeletions, + queriedValueDeletions); + } + + private static void putPoint(TVList list, long time, Object value, TSDataType type) { + switch (type) { + case INT32: + list.putInt(time, (Integer) value); + break; + case INT64: + list.putLong(time, (Long) value); + break; + case FLOAT: + list.putFloat(time, (Float) value); + break; + case DOUBLE: + list.putDouble(time, (Double) value); + break; + case BOOLEAN: + list.putBoolean(time, (Boolean) value); + break; + case STRING: + case TEXT: + case BLOB: + list.putBinary(time, (Binary) value); + break; + default: + throw new UnsupportedOperationException("Unsupported type " + type); + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenario.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenario.java new file mode 100644 index 0000000000000..4d8335cb8b8c3 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenario.java @@ -0,0 +1,1083 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering; + +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.TimeRange; +import org.apache.tsfile.read.filter.basic.Filter; +import org.apache.tsfile.read.filter.factory.FilterFactory; +import org.apache.tsfile.read.filter.factory.TimeFilterApi; +import org.apache.tsfile.read.filter.factory.ValueFilterApi; +import org.apache.tsfile.utils.Binary; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * In-memory description of one scan scenario and a brute-force oracle for its expected result. + * + *

A scenario is a set of files. Every file holds sources of points: an on-disk chunk, or one + * TVList inside a memory chunk. Each source is an independent writer with its own priority. A + * closed file only has on-disk chunks, whose deletions live in the file's modification entries. An + * open file may start with chunks that were already flushed to disk, followed by one or two memory + * tables; a deletion that arrives while a memory table is flushing is handed to it and to every + * older one. + * + *

The oracle is intentionally naive: it walks every timestamp, asks every source whether it has + * a point there, and resolves conflicts by priority. + */ +public final class SeriesScanScenario { + + public enum Model { + NON_ALIGNED, + ALIGNED_TREE, + ALIGNED_TABLE + } + + /** Knobs of the generator that are not part of the data itself. */ + public static final class Config { + /** Shrinks the page bound, so that memory chunks split into several fake pages. */ + public boolean smallPage = false; + + /** Lets an open unordered file hold a flushing and a working memory table at once. */ + public boolean multipleMemChunks = false; + + /** Lets an open file hold flushed chunks in front of its memory tables. */ + public boolean flushedChunks = false; + + /** Lets an aligned scan select a subset of the sensors stored for the device. */ + public boolean subsetSensors = false; + + public boolean deletions = true; + public boolean filters = true; + public boolean pagination = true; + } + + /** One row of the device. A null element means "no value in this column". */ + public static final class Row { + public final long time; + public final Object[] values; + + public Row(long time, Object[] values) { + this.time = time; + this.values = values; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder().append(time).append(":["); + for (int i = 0; i < values.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(values[i]); + } + return sb.append(']').toString(); + } + } + + /** One writer: an on-disk chunk, or one TVList of a memory chunk. */ + public static final class Source { + public final FileNode file; + + /** -1 for an on-disk chunk, otherwise the index of the memory chunk inside its file. */ + public final int memChunkIndex; + + /** Chunk order inside the file, or TVList order inside the memory chunk (older is smaller). */ + public final int rank; + + /** On-disk: one list per page. Memory: a single list holding every row. */ + public final List> pages = new ArrayList<>(); + + private final Map byTime = new HashMap<>(); + private List rows; + + public Source(FileNode file, int memChunkIndex, int rank) { + this.file = file; + this.memChunkIndex = memChunkIndex; + this.rank = rank; + } + + public void addRow(Row row) { + if (pages.isEmpty()) { + pages.add(new ArrayList<>()); + } + pages.get(pages.size() - 1).add(row); + byTime.put(row.time, row); + rows = null; + } + + public void startNewPage() { + if (pages.isEmpty() || !pages.get(pages.size() - 1).isEmpty()) { + pages.add(new ArrayList<>()); + } + } + + public Row rowAt(long time) { + return byTime.get(time); + } + + public List rows() { + if (rows == null) { + List result = new ArrayList<>(); + for (List page : pages) { + result.addAll(page); + } + rows = Collections.unmodifiableList(result); + } + return rows; + } + + public String kind() { + return memChunkIndex < 0 ? "diskChunk" : "mem" + memChunkIndex + ".tv" + rank; + } + } + + /** The part of an open file that lives in one memory table. */ + public static final class MemChunk { + /** Older TVLists first. */ + public final List tvLists = new ArrayList<>(); + + /** Deletions recorded while this memory table was the newest flushing one. */ + public List timeDeletions = new ArrayList<>(); + + public List> valueDeletions = new ArrayList<>(); + } + + public static final class FileNode { + public final boolean seq; + public final boolean open; + public final long version; + + /** Timestamp in the TsFile name. Memory chunks do not use it: they rank as Long.MAX_VALUE. */ + public final long fileTimestamp; + + public final int ordinal; + + /** Closed file: every chunk. Open file: the chunks flushed before the memory tables. */ + public final List diskChunks = new ArrayList<>(); + + public final List memChunks = new ArrayList<>(); + + /** Time-column deletions (aligned) or whole-series deletions (non-aligned), closed files. */ + public List timeDeletions = new ArrayList<>(); + + /** Per-column value deletions of a closed file. Empty for a non-aligned series. */ + public List> valueDeletions = new ArrayList<>(); + + public FileNode(boolean seq, boolean open, long version, long fileTimestamp, int ordinal) { + this.seq = seq; + this.open = open; + this.version = version; + this.fileTimestamp = fileTimestamp; + this.ordinal = ordinal; + } + + public String name() { + return (seq ? "seq" : "unseq") + (open ? "-open" : "") + "#" + ordinal + "(v" + version + ")"; + } + } + + public final Model model; + public final Ordering ordering; + + /** Type of every column stored for the device. */ + public final List storedTypes; + + /** Indices, ascending, of the stored columns the scan reads. */ + public final List queriedColumns; + + public final List files = new ArrayList<>(); + public Filter globalTimeFilter; + public Filter pushDownFilter; + public long limit; + public long offset; + + /** Aligned only: whether the scan selects the device with a wildcard ("d.*"). */ + public boolean queryAllSensors; + + /** The seed the generator was driven with; only used in reports. */ + public long seed; + + public final Config config; + + private SeriesScanScenario( + Model model, + Ordering ordering, + List storedTypes, + List queriedColumns, + Config config) { + this.model = model; + this.ordering = ordering; + this.storedTypes = storedTypes; + this.queriedColumns = queriedColumns; + this.config = config; + } + + public boolean aligned() { + return model != Model.NON_ALIGNED; + } + + public boolean ignoreAllNullRows() { + return model != Model.ALIGNED_TABLE; + } + + /** Number of value columns the scan returns. */ + public int columnCount() { + return queriedColumns.size(); + } + + public TSDataType columnType(int column) { + return storedTypes.get(queriedColumns.get(column)); + } + + /** Types of the value columns the scan returns. */ + public List columnTypes() { + List result = new ArrayList<>(); + for (int column = 0; column < columnCount(); column++) { + result.add(columnType(column)); + } + return result; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // generator + ///////////////////////////////////////////////////////////////////////////////////////////////// + + private static final TSDataType[] VALUE_TYPES = { + TSDataType.INT32, + TSDataType.INT64, + TSDataType.FLOAT, + TSDataType.DOUBLE, + TSDataType.BOOLEAN, + TSDataType.STRING + }; + + public static Object randomValue(Random rnd, TSDataType type) { + switch (type) { + case INT32: + return rnd.nextInt(200); + case INT64: + return (long) rnd.nextInt(200); + case FLOAT: + return (float) (rnd.nextInt(2000) / 10.0); + case DOUBLE: + return rnd.nextInt(2000) / 10.0; + case BOOLEAN: + return rnd.nextBoolean(); + case STRING: + return new Binary("v" + rnd.nextInt(30), TSFileConfig.STRING_CHARSET); + default: + throw new UnsupportedOperationException("Unsupported type " + type); + } + } + + private static T pick(Random rnd, T... items) { + return items[rnd.nextInt(items.length)]; + } + + public static SeriesScanScenario generate( + Random rnd, Model model, Ordering ordering, Config config) { + List storedTypes = new ArrayList<>(); + int storedCount = model == Model.NON_ALIGNED ? 1 : pick(rnd, 1, 2, 2, 3); + for (int i = 0; i < storedCount; i++) { + storedTypes.add(pick(rnd, VALUE_TYPES)); + } + List queriedColumns = new ArrayList<>(); + boolean subset = + model != Model.NON_ALIGNED + && config.subsetSensors + && storedCount > 1 + && rnd.nextInt(2) == 0; + for (int c = 0; c < storedCount; c++) { + if (!subset || rnd.nextBoolean()) { + queriedColumns.add(c); + } + } + if (queriedColumns.isEmpty() || queriedColumns.size() == storedCount && subset) { + queriedColumns.clear(); + // a single sensor, chosen at random, is the interesting case: chunk and page statistics + // then come from that sensor instead of the time column + queriedColumns.add(rnd.nextInt(storedCount)); + } + SeriesScanScenario scenario = + new SeriesScanScenario( + model, ordering, Collections.unmodifiableList(storedTypes), queriedColumns, config); + + // Closed sequence files live in [0, closedSeqEnd); the open sequence file, if any, holds newer + // data in [closedSeqEnd, domainEnd). Unordered files may span the whole domain. + int closedSeqEnd = 1 + rnd.nextInt(40); + boolean hasOpenSeq = rnd.nextInt(3) == 0; + int domainEnd = closedSeqEnd + (hasOpenSeq ? 2 + rnd.nextInt(20) : 0); + // 0..5; a value is null with probability nullLevel / 5 (aligned series only) + int nullLevel = scenario.aligned() ? rnd.nextInt(6) : 0; + + // 1. decide which files exist and which time range each one covers + List orderedSpecs = new ArrayList<>(); // closed sequence files, in time order + List unorderedSpecs = new ArrayList<>(); + int seqCount = rnd.nextInt(4); + TreeSet cuts = new TreeSet<>(); + while (cuts.size() < Math.max(0, seqCount - 1) && rnd.nextInt(4) != 0) { + cuts.add(1 + rnd.nextInt(Math.max(1, closedSeqEnd - 1))); + } + List bounds = new ArrayList<>(); + bounds.add(0); + bounds.addAll(cuts); + bounds.add(closedSeqEnd); + for (int i = 0; i + 1 < bounds.size(); i++) { + FileSpec spec = new FileSpec(); + spec.seq = true; + spec.from = bounds.get(i); + spec.to = bounds.get(i + 1); + spec.density = rnd.nextInt(12) == 0 && seqCount > 1 ? 0 : 0.2 + 0.8 * rnd.nextDouble(); + orderedSpecs.add(spec); + } + if (hasOpenSeq) { + FileSpec spec = new FileSpec(); + spec.seq = true; + spec.open = true; + spec.from = closedSeqEnd; + spec.to = domainEnd; + spec.density = 0.4 + 0.6 * rnd.nextDouble(); + unorderedSpecs.add(spec); + } + int unseqCount = rnd.nextInt(4); + for (int i = 0; i < unseqCount; i++) { + FileSpec spec = new FileSpec(); + spec.from = rnd.nextInt(domainEnd); + spec.to = spec.from + rnd.nextInt(domainEnd - spec.from); + spec.density = 0.1 + 0.7 * rnd.nextDouble(); + unorderedSpecs.add(spec); + } + int openUnseqCount = rnd.nextInt(3); + for (int i = 0; i < openUnseqCount; i++) { + FileSpec spec = new FileSpec(); + spec.open = true; + spec.from = rnd.nextInt(domainEnd); + spec.to = spec.from + rnd.nextInt(domainEnd - spec.from); + spec.density = 0.3 + 0.7 * rnd.nextDouble(); + unorderedSpecs.add(spec); + } + + // 2. decide creation order, which gives versions: closed sequence files first (shuffled), then + // every unordered file plus the open sequence file (shuffled) + Collections.shuffle(orderedSpecs, rnd); + Collections.shuffle(unorderedSpecs, rnd); + List creationOrder = new ArrayList<>(orderedSpecs); + creationOrder.addAll(unorderedSpecs); + long version = 0; + for (FileSpec spec : creationOrder) { + spec.version = ++version; + } + + // 3. fill every file + int ordinal = 0; + for (FileSpec spec : creationOrder) { + List rows = sampleRows(rnd, scenario, spec.from, spec.to, spec.density, nullLevel); + FileNode file = + new FileNode(spec.seq, spec.open, spec.version, 1000L * spec.version, ordinal++); + if (spec.open) { + if (rows.isEmpty()) { + rows.add(new Row(Math.max(0, spec.from), randomRowValues(rnd, scenario, nullLevel))); + } + splitOpenFile(rnd, scenario, file, rows, nullLevel); + } else { + splitIntoDiskChunks(rnd, file, rows); + } + scenario.files.add(file); + } + + // 4. deletions + if (config.deletions) { + for (FileNode file : scenario.files) { + if (file.open) { + continue; + } + List rows = rowsOf(file); + if (rows.isEmpty()) { + continue; + } + if (rnd.nextInt(5) < 2) { + file.timeDeletions = randomDeletionRanges(rnd, rows); + } + if (scenario.aligned() && rnd.nextInt(5) < 2) { + file.valueDeletions = randomValueDeletions(rnd, scenario, rows); + } + } + for (FileNode file : scenario.files) { + for (int i = 0; i < file.memChunks.size(); i++) { + if (rnd.nextInt(3) != 0) { + continue; + } + MemChunk memChunk = file.memChunks.get(i); + List rows = new ArrayList<>(); + for (Source tvList : memChunk.tvLists) { + rows.addAll(tvList.rows()); + } + // A time deletion on a sequence file has to leave the newest rows alone, otherwise the + // file could become empty. + if (rnd.nextBoolean() && !(file.seq && i == file.memChunks.size() - 1)) { + memChunk.timeDeletions = randomDeletionRanges(rnd, rows); + } + if (scenario.aligned() && rnd.nextBoolean()) { + memChunk.valueDeletions = randomValueDeletions(rnd, scenario, rows); + } + } + } + } + + // 5. filters and pagination + if (config.filters) { + if (rnd.nextInt(2) == 0) { + scenario.globalTimeFilter = randomTimeFilter(rnd, domainEnd); + } + if (rnd.nextInt(2) == 0) { + scenario.pushDownFilter = randomPushDownFilter(rnd, scenario, domainEnd); + } + } + if (config.pagination && rnd.nextInt(2) == 0) { + scenario.offset = rnd.nextInt(4); + scenario.limit = rnd.nextInt(12); + } + // a wildcard selects every sensor, so a subset is always an explicit sensor list + scenario.queryAllSensors = + scenario.aligned() && scenario.columnCount() == storedCount && rnd.nextBoolean(); + return scenario; + } + + private static final class FileSpec { + boolean seq; + boolean open; + int from; + int to; + double density; + long version; + } + + private static boolean hasValue(Object[] values) { + for (Object value : values) { + if (value != null) { + return true; + } + } + return false; + } + + private static Object[] randomRowValues(Random rnd, SeriesScanScenario scenario, int nullLevel) { + Object[] values = new Object[scenario.storedTypes.size()]; + for (int c = 0; c < values.length; c++) { + values[c] = rnd.nextInt(5) < nullLevel ? null : randomValue(rnd, scenario.storedTypes.get(c)); + } + // A tree-model file never stores a row whose values are all null. A table-model row may. + if (scenario.aligned() && scenario.ignoreAllNullRows() && !hasValue(values)) { + int c = rnd.nextInt(values.length); + values[c] = randomValue(rnd, scenario.storedTypes.get(c)); + } + return values; + } + + /** A row with the same timestamp as {@code row} but at least one different queried value. */ + private static Row rewrittenRow(Random rnd, SeriesScanScenario scenario, Row row, int nullLevel) { + for (int attempt = 0; attempt < 20; attempt++) { + Object[] values = randomRowValues(rnd, scenario, nullLevel); + boolean differs = false; + for (int column = 0; column < scenario.columnCount() && !differs; column++) { + int stored = scenario.queriedColumns.get(column); + differs = !Objects.equals(values[stored], row.values[stored]); + } + if (differs) { + return new Row(row.time, values); + } + } + return new Row(row.time, randomRowValues(rnd, scenario, nullLevel)); + } + + private static List sampleRows( + Random rnd, SeriesScanScenario scenario, int from, int to, double density, int nullLevel) { + List rows = new ArrayList<>(); + for (long t = Math.max(0, from); t < to; t++) { + if (rnd.nextDouble() > density) { + continue; + } + rows.add(new Row(t, randomRowValues(rnd, scenario, nullLevel))); + } + return rows; + } + + private static void splitIntoDiskChunks(Random rnd, FileNode file, List rows) { + int index = 0; + while (index < rows.size()) { + int chunkLength = 1 + rnd.nextInt(9); + Source chunk = new Source(file, -1, file.diskChunks.size()); + int pageLength = 1 + rnd.nextInt(5); + int inPage = 0; + while (index < rows.size() && chunk.rows().size() < chunkLength) { + if (inPage == pageLength) { + chunk.startNewPage(); + pageLength = 1 + rnd.nextInt(5); + inPage = 0; + } + chunk.addRow(rows.get(index++)); + inPage++; + } + file.diskChunks.add(chunk); + } + } + + /** + * Fills an open file. Its rows go to up to three writers in time order: the chunks already + * flushed to disk, the flushing memory table and the working memory table. Right after a writer + * took over, a timestamp may be written to the newer writer while the older one still holds the + * previous value for it. + */ + private static void splitOpenFile( + Random rnd, SeriesScanScenario scenario, FileNode file, List rows, int nullLevel) { + boolean withFlushed = config(scenario).flushedChunks && rows.size() > 3 && rnd.nextInt(3) == 0; + boolean twoMemChunks = + config(scenario).multipleMemChunks && !file.seq && rows.size() > 3 && rnd.nextInt(3) == 0; + // writer index 0: flushed chunks; 1: first memory table; 2: second memory table + int writerCount = (withFlushed ? 1 : 0) + (twoMemChunks ? 2 : 1); + List> writers = new ArrayList<>(); + for (int i = 0; i < writerCount; i++) { + writers.add(new ArrayList<>()); + } + long[] takeOver = new long[writerCount - 1]; + long[] rewriteWindow = new long[writerCount - 1]; + long splitTime = rows.get(rows.size() / 2).time; + for (int i = 0; i < takeOver.length; i++) { + takeOver[i] = + i == 0 && !withFlushed ? splitTime : splitTime + (i == 0 ? 0 : 1 + rnd.nextInt(3)); + // a sequence file only receives growing timestamps, so nothing is ever rewritten there + rewriteWindow[i] = file.seq ? 0 : rnd.nextInt(4); + } + for (Row row : rows) { + int writer = writerCount - 1; + for (int i = 0; i < takeOver.length; i++) { + if (row.time < takeOver[i]) { + writer = i; + break; + } + } + writers.get(writer).add(row); + int previous = writer - 1; + if (previous >= 0 + && row.time < takeOver[previous] + rewriteWindow[previous] + && rnd.nextInt(5) < 3) { + writers.get(previous).add(rewrittenRow(rnd, scenario, row, nullLevel)); + } + } + // drop the writers that stayed empty and keep the time order of the remaining ones + List> nonEmpty = new ArrayList<>(); + for (List writerRows : writers) { + if (!writerRows.isEmpty()) { + nonEmpty.add(writerRows); + } + } + if (nonEmpty.isEmpty()) { + nonEmpty.add(new ArrayList<>(rows)); + } + boolean[] kinds = new boolean[nonEmpty.size()]; // true: flushed chunks + for (int i = 0; i < nonEmpty.size(); i++) { + kinds[i] = withFlushed && !writers.get(0).isEmpty() && i == 0; + } + for (int i = 0; i < nonEmpty.size(); i++) { + List writerRows = new ArrayList<>(nonEmpty.get(i)); + writerRows.sort((a, b) -> Long.compare(a.time, b.time)); + if (kinds[i]) { + splitIntoDiskChunks(rnd, file, writerRows); + } else { + fillMemChunk(rnd, file, file.memChunks.size(), writerRows); + } + } + } + + /** Puts the rows of one memory table into one TVList, or into two of them. */ + private static void fillMemChunk(Random rnd, FileNode file, int memChunkIndex, List rows) { + MemChunk memChunk = new MemChunk(); + // Several TVLists inside one memory chunk: either disjoint (an ordered iterator merges + // them) or overlapping around the split (a merge-sort iterator merges them). + boolean twoTvLists = rows.size() > 2 && rnd.nextInt(3) == 0; + if (!twoTvLists) { + Source tvList = new Source(file, memChunkIndex, 0); + rows.forEach(tvList::addRow); + memChunk.tvLists.add(tvList); + } else { + int split = 1 + rnd.nextInt(rows.size() - 1); + boolean overlapping = rnd.nextBoolean(); + Source older = new Source(file, memChunkIndex, 0); + Source newer = new Source(file, memChunkIndex, 1); + for (int i = 0; i < rows.size(); i++) { + boolean goesToNewer = i >= split || (overlapping && i >= split - 2 && rnd.nextBoolean()); + (goesToNewer ? newer : older).addRow(rows.get(i)); + } + if (older.rows().isEmpty()) { + older.addRow(rows.get(0)); + } + if (newer.rows().isEmpty()) { + newer.addRow(rows.get(rows.size() - 1)); + } + memChunk.tvLists.add(older); + memChunk.tvLists.add(newer); + } + file.memChunks.add(memChunk); + } + + private static Config config(SeriesScanScenario scenario) { + return scenario.config; + } + + public static List rowsOf(FileNode file) { + List rows = new ArrayList<>(); + for (Source chunk : file.diskChunks) { + rows.addAll(chunk.rows()); + } + for (MemChunk memChunk : file.memChunks) { + for (Source tvList : memChunk.tvLists) { + rows.addAll(tvList.rows()); + } + } + rows.sort((a, b) -> Long.compare(a.time, b.time)); + return rows; + } + + private static List randomDeletionRanges(Random rnd, List rows) { + List ranges = new ArrayList<>(); + long start = rows.get(0).time; + long end = rows.get(rows.size() - 1).time; + int count = 1 + rnd.nextInt(2); + for (int i = 0; i < count; i++) { + switch (rnd.nextInt(4)) { + case 0: + ranges.add(new TimeRange(start, end)); + break; + case 1: + long a = rows.get(rnd.nextInt(rows.size())).time; + long b = rows.get(rnd.nextInt(rows.size())).time; + ranges.add(new TimeRange(Math.min(a, b), Math.max(a, b))); + break; + case 2: + long point = rows.get(rnd.nextInt(rows.size())).time; + ranges.add(new TimeRange(point, point)); + break; + default: + ranges.add(new TimeRange(start - 3, end + 3)); + break; + } + } + return TimeRange.sortAndMerge(ranges); + } + + /** Value-column deletions for aligned series: one list per column, many of them empty. */ + private static List> randomValueDeletions( + Random rnd, SeriesScanScenario scenario, List rows) { + List> result = new ArrayList<>(); + for (int c = 0; c < scenario.storedTypes.size(); c++) { + result.add(rnd.nextInt(3) == 0 ? randomDeletionRanges(rnd, rows) : new ArrayList<>()); + } + return result; + } + + private static long randomTime(Random rnd, int domainEnd) { + return rnd.nextInt(Math.max(1, domainEnd)); + } + + private static Filter randomTimeFilter(Random rnd, int domainEnd) { + long a = randomTime(rnd, domainEnd); + long b = a + rnd.nextInt(Math.max(1, domainEnd - (int) a)); + switch (rnd.nextInt(5)) { + case 0: + return TimeFilterApi.between(a, b); + case 1: + return TimeFilterApi.gtEq(a); + case 2: + return TimeFilterApi.ltEq(a); + case 3: + long c = Math.min(b + 1, domainEnd - 1); + long d = Math.min(domainEnd - 1L, c + rnd.nextInt(Math.max(1, domainEnd - (int) c))); + return FilterFactory.or(TimeFilterApi.between(a, a), TimeFilterApi.between(c, d)); + default: + return FilterFactory.and(TimeFilterApi.between(0, domainEnd), TimeFilterApi.notEq(a)); + } + } + + private static Filter randomValueFilter(Random rnd, SeriesScanScenario scenario) { + int column = rnd.nextInt(scenario.columnCount()); + TSDataType type = scenario.columnType(column); + Object operand = randomValue(rnd, type); + switch (type) { + case INT32: + case INT64: + case FLOAT: + case DOUBLE: + switch (rnd.nextInt(6)) { + case 0: + return ValueFilterApi.gt(column, operand, type); + case 1: + return ValueFilterApi.gtEq(column, operand, type); + case 2: + return ValueFilterApi.lt(column, operand, type); + case 3: + return ValueFilterApi.ltEq(column, operand, type); + case 4: + return ValueFilterApi.notEq(column, operand, type); + default: + Object other = randomValue(rnd, type); + @SuppressWarnings("unchecked") + int cmp = ((Comparable) operand).compareTo(other); + Object lower = cmp <= 0 ? operand : other; + Object upper = cmp <= 0 ? other : operand; + return ValueFilterApi.between(column, lower, upper, type); + } + default: + return rnd.nextBoolean() + ? ValueFilterApi.eq(column, operand, type) + : ValueFilterApi.notEq(column, operand, type); + } + } + + private static Filter randomPushDownFilter(Random rnd, SeriesScanScenario scenario, int end) { + Filter valueFilter = randomValueFilter(rnd, scenario); + switch (rnd.nextInt(4)) { + case 0: + return valueFilter; + case 1: + return FilterFactory.and(valueFilter, TimeFilterApi.gtEq(randomTime(rnd, end))); + case 2: + return FilterFactory.or(valueFilter, TimeFilterApi.ltEq(randomTime(rnd, end))); + default: + return FilterFactory.and(valueFilter, randomValueFilter(rnd, scenario)); + } + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // hand-written scenarios + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** An empty scenario for a device storing the given sensors, all of which the scan reads. */ + public static SeriesScanScenario create( + Model model, Ordering ordering, TSDataType... storedTypes) { + List queriedColumns = new ArrayList<>(); + for (int c = 0; c < storedTypes.length; c++) { + queriedColumns.add(c); + } + return new SeriesScanScenario( + model, + ordering, + Collections.unmodifiableList(Arrays.asList(storedTypes)), + queriedColumns, + new Config()); + } + + /** Narrows the scan to the given stored columns. */ + public void queryColumns(int... storedColumns) { + queriedColumns.clear(); + for (int storedColumn : storedColumns) { + queriedColumns.add(storedColumn); + } + } + + /** + * Adds a file. {@code version} is the creation order of the file among those of the scenario: the + * newer a file, the higher its version and its priority. + */ + public FileNode addFile(boolean seq, boolean open, long version) { + FileNode file = new FileNode(seq, open, version, 1000L * (version + 10), files.size()); + files.add(file); + return file; + } + + public static Row row(long time, Object... values) { + return new Row(time, values); + } + + public static List page(Row... rows) { + return Arrays.asList(rows); + } + + /** Adds an on-disk chunk to the file, with one page per argument. */ + public static Source addDiskChunk(FileNode file, List... pages) { + Source chunk = new Source(file, -1, file.diskChunks.size()); + for (List page : pages) { + chunk.startNewPage(); + page.forEach(chunk::addRow); + } + file.diskChunks.add(chunk); + return chunk; + } + + /** + * Adds a memory table to the open file, holding one TVList per argument. Its value deletions + * start out empty, one list per stored sensor. + */ + public MemChunk addMemChunk(FileNode file, List... tvLists) { + MemChunk memChunk = new MemChunk(); + for (List tvList : tvLists) { + Source source = new Source(file, file.memChunks.size(), memChunk.tvLists.size()); + tvList.forEach(source::addRow); + memChunk.tvLists.add(source); + } + memChunk.valueDeletions = noValueDeletions(); + file.memChunks.add(memChunk); + return memChunk; + } + + /** + * Closed ranges given as start and end bounds: {@code ranges(1, 2, 5, 5)} is [1, 2] and [5, 5]. + */ + public static List ranges(long... bounds) { + List ranges = new ArrayList<>(); + for (int i = 0; i + 1 < bounds.length; i += 2) { + ranges.add(new TimeRange(bounds[i], bounds[i + 1])); + } + return TimeRange.sortAndMerge(ranges); + } + + /** Value deletions for the stored sensors of a scenario, none at first. */ + public List> noValueDeletions() { + List> result = new ArrayList<>(); + for (int c = 0; c < storedTypes.size(); c++) { + result.add(new ArrayList<>()); + } + return result; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // oracle + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** All sources of the scenario, sorted from the lowest to the highest priority. */ + public List sourcesByPriority() { + List sources = new ArrayList<>(); + for (FileNode file : files) { + sources.addAll(file.diskChunks); + for (MemChunk memChunk : file.memChunks) { + sources.addAll(memChunk.tvLists); + } + } + sources.sort(SeriesScanScenario::comparePriority); + return sources; + } + + /** Mirrors MergeReaderPriority: unordered beats sequence, then version, file, offset. */ + private static int comparePriority(Source a, Source b) { + // !seq: an unordered file (seq == false) must sort after a sequence file + int result = Boolean.compare(!a.file.seq, !b.file.seq); + if (result != 0) { + return result; + } + result = Long.compare(a.file.version, b.file.version); + if (result != 0) { + return result; + } + // Memory chunks are loaded through MemChunkLoader, whose "timestamp in file name" is MAX_VALUE, + // so they outrank the flushed chunks of the same file. + result = + Long.compare( + a.memChunkIndex < 0 ? a.file.fileTimestamp : Long.MAX_VALUE, + b.memChunkIndex < 0 ? b.file.fileTimestamp : Long.MAX_VALUE); + if (result != 0) { + return result; + } + result = Integer.compare(a.memChunkIndex, b.memChunkIndex); + if (result != 0) { + return result; + } + return Integer.compare(a.rank, b.rank); + } + + private static boolean contains(List ranges, long time) { + if (ranges == null) { + return false; + } + for (TimeRange range : ranges) { + if (range.contains(time)) { + return true; + } + } + return false; + } + + /** + * Whether the row at {@code time} of {@code source} is hit by a deletion of the time column + * (aligned) or of the series (non-aligned). + */ + public boolean timeDeleted(Source source, long time) { + if (source.memChunkIndex < 0) { + return contains(source.file.timeDeletions, time); + } + // A deletion recorded for memory table i also applies to every older memory table. + for (int i = source.memChunkIndex; i < source.file.memChunks.size(); i++) { + if (contains(source.file.memChunks.get(i).timeDeletions, time)) { + return true; + } + } + return false; + } + + /** Whether stored column {@code storedColumn} at {@code time} of {@code source} is deleted. */ + public boolean valueDeleted(Source source, int storedColumn, long time) { + if (source.memChunkIndex < 0) { + return source.file.valueDeletions.size() > storedColumn + && contains(source.file.valueDeletions.get(storedColumn), time); + } + for (int i = source.memChunkIndex; i < source.file.memChunks.size(); i++) { + List> perColumn = source.file.memChunks.get(i).valueDeletions; + if (perColumn.size() > storedColumn && contains(perColumn.get(storedColumn), time)) { + return true; + } + } + return false; + } + + /** Rows of every source merged by priority, with the deletions applied, before any filter. */ + public TreeMap mergedRows() { + List sources = sourcesByPriority(); + TreeSet times = new TreeSet<>(); + for (Source source : sources) { + for (Row row : source.rows()) { + times.add(row.time); + } + } + TreeMap merged = new TreeMap<>(); + for (long time : times) { + Object[] mergedRow = new Object[columnCount()]; + boolean exists = false; + // ascending priority: a non-null value written by a newer source overrides an older one + for (Source source : sources) { + Row row = source.rowAt(time); + if (row == null || timeDeleted(source, time)) { + continue; + } + Object[] values = new Object[columnCount()]; + boolean hasValue = false; + for (int column = 0; column < values.length; column++) { + int storedColumn = queriedColumns.get(column); + values[column] = row.values[storedColumn]; + if (values[column] != null && valueDeleted(source, storedColumn, time)) { + values[column] = null; + } + hasValue |= values[column] != null; + } + // The tree model drops a row whose queried values are all null; the table model keeps it. + if (aligned() && ignoreAllNullRows() && !hasValue) { + continue; + } + exists = true; + for (int column = 0; column < values.length; column++) { + if (values[column] != null) { + mergedRow[column] = values[column]; + } + } + } + if (exists) { + merged.put(time, mergedRow); + } + } + return merged; + } + + /** The rows a correct scan must return, in scan order. */ + public List expectedRows() { + List rows = new ArrayList<>(); + for (Map.Entry entry : mergedRows().entrySet()) { + long time = entry.getKey(); + Object[] values = entry.getValue(); + if (globalTimeFilter != null && !globalTimeFilter.satisfyRow(time, null)) { + continue; + } + if (pushDownFilter != null && !pushDownFilter.satisfyRow(time, values)) { + continue; + } + rows.add(new Row(time, values)); + } + if (!ordering.isAscending()) { + Collections.reverse(rows); + } + if (offset > 0) { + rows = new ArrayList<>(rows.subList((int) Math.min(offset, rows.size()), rows.size())); + } + if (limit > 0 && rows.size() > limit) { + rows = new ArrayList<>(rows.subList(0, (int) limit)); + } + return rows; + } + + /** Human readable dump, used in failure messages. */ + public String describe() { + StringBuilder sb = new StringBuilder(); + sb.append("model=").append(model).append(" order=").append(ordering); + sb.append(" storedTypes=").append(storedTypes); + sb.append(" queriedColumns=").append(queriedColumns).append('\n'); + for (FileNode file : files) { + sb.append(" ").append(file.name()); + if (!file.timeDeletions.isEmpty()) { + sb.append(" timeDel=").append(file.timeDeletions); + } + if (!file.valueDeletions.isEmpty() + && file.valueDeletions.stream().anyMatch(range -> !range.isEmpty())) { + sb.append(" valueDel=").append(file.valueDeletions); + } + sb.append('\n'); + for (Source chunk : file.diskChunks) { + describeSource(sb, chunk); + } + for (MemChunk memChunk : file.memChunks) { + if (!memChunk.timeDeletions.isEmpty()) { + sb.append(" memDel(time)=").append(memChunk.timeDeletions).append('\n'); + } + if (memChunk.valueDeletions.stream().anyMatch(range -> !range.isEmpty())) { + sb.append(" memDel(value)=").append(memChunk.valueDeletions).append('\n'); + } + for (Source tvList : memChunk.tvLists) { + describeSource(sb, tvList); + } + } + } + sb.append(" globalTimeFilter=").append(globalTimeFilter).append('\n'); + sb.append(" pushDownFilter=").append(pushDownFilter).append('\n'); + sb.append(" offset=").append(offset).append(" limit=").append(limit); + sb.append(" queryAllSensors=").append(queryAllSensors).append('\n'); + sb.append(" config: smallPage=").append(config.smallPage); + sb.append(" multipleMemChunks=").append(config.multipleMemChunks); + sb.append(" flushedChunks=").append(config.flushedChunks); + sb.append(" subsetSensors=").append(config.subsetSensors); + sb.append(" seed=").append(seed).append('\n'); + return sb.toString(); + } + + private static void describeSource(StringBuilder sb, Source source) { + sb.append(" ").append(source.kind()).append(" pages="); + for (List page : source.pages) { + sb.append(page).append(' '); + } + sb.append('\n'); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenarioRunner.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenarioRunner.java new file mode 100644 index 0000000000000..fb6b5c83889a9 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenarioRunner.java @@ -0,0 +1,252 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.commons.path.AlignedFullPath; +import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext; +import org.apache.iotdb.db.queryengine.execution.operator.source.AlignedSeriesScanUtil; +import org.apache.iotdb.db.queryengine.execution.operator.source.SeriesScanUtil; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanFuzzDriver.Agg; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanMaterializer.Handle; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Row; +import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.SeriesScanOptions; +import org.apache.iotdb.db.storageengine.dataregion.read.QueryDataSource; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; + +/** + * Runs the scans of one scenario the way the operators do, and reports what they got wrong. + * Materializes the scenario afresh for every scan, because a scan cannot be rewound. + */ +public final class SeriesScanScenarioRunner { + + private static final AtomicInteger QUERY_IDS = new AtomicInteger(); + private static final Pattern NUMBER = Pattern.compile("-?\\d+"); + + private SeriesScanScenarioRunner() { + // utility class + } + + /** One thing a scan did that it should not have. */ + public static final class Problem { + /** The shape of the problem; problems of one shape share it even when their numbers differ. */ + public final String kind; + + /** What happened, with the numbers. */ + public final String detail; + + Problem(String kind, String detail) { + this.kind = kind; + this.detail = detail; + } + + @Override + public String toString() { + return detail; + } + } + + private interface HandleAction { + T run(Handle handle) throws Exception; + } + + /** + * Scans like {@code SeriesScanOperator} and returns the rows, in scan order. Every setting of the + * scenario applies, limit and offset included. + */ + public static List scanRows(SeriesScanScenario scenario) throws IOException { + return withMaterialized( + scenario, + handle -> { + SeriesScanUtil scan = newScan(handle, true); + return SeriesScanFuzzDriver.scanLikeSeriesScanOperator(scan, scenario.columnCount()); + }); + } + + /** + * Aggregates like {@code SeriesAggregationScanOperator}: the statistics of a file, chunk or page + * replace its data whenever the scan says they are usable. Only for scenarios without limit and + * offset, which such an aggregation never combines with statistics. + */ + public static Agg aggregateWithStatistics(SeriesScanScenario scenario) throws IOException { + return withMaterialized( + scenario, + handle -> + SeriesScanFuzzDriver.aggregateLikeAggregationScanOperator( + newScan(handle, false), scenario.columnTypes())); + } + + /** The aggregate of the rows the oracle expects. */ + public static Agg expectedAggregate(SeriesScanScenario scenario) { + Agg result = new Agg(scenario.columnTypes()); + for (Row row : scenario.expectedRows()) { + result.addRow(row); + } + return result; + } + + /** + * Runs every driver on the scenario and reports the problems. {@code statisticsChecks} adds the + * two drivers that compare statistics with raw data. + */ + public static List check(SeriesScanScenario scenario, boolean statisticsChecks) { + List problems = new ArrayList<>(); + try { + List expected = scenario.expectedRows(); + List operatorRows = scanRows(scenario); + checkRows(problems, "rows differ [SeriesScanOperator]", expected, operatorRows); + if (statisticsChecks && scenario.offset == 0 && scenario.limit == 0) { + List statisticsProblems = new ArrayList<>(); + List explicitRows = + withMaterialized( + scenario, + handle -> + SeriesScanFuzzDriver.scanCheckingStatistics( + newScan(handle, false), scenario.columnTypes(), statisticsProblems)); + checkRows(problems, "rows differ [file-to-page walk]", expected, explicitRows); + for (String statisticsProblem : statisticsProblems) { + problems.add(new Problem("statistics claimed usable but inexact", statisticsProblem)); + } + Agg expectedAggregate = expectedAggregate(scenario); + Agg actualAggregate = aggregateWithStatistics(scenario); + String mismatch = expectedAggregate.mismatch(actualAggregate); + if (mismatch != null) { + problems.add( + new Problem( + "aggregate from statistics differs from raw data", + "SeriesAggregationScanOperator-style scan: expected " + + expectedAggregate + + " but got " + + actualAggregate + + " (" + + mismatch + + ")")); + } + } + } catch (Throwable t) { + String description = describe(t); + problems.add(new Problem("scan threw " + kindOf(description), "scan threw " + description)); + } + return problems; + } + + /** Problems of the same shape share a kind even when their numbers differ. */ + public static String kindOf(String detail) { + return NUMBER + .matcher(detail.substring(0, Math.min(detail.length(), 160))) + .replaceAll("#") + .replaceAll("expected.*", "..."); + } + + private static void checkRows( + List problems, String kind, List expected, List actual) { + String difference = SeriesScanFuzzDriver.firstDifference(expected, actual); + if (difference != null) { + problems.add( + new Problem( + kind, + kind + + ": " + + difference + + "\n expected " + + expected + + "\n actual " + + actual)); + } + } + + private static T withMaterialized(SeriesScanScenario scenario, HandleAction action) + throws IOException { + FragmentInstanceContext context = + FragmentInstanceContext.createFragmentInstanceContextForCompaction( + QUERY_IDS.incrementAndGet()); + context.setIgnoreAllNullRows(scenario.ignoreAllNullRows()); + if (scenario.globalTimeFilter != null) { + // production keeps the fragment-level time filter and the scan-level one in sync + context.setTimeFilterForTableModel(scenario.globalTimeFilter); + } + try (Handle handle = SeriesScanMaterializer.materialize(scenario, context)) { + return action.run(handle); + } catch (IOException | RuntimeException | Error e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } + } + + private static SeriesScanUtil newScan(Handle handle, boolean withPagination) { + SeriesScanScenario scenario = handle.scenario; + SeriesScanOptions.Builder builder = new SeriesScanOptions.Builder(); + builder.withAllSensors(new HashSet<>(handle.measurements())); + builder.withGlobalTimeFilter(scenario.globalTimeFilter); + builder.withPushDownFilter(scenario.pushDownFilter); + if (withPagination) { + builder.withPushDownLimit(scenario.limit); + builder.withPushDownOffset(scenario.offset); + } + SeriesScanUtil scanUtil = + scenario.aligned() + ? new AlignedSeriesScanUtil( + (AlignedFullPath) handle.path, + scenario.ordering, + builder.build(), + handle.context, + scenario.queryAllSensors, + null) + : new SeriesScanUtil(handle.path, scenario.ordering, builder.build(), handle.context); + scanUtil.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + return scanUtil; + } + + /** + * The exception and its causes with their first frames. Surefire trims stack traces, so the cause + * of a wrapped failure would not reach the report otherwise. + */ + public static String describe(Throwable t) { + StringBuilder sb = new StringBuilder(); + int depth = 0; + for (Throwable cause = t; cause != null && depth < 4; cause = cause.getCause(), depth++) { + sb.append(depth == 0 ? "" : "\n caused by ").append(cause.toString()); + int shown = 0; + for (StackTraceElement frame : cause.getStackTrace()) { + if (shown >= 7) { + break; + } + String className = frame.getClassName(); + if (className.startsWith("org.apache.") && !className.contains("scanfuzz")) { + sb.append("\n at ") + .append(className, className.lastIndexOf('.') + 1, className.length()) + .append('.') + .append(frame.getMethodName()) + .append(':') + .append(frame.getLineNumber()); + shown++; + } + } + } + return sb.toString(); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilDefectTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilDefectTest.java new file mode 100644 index 0000000000000..508b447119585 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilDefectTest.java @@ -0,0 +1,257 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanFuzzDriver.Agg; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.FileNode; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Model; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Row; + +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.filter.factory.ValueFilterApi; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.addDiskChunk; +import static org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.create; +import static org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.page; +import static org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.ranges; +import static org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.row; +import static org.apache.iotdb.db.queryengine.plan.statement.component.Ordering.ASC; + +/** + * Minimal regression scenarios for {@link + * org.apache.iotdb.db.queryengine.execution.operator.source.SeriesScanUtil} and the readers it + * uses. + * + *

Each test spells its scenario out: which files hold which rows, what was deleted, and what a + * correct scan returns. The expectations rest on three rules of the storage engine: + * + *

    + *
  • At one timestamp the newer writer wins: an unordered file over a sequence file, then the + * later file; inside an open file, a memory table over the flushed chunks. + *
  • The tree model drops a row whose queried values are all null; the table model keeps it. + *
  • Statistics may stand in for data only when they describe exactly the rows the data yields. + *
+ */ +public class SeriesScanUtilDefectTest { + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // the rows a scan returns + ///////////////////////////////////////////////////////////////////////////////////////////////// + + @Test + public void valueDeletionOfFlushingMemoryTableIsAppliedWhenMerged() throws IOException { + // s0 of the memory table was deleted at 1 and 2 while the table was flushing + SeriesScanScenario s = alignedTree(); + FileNode flushed = s.addFile(true, false, 1); + addDiskChunk(flushed, page(row(2, 200L, null))); + FileNode flushing = s.addFile(false, true, 2); + s.addMemChunk(flushing, page(row(1, 10L, 1L), row(2, 20L, 2L))); + flushing.memChunks.get(0).valueDeletions.get(0).addAll(ranges(1, 2)); + + assertRows(s, row(1, null, 1L), row(2, 200L, 2L)); + } + + @Test + public void valueDeletionOfMemoryTableIsAppliedWithTwoTVLists() throws IOException { + SeriesScanScenario s = alignedTree(); + FileNode open = s.addFile(false, true, 1); + s.addMemChunk(open, page(row(1, 10L, 1L)), page(row(2, 20L, 2L))); + open.memChunks.get(0).valueDeletions.get(0).addAll(ranges(1, 2)); + + assertRows(s, row(1, null, 1L), row(2, null, 2L)); + } + + @Test + public void offsetDoesNotSkipAChunkThatOverlapsUnpackedData() throws IOException { + // the sequence file at 1 and 2 was deleted entirely; the unordered file carries the newer + // value at 2 and 3, so the rows are 2:20, 3:30, 4:4 and an offset of 2 leaves 4:4 + SeriesScanScenario s = overlappingAfterChunklessFile(); + s.offset = 2; + s.limit = 2; + + assertRows(s, row(4, 4L)); + } + + @Test + public void offsetCountsRowsWithoutValues() throws IOException { + // s1 was deleted everywhere, which leaves row 2 without any value; the rows are 1, 3, 4, 5 + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + addDiskChunk( + file, + page(row(1, 1L, null), row(2, null, 2L), row(3, 3L, null)), + page(row(4, 4L, null), row(5, 5L, null))); + file.valueDeletions = s.noValueDeletions(); + file.valueDeletions.get(1).addAll(ranges(1, 5)); + s.queryAllSensors = true; + s.offset = 3; + s.limit = 5; + + assertRows(s, row(5, 5L, null)); + } + + @Test + public void pushDownFilterIsAppliedToDeletedValues() throws IOException { + // the table model keeps the row at 2 once its only value is deleted, and a null is not + // "!= 173" + SeriesScanScenario s = create(Model.ALIGNED_TABLE, ASC, TSDataType.INT64); + FileNode file = s.addFile(true, false, 1); + addDiskChunk(file, page(row(1, 10L), row(2, 20L), row(3, 30L))); + file.valueDeletions = s.noValueDeletions(); + file.valueDeletions.get(0).addAll(ranges(2, 2)); + s.pushDownFilter = ValueFilterApi.notEq(0, 173L, TSDataType.INT64); + + assertRows(s, row(1, 10L), row(3, 30L)); + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + // what an aggregation computes from statistics + ///////////////////////////////////////////////////////////////////////////////////////////////// + + @Test + public void statisticsOfOverlappingChunksAreNotUsedAfterChunklessFile() throws IOException { + // the rows are 2:20, 3:30, 4:4 + SeriesScanScenario s = overlappingAfterChunklessFile(); + + assertAggregate(s, aggregate(TSDataType.INT64, row(2, 20L), row(3, 30L), row(4, 4L))); + } + + @Test + public void timeStatisticsDoNotCountRowsWithoutQueriedValues() throws IOException { + // only s0 is read; it has no value at 2, so the scan returns two timestamps + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + addDiskChunk(file, page(row(1, 1L, null), row(2, null, 2L), row(3, 3L, null))); + s.queryColumns(0); + + assertAggregate(s, aggregate(TSDataType.INT64, row(1, 1L), row(3, 3L))); + } + + @Test + public void timeStatisticsDoNotCountRowsWhoseValuesWereAllDeleted() throws IOException { + // s1 was deleted everywhere, which leaves row 2 without any value + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + addDiskChunk(file, page(row(1, 1L, null), row(2, null, 2L), row(3, 3L, null))); + file.valueDeletions = s.noValueDeletions(); + file.valueDeletions.get(1).addAll(ranges(1, 3)); + + assertAggregate( + s, aggregate(TSDataType.INT64, TSDataType.INT64, row(1, 1L, null), row(3, 3L, null))); + } + + @Test + public void timeStatisticsDoNotCountADeletedRowOfADroppedValuePage() throws IOException { + // the row at 1 is deleted. s1 has no other value in that page, so its page is deleted as a + // whole and dropped instead of being marked modified; the time page is never marked either + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + addDiskChunk( + file, page(row(1, null, 1L), row(2, 2L, null), row(3, 3L, null)), page(row(4, 4L, null))); + file.timeDeletions = ranges(1, 1); + + assertAggregate( + s, + aggregate( + TSDataType.INT64, + TSDataType.INT64, + row(2, 2L, null), + row(3, 3L, null), + row(4, 4L, null))); + } + + ///////////////////////////////////////////////////////////////////////////////////////////////// + + /** An aligned device with two int sensors, read in full. */ + private static SeriesScanScenario alignedTree() { + return create(Model.ALIGNED_TREE, ASC, TSDataType.INT64, TSDataType.INT64); + } + + /** A deleted sequence file, an unordered file overlapping its end, a later sequence file. */ + private static SeriesScanScenario overlappingAfterChunklessFile() { + SeriesScanScenario s = create(Model.NON_ALIGNED, ASC, TSDataType.INT64); + FileNode deleted = s.addFile(true, false, 1); + addDiskChunk(deleted, page(row(1, 1L), row(2, 2L))); + deleted.timeDeletions = ranges(1, 2); + FileNode unordered = s.addFile(false, false, 2); + addDiskChunk(unordered, page(row(2, 20L), row(3, 30L))); + FileNode later = s.addFile(true, false, 3); + addDiskChunk(later, page(row(3, 3L), row(4, 4L))); + return s; + } + + private static Agg aggregate(TSDataType type, Row... rows) { + Agg result = new Agg(Collections.singletonList(type)); + for (Row r : rows) { + result.addRow(r); + } + return result; + } + + private static Agg aggregate(TSDataType first, TSDataType second, Row... rows) { + Agg result = new Agg(Arrays.asList(first, second)); + for (Row r : rows) { + result.addRow(r); + } + return result; + } + + /** The scan must return exactly these rows, in this order. */ + private static void assertRows(SeriesScanScenario s, Row... expected) throws IOException { + assertRows(s, Arrays.asList(expected)); + } + + private static void assertRows(SeriesScanScenario s, List expected) throws IOException { + // the expectation is written by hand; the oracle has to read the scenario the same way + String oracleDifference = SeriesScanFuzzDriver.firstDifference(expected, s.expectedRows()); + if (oracleDifference != null) { + throw new AssertionError( + "the oracle reads the scenario differently: " + oracleDifference + "\n" + s.describe()); + } + List actual = SeriesScanScenarioRunner.scanRows(s); + String difference = SeriesScanFuzzDriver.firstDifference(expected, actual); + if (difference != null) { + throw new AssertionError( + difference + + "\n expected " + + expected + + "\n actual " + + actual + + "\n" + + s.describe()); + } + } + + /** An aggregation that uses statistics whenever the scan says they are usable must add up. */ + private static void assertAggregate(SeriesScanScenario s, Agg expected) throws IOException { + Agg actual = SeriesScanScenarioRunner.aggregateWithStatistics(s); + String mismatch = expected.mismatch(actual); + if (mismatch != null) { + throw new AssertionError( + "expected " + expected + " but got " + actual + " (" + mismatch + ")\n" + s.describe()); + } + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilFuzzTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilFuzzTest.java new file mode 100644 index 0000000000000..02aaa6e3bd80f --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilFuzzTest.java @@ -0,0 +1,197 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz; + +import org.apache.iotdb.db.queryengine.execution.operator.source.AlignedSeriesScanUtil; +import org.apache.iotdb.db.queryengine.execution.operator.source.SeriesScanUtil; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Config; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenario.Model; +import org.apache.iotdb.db.queryengine.execution.operator.source.scanfuzz.SeriesScanScenarioRunner.Problem; +import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.stream.Collectors; + +import static org.junit.Assert.fail; + +/** + * Randomized, oracle-checked coverage of {@link SeriesScanUtil} and {@link AlignedSeriesScanUtil}. + * + *

Every scenario is generated from a seed, materialized into real TsFiles, modification files + * and memory chunks, and scanned the way the operators scan: like {@code SeriesScanOperator}, + * always; like an explicit file-to-page walk and like {@code SeriesAggregationScanOperator} when + * the scenario has no limit and offset. The rows and the aggregates must match a brute-force + * oracle. + * + *

Scenarios shaped like a known defect are left out, so that a failure here is something new; + * {@code SeriesScanUtilDefectTest} pins the known defects down. {@code scan_strict=1} runs them all + * the same. + * + *

Options, read from the system property or the environment variable of the same name (surefire + * does not forward {@code -D} to the test JVM): {@code scan_scenarios} sets how many scenarios each + * parameter runs (default 60); {@code scan_first} moves the start of the default range of seeds; + * {@code scan_seed} reruns a single scenario, by its index, and reports every problem in full + * instead of one example per kind; {@code scan_multimem}, {@code scan_flushed} and {@code + * scan_subset} (each {@code =1}) switch on an open file with two memory tables, an open file with + * flushed chunks, and scans of a subset of the sensors stored for the device. + */ +@RunWith(Parameterized.class) +public class SeriesScanUtilFuzzTest { + + private static final int SCENARIOS_PER_PARAMETER = option("scan_scenarios", 60); + private static final int ONLY_SEED = option("scan_seed", -1); + private static final int FIRST_INDEX = option("scan_first", 1000) - 1000; + private static final boolean MULTIPLE_MEM_CHUNKS = option("scan_multimem", 0) == 1; + private static final boolean FLUSHED_CHUNKS = option("scan_flushed", 0) == 1; + private static final boolean SUBSET_SENSORS = option("scan_subset", 0) == 1; + + private final Model model; + private final Ordering ordering; + + public SeriesScanUtilFuzzTest(Model model, Ordering ordering) { + this.model = model; + this.ordering = ordering; + } + + @Parameterized.Parameters(name = "model={0} order={1}") + public static Object[][] parameters() { + return new Object[][] { + {Model.NON_ALIGNED, Ordering.ASC}, + {Model.NON_ALIGNED, Ordering.DESC}, + {Model.ALIGNED_TREE, Ordering.ASC}, + {Model.ALIGNED_TREE, Ordering.DESC}, + {Model.ALIGNED_TABLE, Ordering.ASC}, + {Model.ALIGNED_TABLE, Ordering.DESC}, + }; + } + + @Test + public void randomScenariosMatchTheOracle() { + // kind of problem -> one example per scenario that showed it + Map> problems = new LinkedHashMap<>(); + int scenarios = 0; + int failingScenarios = 0; + int skipped = 0; + // A single-seed rerun must reach its seed even when it lies beyond scan_scenarios. + int firstIndex = ONLY_SEED >= 0 ? ONLY_SEED - 1000 : FIRST_INDEX; + int lastIndex = ONLY_SEED >= 0 ? ONLY_SEED - 1000 : FIRST_INDEX + SCENARIOS_PER_PARAMETER - 1; + for (int index = firstIndex; index <= lastIndex; index++) { + int seed = 1000 + index; + Config config = new Config(); + config.smallPage = index % 2 == 0; + config.multipleMemChunks = MULTIPLE_MEM_CHUNKS; + config.flushedChunks = FLUSHED_CHUNKS; + config.subsetSensors = SUBSET_SENSORS; + long fullSeed = + seed * 1_000_003L + model.ordinal() * 7919L + (ordering.isAscending() ? 0 : 1); + SeriesScanScenario scenario = + SeriesScanScenario.generate(new Random(fullSeed), model, ordering, config); + scenario.seed = fullSeed; + if (SeriesScanKnownIssues.scenarioHitsKnownDefect(scenario)) { + // the rows of this shape are known to come out wrong, see SeriesScanKnownIssues + skipped++; + continue; + } + scenarios++; + List found = + SeriesScanScenarioRunner.check( + scenario, !SeriesScanKnownIssues.statisticsHitKnownDefect(scenario)); + if (!found.isEmpty()) { + failingScenarios++; + } + for (Problem problem : found) { + problems + .computeIfAbsent(problem.kind, ignored -> new ArrayList<>()) + .add(new Example(problem.detail, scenario.describe(), fullSeed)); + } + } + if (problems.isEmpty()) { + return; + } + int total = problems.values().stream().mapToInt(List::size).sum(); + StringBuilder message = + new StringBuilder() + .append(total) + .append(" problem(s) of ") + .append(problems.size()) + .append(" kind(s) in ") + .append(failingScenarios) + .append(" of ") + .append(scenarios) + .append(" scenario(s), ") + .append(skipped) + .append(" more skipped as known defects"); + for (Map.Entry> entry : problems.entrySet()) { + List ofKind = entry.getValue(); + message + .append("\n\n== ") + .append(ofKind.size()) + .append(" x [") + .append(entry.getKey()) + .append("], seeds ") + .append( + ofKind.stream() + .map(example -> String.valueOf(example.seed)) + .limit(8) + .collect(Collectors.joining(","))); + // one example per kind is enough to reproduce; a single-seed rerun shows everything + int shown = ONLY_SEED >= 0 ? ofKind.size() : 1; + for (Example example : ofKind.subList(0, shown)) { + message.append("\n").append(example.detail).append('\n').append(example.scenario); + } + } + fail(message.toString()); + } + + /** A problem together with the scenario that showed it. */ + private static final class Example { + final String detail; + final String scenario; + final long seed; + + Example(String detail, String scenario, long seed) { + this.detail = detail; + // a single-seed rerun is a debugging session: keep the whole scenario + this.scenario = ONLY_SEED >= 0 ? scenario : shorten(scenario); + this.seed = seed; + } + } + + private static String shorten(String text) { + return text.length() <= 2600 ? text : text.substring(0, 2600) + "\n ...(truncated)"; + } + + /** Surefire does not forward -D options to the test JVM, so the environment is read as well. */ + private static int option(String name, int defaultValue) { + String value = System.getProperty(name); + if (value == null) { + value = System.getenv(name); + } + return value == null ? defaultValue : Integer.parseInt(value.trim()); + } +}