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..a3f386f4f3c65 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/query/IoTDBSeriesScanDefectIT.java @@ -0,0 +1,788 @@ +/* + * 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.db.it.utils.FlushHoldController; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.env.cluster.config.MppCommonConfig; +import org.apache.iotdb.it.env.cluster.config.MppJVMConfig; +import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.ClusterIT; +import org.apache.iotdb.itbase.category.LocalStandaloneIT; + +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.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; + +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; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * End-to-end regression ITs reproducing the 8 production-reachable scan defects (D1, D3, D4, D5, + * D7, D9, D10, D11) and altered-column predicate pushdown. Each test asserts the correct SQL + * result. + */ +@RunWith(IoTDBTestRunner.class) +@Category({LocalStandaloneIT.class, ClusterIT.class}) +public class IoTDBSeriesScanDefectIT { + + private static final long FLUSH_STATE_POLL_TIMEOUT_MS = 30_000L; + private static final long FLUSH_STATE_POLL_INTERVAL_MS = 20L; + + private static final Map FLUSH_HOLD_NODES = + new HashMap<>(); + private static FlushHoldController flushHoldController; + + @BeforeClass + public static void setUp() throws Exception { + EnvFactory.getEnv() + .getConfig() + .getCommonConfig() + .setEnableSeqSpaceCompaction(false) + .setEnableUnseqSpaceCompaction(false) + .setEnableCrossSpaceCompaction(false) + .setMaxNumberOfPointsInPage(3) + .setMemtableSizeThreshold(64L * 1024 * 1024) + .setDataRegionGroupExtensionPolicy("CUSTOM") + .setDefaultDataRegionGroupNumPerDatabase(1); + if (EnvFactory.getEnv().getConfig().getDataNodeCommonConfig() instanceof MppCommonConfig) { + Properties properties = new Properties(); + properties.setProperty("flush_thread_count", "1"); + properties.setProperty("enable_timed_flush_seq_memtable", "false"); + properties.setProperty("enable_timed_flush_unseq_memtable", "false"); + ((MppCommonConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig()) + .updateProperties(properties); + } + flushHoldController = + new FlushHoldController( + (MppJVMConfig) EnvFactory.getEnv().getConfig().getDataNodeJVMConfig()); + boolean initialized = false; + try { + EnvFactory.getEnv().initClusterEnvironment(); + for (DataNodeWrapper wrapper : EnvFactory.getEnv().getDataNodeWrapperList()) { + FLUSH_HOLD_NODES.put(wrapper, flushHoldController.connect(wrapper)); + } + initialized = true; + } finally { + flushHoldController.restoreLaunchEnvironment(); + if (!initialized) { + try { + EnvFactory.getEnv().cleanClusterEnvironment(); + } finally { + flushHoldController.close(); + flushHoldController = null; + FLUSH_HOLD_NODES.clear(); + } + } + } + } + + @AfterClass + public static void tearDown() throws Exception { + try { + if (flushHoldController != null) { + try { + flushHoldController.reset(); + } catch (IOException ignored) { + // Best-effort release before cluster shutdown. + } + } + } finally { + try { + EnvFactory.getEnv().cleanClusterEnvironment(); + } finally { + if (flushHoldController != null) { + flushHoldController.close(); + flushHoldController = null; + } + FLUSH_HOLD_NODES.clear(); + } + } + } + + /** + * 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=INT64", + // 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)", + // Seq memtable on blocker so FLUSH root.d1a TRUE enters the hold latch on the sole flush + // worker + "INSERT INTO root.d1a.blocker(time, s0) VALUES (1, 1)" + }); + + runDeleteAndQueryWhileFlushing( + "root.d1a", + "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=INT64", + // Seed blocker seq file at high timestamp so the subsequent blocker write lands in UNSEQ + "INSERT INTO root.d1b.blocker(time, s0) VALUES (1000000, 1)", + "FLUSH root.d1b" + }); + 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\""); + + // Unseq memtable on blocker so FLUSH root.d1b FALSE enters the hold latch on the sole flush + // worker + executeSql("INSERT INTO root.d1b.blocker(time, s0) VALUES (1, 1)"); + + runDeleteAndQueryWhileFlushing( + "root.d1b", + "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,"}); + } + + /** + * After {@code ALTER TIMESERIES ... SET DATA TYPE STRING} on an aligned column, a pushed-down + * string predicate must be re-evaluated against converted values rather than accepting the whole + * page via pre-alteration numeric extrema (e.g. {@code '1'} and {@code '100'} both sort before + * {@code '2'}). + */ + @Test + public void testAlterAlignedDataTypeToStringReevaluatesPushDownPredicate() { + prepareData( + new String[] { + "CREATE DATABASE root.reviewalter", + "CREATE ALIGNED TIMESERIES root.reviewalter.d(s0 INT32, s1 INT32)", + "INSERT INTO root.reviewalter.d(time, s0, s1) ALIGNED VALUES (1, 1, 10), (2, 2, 20), (3, 100, 30)", + "FLUSH root.reviewalter", + "ALTER TIMESERIES root.reviewalter.d.s0 SET DATA TYPE STRING", + // Multi-page chunk (max_number_of_points_in_page = 3): page 1 [1, 2, 100], page 2 [2, + // 200] + "CREATE ALIGNED TIMESERIES root.reviewalter.d_multi(s0 INT32, s1 INT32)", + "INSERT INTO root.reviewalter.d_multi(time, s0, s1) ALIGNED VALUES (1, 1, 10), (2, 2, 20), (3, 100, 30), (4, 2, 40), (5, 200, 50)", + "FLUSH root.reviewalter", + "ALTER TIMESERIES root.reviewalter.d_multi.s0 SET DATA TYPE STRING" + }); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewalter.d WHERE s0 != '2'", + "Time,root.reviewalter.d.s0,root.reviewalter.d.s1,", + new String[] {"1,1,10,", "3,100,30,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewalter.d WHERE s0 < '2'", + "Time,root.reviewalter.d.s0,root.reviewalter.d.s1,", + new String[] {"1,1,10,", "3,100,30,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewalter.d WHERE s1 > 0 LIMIT 1", + "Time,root.reviewalter.d.s0,root.reviewalter.d.s1,", + new String[] {"1,1,10,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewalter.d_multi WHERE s0 != '2'", + "Time,root.reviewalter.d_multi.s0,root.reviewalter.d_multi.s1,", + new String[] {"1,1,10,", "3,100,30,", "5,200,50,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewalter.d_multi WHERE s0 != '2' ORDER BY time DESC", + "Time,root.reviewalter.d_multi.s0,root.reviewalter.d_multi.s1,", + new String[] {"5,200,50,", "3,100,30,", "1,1,10,"}); + + // BOOLEAN -> STRING: BooleanStatistics throws on getMinValue(), so type validity must be + // checked before allSatisfy(pageReader) while unaffected columns keep the LIMIT fast path. + prepareData( + new String[] { + "CREATE DATABASE root.reviewbool", + "CREATE ALIGNED TIMESERIES root.reviewbool.d(s0 BOOLEAN, s1 INT32)", + "INSERT INTO root.reviewbool.d(time, s0, s1) ALIGNED VALUES (1, true, 10), (2, false, 20), (3, true, 30)", + "FLUSH root.reviewbool", + "ALTER TIMESERIES root.reviewbool.d.s0 SET DATA TYPE STRING", + // Multi-page BOOLEAN chunk (max_number_of_points_in_page = 3) + "CREATE ALIGNED TIMESERIES root.reviewbool.d_multi(s0 BOOLEAN, s1 INT32)", + "INSERT INTO root.reviewbool.d_multi(time, s0, s1) ALIGNED VALUES (1, true, 10), (2, false, 20), (3, true, 30), (4, false, 40), (5, true, 50)", + "FLUSH root.reviewbool", + "ALTER TIMESERIES root.reviewbool.d_multi.s0 SET DATA TYPE STRING" + }); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewbool.d WHERE s0 != 'false'", + "Time,root.reviewbool.d.s0,root.reviewbool.d.s1,", + new String[] {"1,true,10,", "3,true,30,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewbool.d WHERE s0 = 'true'", + "Time,root.reviewbool.d.s0,root.reviewbool.d.s1,", + new String[] {"1,true,10,", "3,true,30,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewbool.d WHERE s1 > 0 LIMIT 1", + "Time,root.reviewbool.d.s0,root.reviewbool.d.s1,", + new String[] {"1,true,10,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewbool.d_multi WHERE s0 != 'false'", + "Time,root.reviewbool.d_multi.s0,root.reviewbool.d_multi.s1,", + new String[] {"1,true,10,", "3,true,30,", "5,true,50,"}); + resultSetEqualTest( + "SELECT s0, s1 FROM root.reviewbool.d_multi WHERE s0 != 'false' ORDER BY time DESC", + "Time,root.reviewbool.d_multi.s0,root.reviewbool.d_multi.s1,", + new String[] {"5,true,50,", "3,true,30,", "1,true,10,"}); + } + + 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 runDeleteAndQueryWhileFlushing( + String database, + String blockerFlushSql, + String targetFlushSql, + String deleteSql, + String querySql, + String expectedHeader, + String[] expectedRows) + throws Exception { + List replicas = findDataRegionReplicas(database); + assertFalse("Expected at least one DataRegion replica for " + database, replicas.isEmpty()); + + // Wait for any prior flush (e.g. setup FLUSH) to finish before arming the blocker hold latch. + awaitCondition( + "flush queue to become idle before starting blocker flush", + () -> + allReplicasMatch( + replicas, + replica -> { + FlushHoldController.Status status = replica.status(); + return status.getWorkingTasks() == 0 && status.getWaitingTasks() == 0; + }), + () -> false, + () -> describeReplicas(replicas)); + + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blockerFlushFuture = null; + Future targetFlushFuture = null; + Throwable primaryFailure = null; + try { + for (RegionReplica replica : replicas) { + replica.node.arm(replica.storageGroup); + } + + Future submittedBlocker = + executor.submit( + () -> { + executeSqlUnchecked(blockerFlushSql); + return null; + }); + blockerFlushFuture = submittedBlocker; + // Wait until the blocker FLUSH hits the hold latch on the sole flush worker of every replica + awaitCondition( + "blocker flush to hold the sole flush worker on all " + replicas.size() + " replica(s)", + () -> allReplicasMatch(replicas, replica -> replica.status().isHeld()), + submittedBlocker::isDone, + () -> "blockerDone=" + submittedBlocker.isDone() + ", " + describeReplicas(replicas)); + assertFalse( + "Blocker flush finished before target flush started", blockerFlushFuture.isDone()); + + Future submittedTarget = + executor.submit( + () -> { + executeSqlUnchecked(targetFlushSql); + return null; + }); + targetFlushFuture = submittedTarget; + // Wait until the target FLUSH moves d1's working memtable into flushingMemTables and queues + // behind the held blocker on every replica DataNode + awaitCondition( + "target flush to queue behind held blocker on all " + replicas.size() + " replica(s)", + () -> + allReplicasMatch( + replicas, + replica -> { + FlushHoldController.Status status = replica.status(); + return status.isHeld() && status.getWaitingTasks() >= 1; + }), + () -> submittedBlocker.isDone() || submittedTarget.isDone(), + () -> + "blockerDone=" + + submittedBlocker.isDone() + + ", targetDone=" + + submittedTarget.isDone() + + ", " + + describeReplicas(replicas)); + assertFalse("Blocker flush finished before DELETE", blockerFlushFuture.isDone()); + assertFalse("Target flush finished before DELETE", targetFlushFuture.isDone()); + + executeSql(deleteSql); + resultSetEqualTest(querySql, expectedHeader, expectedRows); + + // Verify the blocker remained held on the latch and d1's memtable stayed queued in + // flushingMemTables through both DELETE and SELECT. + assertFalse("Blocker flush finished before SELECT completed", blockerFlushFuture.isDone()); + assertFalse("Target flush finished before SELECT completed", targetFlushFuture.isDone()); + for (RegionReplica replica : replicas) { + FlushHoldController.Status status = replica.status(); + assertTrue( + "Blocker flush released before SELECT completed on " + replica + ": " + status, + status.isHeld()); + assertFalse( + "Blocker flush hold timed out before SELECT completed on " + replica + ": " + status, + status.isTimedOut()); + assertFalse( + "Blocker flush hold interrupted before SELECT completed on " + replica + ": " + status, + status.isInterrupted()); + assertTrue( + "Target flush dequeued before SELECT completed on " + replica + ": " + status, + status.getWaitingTasks() >= 1); + } + } catch (Throwable t) { + primaryFailure = t; + throw t; + } finally { + Throwable cleanupFailure = null; + try { + releaseAll(replicas); + } catch (Throwable t) { + cleanupFailure = t; + } + try { + if (blockerFlushFuture != null) { + blockerFlushFuture.get(60, TimeUnit.SECONDS); + } + } catch (Throwable t) { + cleanupFailure = combineFailures(cleanupFailure, t); + } + try { + if (targetFlushFuture != null) { + targetFlushFuture.get(60, TimeUnit.SECONDS); + } + } catch (Throwable t) { + cleanupFailure = combineFailures(cleanupFailure, t); + } + executor.shutdownNow(); + try { + if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { + cleanupFailure = + combineFailures( + cleanupFailure, new AssertionError("Flush executor did not terminate in 30s")); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + cleanupFailure = combineFailures(cleanupFailure, e); + } + if (cleanupFailure != null) { + if (primaryFailure != null) { + primaryFailure.addSuppressed(cleanupFailure); + } else if (cleanupFailure instanceof Exception) { + throw (Exception) cleanupFailure; + } else if (cleanupFailure instanceof Error) { + throw (Error) cleanupFailure; + } else { + throw new RuntimeException(cleanupFailure); + } + } + } + } + + private static List findDataRegionReplicas(String database) throws SQLException { + List replicas = new ArrayList<>(); + try (Connection connection = EnvFactory.getEnv().getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SHOW REGIONS")) { + while (resultSet.next()) { + if ("DataRegion".equals(resultSet.getString("Type")) + && database.equals(resultSet.getString("Database"))) { + int regionId = resultSet.getInt("RegionId"); + int dataNodeId = resultSet.getInt("DataNodeId"); + DataNodeWrapper wrapper = + EnvFactory.getEnv() + .dataNodeIdToWrapper(dataNodeId) + .orElseThrow( + () -> new AssertionError("Missing DataNodeWrapper for id " + dataNodeId)); + FlushHoldController.Node node = FLUSH_HOLD_NODES.get(wrapper); + assertNotNull("Missing FlushHoldController.Node for DataNode " + dataNodeId, node); + replicas.add(new RegionReplica(dataNodeId, database + "-" + regionId, node)); + } + } + } + return replicas; + } + + private static boolean allReplicasMatch( + List replicas, CheckedPredicate predicate) throws Exception { + for (RegionReplica replica : replicas) { + if (!predicate.test(replica)) { + return false; + } + } + return true; + } + + private static void releaseAll(List replicas) throws IOException { + IOException failure = null; + for (RegionReplica replica : replicas) { + try { + replica.node.release(replica.storageGroup); + } catch (IOException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); + } + } + } + if (failure != null) { + throw failure; + } + } + + private static String describeReplicas(List replicas) { + StringBuilder builder = new StringBuilder("["); + for (int i = 0; i < replicas.size(); i++) { + if (i > 0) { + builder.append(", "); + } + RegionReplica replica = replicas.get(i); + builder.append(replica).append('='); + try { + builder.append(replica.status()); + } catch (IOException e) { + builder.append("statusError(").append(e.getMessage()).append(')'); + } + } + return builder.append(']').toString(); + } + + private static Throwable combineFailures(Throwable first, Throwable next) { + if (first == null) { + return next; + } + first.addSuppressed(next); + return first; + } + + private static void awaitCondition( + String description, + CheckedBooleanSupplier condition, + BooleanSupplier abortCondition, + CheckedSupplier diagnostics) + throws Exception { + long deadline = System.currentTimeMillis() + FLUSH_STATE_POLL_TIMEOUT_MS; + while (System.currentTimeMillis() < deadline) { + if (condition.getAsBoolean()) { + return; + } + if (abortCondition.getAsBoolean()) { + fail("Aborted waiting for " + description + " (" + diagnostics.get() + ")"); + } + Thread.sleep(FLUSH_STATE_POLL_INTERVAL_MS); + } + assertTrue( + "Timed out waiting for " + description + " (" + diagnostics.get() + ")", + condition.getAsBoolean()); + } + + private static final class RegionReplica { + private final int dataNodeId; + private final String storageGroup; + private final FlushHoldController.Node node; + + private RegionReplica(int dataNodeId, String storageGroup, FlushHoldController.Node node) { + this.dataNodeId = dataNodeId; + this.storageGroup = storageGroup; + this.node = node; + } + + private FlushHoldController.Status status() throws IOException { + return node.status(storageGroup); + } + + @Override + public String toString() { + return "dn=" + dataNodeId + "(" + storageGroup + ")"; + } + } + + @FunctionalInterface + private interface CheckedBooleanSupplier { + boolean getAsBoolean() throws Exception; + } + + @FunctionalInterface + private interface CheckedPredicate { + boolean test(T value) throws Exception; + } + + @FunctionalInterface + private interface CheckedSupplier { + T get() throws Exception; + } + + 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/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldAgent.java b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldAgent.java new file mode 100644 index 0000000000000..f8bce0878708e --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldAgent.java @@ -0,0 +1,278 @@ +/* + * 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.utils; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.Instrumentation; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.ProtectionDomain; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Launch-time instrumentation for IT child DataNodes that deterministically holds the first {@code + * MemTableFlushTask#syncFlushMemTable()} call of an armed DataRegion on a bounded test-controlled + * latch. No production classes are modified on disk, and the gate runs at entry of {@code + * syncFlushMemTable()} before any flush or TsFileProcessor lock is acquired. + */ +public final class FlushHoldAgent { + + private static final String TARGET_CLASS = + "org/apache/iotdb/db/storageengine/dataregion/flush/MemTableFlushTask"; + private static final String TARGET_METHOD = "syncFlushMemTable"; + private static final String TARGET_DESCRIPTOR = "()V"; + private static final String FLUSH_MANAGER_CLASS = + "org.apache.iotdb.db.storageengine.dataregion.flush.FlushManager"; + private static final long HOLD_TIMEOUT_MS = 120_000L; + + private static final Map GATES = new ConcurrentHashMap<>(); + + private FlushHoldAgent() {} + + public static void premain(String directory, Instrumentation instrumentation) throws IOException { + instrumentation.addTransformer(new Transformer()); + ServerSocket server = new ServerSocket(0, 16, InetAddress.getLoopbackAddress()); + Thread controller = new Thread(() -> serve(server), "flush-hold-it-controller"); + controller.setDaemon(true); + controller.start(); + long pid = ProcessHandle.current().pid(); + Path tmp = Paths.get(directory, pid + ".port.tmp"); + Path endpoint = Paths.get(directory, pid + ".port"); + Files.write( + tmp, + Collections.singletonList(Integer.toString(server.getLocalPort())), + StandardCharsets.UTF_8); + try { + Files.move( + tmp, endpoint, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(tmp, endpoint, StandardCopyOption.REPLACE_EXISTING); + } + } + + private static void serve(ServerSocket server) { + while (!server.isClosed()) { + try (Socket socket = server.accept(); + DataInputStream input = new DataInputStream(socket.getInputStream()); + DataOutputStream output = new DataOutputStream(socket.getOutputStream())) { + socket.setSoTimeout(5_000); + Map response; + try { + String command = input.readUTF(); + String storageGroup = input.readUTF(); + response = handleCommand(command, storageGroup); + } catch (Throwable e) { + response = Collections.singletonMap("error", e.toString()); + } + output.writeInt(response.size()); + for (Map.Entry entry : response.entrySet()) { + output.writeUTF(entry.getKey()); + output.writeUTF(entry.getValue()); + } + output.flush(); + } catch (IOException e) { + // A failed control connection must not disable subsequent release/cleanup requests. + System.err.println("Flush hold IT control connection failed: " + e); + } + } + } + + private static Map handleCommand(String command, String storageGroup) + throws Exception { + switch (command) { + case "arm": + Gate existing = GATES.putIfAbsent(storageGroup, new Gate()); + if (existing != null) { + throw new IllegalStateException("Flush gate already armed for " + storageGroup); + } + return Collections.emptyMap(); + case "status": + return buildStatus(storageGroup); + case "release": + Gate toRelease = GATES.remove(storageGroup); + if (toRelease != null) { + toRelease.release(); + } + return Collections.emptyMap(); + case "reset": + for (Gate gate : GATES.values()) { + gate.release(); + } + GATES.clear(); + return Collections.emptyMap(); + default: + throw new IllegalArgumentException("Unknown command: " + command); + } + } + + private static Map buildStatus(String storageGroup) throws Exception { + Map result = new HashMap<>(); + Gate gate = GATES.get(storageGroup); + result.put("armed", Boolean.toString(gate != null)); + result.put("held", Boolean.toString(gate != null && gate.held.get())); + result.put("timedOut", Boolean.toString(gate != null && gate.timedOut.get())); + result.put("interrupted", Boolean.toString(gate != null && gate.interrupted.get())); + Object flushManager = Class.forName(FLUSH_MANAGER_CLASS).getMethod("getInstance").invoke(null); + Object working = + flushManager.getClass().getMethod("getNumberOfWorkingTasks").invoke(flushManager); + Object waiting = + flushManager.getClass().getMethod("getNumberOfWaitingTasks").invoke(flushManager); + result.put("workingTasks", working.toString()); + result.put("waitingTasks", waiting.toString()); + return result; + } + + /** + * Invoked by bytecode injected at entry of {@code MemTableFlushTask#syncFlushMemTable()}. Never + * throws so that a test control timeout or interrupt cannot trip DataNode unrecoverable-error + * handling. + */ + public static void beforeSyncFlush(Object flushTask) { + String storageGroup = readStorageGroup(flushTask); + if (storageGroup == null) { + return; + } + Gate gate = GATES.get(storageGroup); + if (gate == null || !gate.claimHold()) { + return; + } + gate.awaitRelease(); + } + + private static String readStorageGroup(Object flushTask) { + if (flushTask == null) { + return null; + } + try { + Field field = flushTask.getClass().getDeclaredField("storageGroup"); + field.setAccessible(true); + Object value = field.get(flushTask); + return value == null ? null : value.toString(); + } catch (ReflectiveOperationException e) { + return null; + } + } + + private static final class Gate { + private final AtomicBoolean claimed = new AtomicBoolean(false); + private final AtomicBoolean held = new AtomicBoolean(false); + private final AtomicBoolean timedOut = new AtomicBoolean(false); + private final AtomicBoolean interrupted = new AtomicBoolean(false); + private final CountDownLatch releaseLatch = new CountDownLatch(1); + + private boolean claimHold() { + return claimed.compareAndSet(false, true); + } + + private void release() { + releaseLatch.countDown(); + } + + private void awaitRelease() { + held.set(true); + try { + if (!releaseLatch.await(HOLD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + timedOut.set(true); + } + } catch (InterruptedException e) { + interrupted.set(true); + Thread.currentThread().interrupt(); + } finally { + held.set(false); + } + } + } + + private static final class Transformer implements ClassFileTransformer { + @Override + public byte[] transform( + ClassLoader loader, + String className, + Class classBeingRedefined, + ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + if (!TARGET_CLASS.equals(className)) { + return null; + } + ClassReader reader = new ClassReader(classfileBuffer); + ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS); + reader.accept(new HookClassVisitor(writer), 0); + return writer.toByteArray(); + } + } + + private static final class HookClassVisitor extends ClassVisitor { + private HookClassVisitor(ClassVisitor visitor) { + super(Opcodes.ASM9, visitor); + } + + @Override + public MethodVisitor visitMethod( + int access, String name, String descriptor, String signature, String[] exceptions) { + MethodVisitor visitor = super.visitMethod(access, name, descriptor, signature, exceptions); + if (!TARGET_METHOD.equals(name) || !TARGET_DESCRIPTOR.equals(descriptor)) { + return visitor; + } + return new HookMethodVisitor(visitor); + } + } + + private static final class HookMethodVisitor extends MethodVisitor { + private HookMethodVisitor(MethodVisitor visitor) { + super(Opcodes.ASM9, visitor); + } + + @Override + public void visitCode() { + super.visitCode(); + super.visitVarInsn(Opcodes.ALOAD, 0); + super.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(FlushHoldAgent.class), + "beforeSyncFlush", + "(Ljava/lang/Object;)V", + false); + } + } +} diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldController.java b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldController.java new file mode 100644 index 0000000000000..5dc675a82a480 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/FlushHoldController.java @@ -0,0 +1,295 @@ +/* + * 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.utils; + +import org.apache.iotdb.it.env.cluster.config.MppJVMConfig; +import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; + +import org.awaitility.Awaitility; +import org.objectweb.asm.ClassReader; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +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.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Owns the temporary {@link FlushHoldAgent} jar, child-JVM launch options, and bounded loopback + * control connections for deterministically holding and releasing blocker flushes in ITs. + */ +public final class FlushHoldController implements AutoCloseable { + + private static final int CONNECT_TIMEOUT_MS = 5_000; + private static final int READ_TIMEOUT_MS = 5_000; + + private final Path directory; + private final List nodes = new ArrayList<>(); + private final MppJVMConfig dataNodeJvmConfig; + private final List previousJvmOptions; + private boolean launchEnvironmentRestored; + + public FlushHoldController(MppJVMConfig dataNodeJvmConfig) throws Exception { + this.dataNodeJvmConfig = dataNodeJvmConfig; + this.previousJvmOptions = new ArrayList<>(dataNodeJvmConfig.getJvmOptions()); + this.directory = Files.createTempDirectory(Paths.get("target").toAbsolutePath(), "flush-hold-"); + try { + Path jar = directory.resolve("agent.jar"); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().putValue("Premain-Class", FlushHoldAgent.class.getName()); + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) { + addClass(output, FlushHoldAgent.class); + // Keep ASM inside the temporary agent so child-process classpaths need no test artifacts. + Path asm = + Paths.get( + ClassReader.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + try (JarFile source = new JarFile(asm.toFile())) { + for (JarEntry entry : source.stream().collect(Collectors.toList())) { + if (entry.getName().startsWith("org/objectweb/asm/") && !entry.isDirectory()) { + output.putNextEntry(new JarEntry(entry.getName())); + try (InputStream input = source.getInputStream(entry)) { + copy(input, output); + } + output.closeEntry(); + } + } + } + } + List launchOptions = new ArrayList<>(previousJvmOptions); + launchOptions.add("-javaagent:" + jar + "=" + directory); + dataNodeJvmConfig.setJvmOptions(launchOptions); + } catch (Throwable t) { + try { + close(); + } catch (IOException suppressed) { + t.addSuppressed(suppressed); + } + throw t; + } + } + + /** Restores DataNode JVM options immediately after cluster startup (also on startup failure). */ + public void restoreLaunchEnvironment() { + if (launchEnvironmentRestored) { + return; + } + dataNodeJvmConfig.setJvmOptions(previousJvmOptions); + launchEnvironmentRestored = true; + } + + public Node connect(DataNodeWrapper wrapper) throws Exception { + long pid = wrapper.getInstance().pid(); + Path endpoint = directory.resolve(pid + ".port"); + Awaitility.await() + .atMost(30, TimeUnit.SECONDS) + .until( + () -> + Files.isRegularFile(endpoint) + && !Files.readAllLines(endpoint, StandardCharsets.UTF_8).isEmpty()); + int port = Integer.parseInt(Files.readAllLines(endpoint, StandardCharsets.UTF_8).get(0).trim()); + Node node = new Node(port); + nodes.add(node); + return node; + } + + /** Releases all armed gates across connected DataNodes. */ + public void reset() throws IOException { + IOException failure = null; + for (Node node : nodes) { + try { + node.reset(); + } catch (IOException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); + } + } + } + if (failure != null) { + throw failure; + } + } + + /** + * Called after child DataNode processes have stopped so temporary jars can be deleted cleanly. + */ + @Override + public void close() throws IOException { + restoreLaunchEnvironment(); + if (!Files.exists(directory)) { + return; + } + try (Stream paths = Files.walk(directory)) { + for (Path path : paths.sorted(Comparator.reverseOrder()).collect(Collectors.toList())) { + Files.deleteIfExists(path); + } + } + } + + private static void addClass(JarOutputStream output, Class type) throws IOException { + String name = type.getName().replace('.', '/') + ".class"; + output.putNextEntry(new JarEntry(name)); + try (InputStream input = type.getClassLoader().getResourceAsStream(name)) { + if (input == null) { + throw new IOException("Missing agent class: " + name); + } + copy(input, output); + } + output.closeEntry(); + for (Class nested : type.getDeclaredClasses()) { + addClass(output, nested); + } + } + + private static void copy(InputStream input, JarOutputStream output) throws IOException { + byte[] buffer = new byte[8_192]; + int length; + while ((length = input.read(buffer)) != -1) { + output.write(buffer, 0, length); + } + } + + public static final class Status { + private final boolean armed; + private final boolean held; + private final boolean timedOut; + private final boolean interrupted; + private final int workingTasks; + private final int waitingTasks; + + private Status(Map values) { + this.armed = Boolean.parseBoolean(values.get("armed")); + this.held = Boolean.parseBoolean(values.get("held")); + this.timedOut = Boolean.parseBoolean(values.get("timedOut")); + this.interrupted = Boolean.parseBoolean(values.get("interrupted")); + this.workingTasks = Integer.parseInt(values.get("workingTasks")); + this.waitingTasks = Integer.parseInt(values.get("waitingTasks")); + } + + public boolean isArmed() { + return armed; + } + + public boolean isHeld() { + return held; + } + + public boolean isTimedOut() { + return timedOut; + } + + public boolean isInterrupted() { + return interrupted; + } + + public int getWorkingTasks() { + return workingTasks; + } + + public int getWaitingTasks() { + return waitingTasks; + } + + @Override + public String toString() { + return "Status{armed=" + + armed + + ", held=" + + held + + ", timedOut=" + + timedOut + + ", interrupted=" + + interrupted + + ", workingTasks=" + + workingTasks + + ", waitingTasks=" + + waitingTasks + + '}'; + } + } + + public static final class Node { + private final int port; + + private Node(int port) { + this.port = port; + } + + public void arm(String storageGroup) throws IOException { + request("arm", storageGroup); + } + + public Status status(String storageGroup) throws IOException { + return new Status(request("status", storageGroup)); + } + + public void release(String storageGroup) throws IOException { + request("release", storageGroup); + } + + public void reset() throws IOException { + request("reset", ""); + } + + private Map request(String command, String storageGroup) throws IOException { + try (Socket socket = new Socket()) { + socket.connect( + new InetSocketAddress(InetAddress.getLoopbackAddress(), port), CONNECT_TIMEOUT_MS); + socket.setSoTimeout(READ_TIMEOUT_MS); + try (DataOutputStream output = new DataOutputStream(socket.getOutputStream()); + DataInputStream input = new DataInputStream(socket.getInputStream())) { + output.writeUTF(command); + output.writeUTF(storageGroup); + output.flush(); + Map result = new HashMap<>(); + int size = input.readInt(); + for (int i = 0; i < size; i++) { + result.put(input.readUTF(), input.readUTF()); + } + if (result.containsKey("error")) { + throw new IOException("Flush hold IT controller: " + result.get("error")); + } + return result; + } + } + } + } +} diff --git a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java index ef3db3ca28f90..459708022568b 100644 --- a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -588,8 +588,6 @@ private StorageEngineMessages() {} // ======================== Read ======================== - public static final String MEM_CHUNK_READER_NOT_SUPPORT_METHOD = "mem chunk reader does not support this method"; - public static final String MEM_ALIGNED_PAGE_READER_TSBLOCK = "[memAlignedPageReader] TsBlock:{}"; public static final String AFTER_FILTER_CHUNK_METADATA_LIST = "After removed by filter Chunk meta data list is: "; public static final String AFTER_MODIFICATION_CHUNK_METADATA_LIST = "After modification Chunk meta data list is: "; public static final String TIME_DATA_SIZE_NOT_MATCH = "Time data size not match"; @@ -1750,7 +1748,6 @@ private StorageEngineMessages() {} // Additional auto-collected messages // --------------------------------------------------------------------------- public static final String MESSAGE_NO_LOAD_TSFILE_UUID_ARG_RECORDED_EXECUTE_LOAD_COMMAND_ARG_66722D80 = "No load TsFile uuid %s recorded for execute load command %s."; - public static final String EXCEPTION_NON_MINUS_ALIGNED_CHUNK_ONLY_HAS_ONE_MEASUREMENT_COMMA_BUT_MEASUREMENTINDEX_IS_E1A87F80 = "Non-aligned chunk only has one measurement, but measurementIndex is "; public static final String MESSAGE_LOAD_QUERY_FALLBACK_FAILED_FOR_DEVICE_ARG_MEASUREMENTS_ARG_IN_TSFILE_ARG_50771955 = "Load: Query fallback failed for device {} measurements {} in TsFile {}. "; public static final String MESSAGE_LOAD_FAILED_TO_INITIALIZE_QUERY_FALLBACK_FOR_TSFILE_ARG_AFTER_SCAN_PARSER_FAILURE_143B6037 = "Load: Failed to initialize query fallback for TsFile {} after scan parser failure."; public static final String MESSAGE_LOAD_SCAN_PARSER_DETECTED_A_CORRUPTED_SECTION_IN_TSFILE_ARG_AT_DEVICE_ARG_E2632421 = "Load: Scan parser detected a corrupted section in TsFile {} at device {}. "; diff --git a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java index d67165c837ac2..dce4c70aa82b1 100644 --- a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java +++ b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/StorageEngineMessages.java @@ -569,8 +569,6 @@ private StorageEngineMessages() {} // ======================== Read ======================== - public static final String MEM_CHUNK_READER_NOT_SUPPORT_METHOD = "内存 Chunk 读取器不支持此方法"; - public static final String MEM_ALIGNED_PAGE_READER_TSBLOCK = "[memAlignedPageReader] TsBlock:{}"; public static final String AFTER_FILTER_CHUNK_METADATA_LIST = "按过滤器移除后的 Chunk 元数据列表: "; public static final String AFTER_MODIFICATION_CHUNK_METADATA_LIST = "修改后的 Chunk 元数据列表: "; public static final String TIME_DATA_SIZE_NOT_MATCH = "时间数据大小不匹配"; @@ -1660,7 +1658,6 @@ private StorageEngineMessages() {} // Additional auto-collected messages // --------------------------------------------------------------------------- public static final String MESSAGE_NO_LOAD_TSFILE_UUID_ARG_RECORDED_EXECUTE_LOAD_COMMAND_ARG_66722D80 = "未记录 Load TsFile uuid %s,执行 Load 命令为 %s。"; - public static final String EXCEPTION_NON_MINUS_ALIGNED_CHUNK_ONLY_HAS_ONE_MEASUREMENT_COMMA_BUT_MEASUREMENTINDEX_IS_E1A87F80 = "非对齐 chunk 只有一个 measurement,但 measurementIndex 为 "; public static final String MESSAGE_LOAD_QUERY_FALLBACK_FAILED_FOR_DEVICE_ARG_MEASUREMENTS_ARG_IN_TSFILE_ARG_50771955 = "Load:设备 {} 测点 {} 在 TsFile {} 中的查询回退失败。"; public static final String MESSAGE_LOAD_FAILED_TO_INITIALIZE_QUERY_FALLBACK_FOR_TSFILE_ARG_AFTER_SCAN_PARSER_FAILURE_143B6037 = "Load:scan parser 失败后,TsFile {} 的查询回退初始化失败。"; public static final String MESSAGE_LOAD_SCAN_PARSER_DETECTED_A_CORRUPTED_SECTION_IN_TSFILE_ARG_AT_DEVICE_ARG_E2632421 = "Load:scan parser 在 TsFile {} 的设备 {} 处检测到损坏的数据段。"; 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/AlignedSeriesScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanOperator.java index e06b3d17b310a..6710ea8963816 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/AlignedSeriesScanOperator.java @@ -52,19 +52,13 @@ public AlignedSeriesScanOperator( AlignedFullPath seriesPath, Ordering scanOrder, SeriesScanOptions seriesScanOptions, - boolean queryAllSensors, List dataTypes, int maxTsBlockLineNum) { this.sourceId = sourceId; this.operatorContext = context; this.seriesScanUtil = new AlignedSeriesScanUtil( - seriesPath, - scanOrder, - seriesScanOptions, - context.getInstanceContext(), - queryAllSensors, - dataTypes); + seriesPath, scanOrder, seriesScanOptions, context.getInstanceContext(), dataTypes); this.valueColumnCount = seriesPath.getColumnNum(); this.maxReturnSize = Math.min( 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..338cd6838ca6d 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,11 +33,15 @@ 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; import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -45,12 +49,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; @@ -60,7 +58,7 @@ public AlignedSeriesScanUtil( Ordering scanOrder, SeriesScanOptions scanOptions, FragmentInstanceContext context) { - this(seriesPath, scanOrder, scanOptions, context, false, null); + this(seriesPath, scanOrder, scanOptions, context, null); } public AlignedSeriesScanUtil( @@ -68,7 +66,6 @@ public AlignedSeriesScanUtil( Ordering scanOrder, SeriesScanOptions scanOptions, FragmentInstanceContext context, - boolean queryAllSensors, List givenDataTypes) { super(seriesPath, scanOrder, scanOptions, context); isAligned = true; @@ -78,7 +75,6 @@ public AlignedSeriesScanUtil( : seriesPath.getSchemaList().stream() .map(IMeasurementSchema::getType) .collect(Collectors.toList()); - this.queryAllSensors = queryAllSensors; this.ignoreAllNullRows = context.isIgnoreAllNullRows(); } @@ -116,10 +112,153 @@ protected IPointReader getPointReader(TsBlock tsBlock) { } @Override - protected boolean timeAllSelected(IMetadata metadata) { - if (queryAllSensors || metadata.getMeasurementCount() == 0) { + 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()); + } + + @Override + protected boolean canUseTimeStatistics(IMetadata metadata) { + return canUseAlignedTimeStatistics(metadata); + } + + private boolean canUseAlignedTimeStatistics(IMetadata metadata) { + if (!ignoreAllNullRows || metadata == null) { + return true; + } + return timeAllSelected(metadata) || hasSingleNonNullMeasurement(metadata); + } + + private boolean hasSingleNonNullMeasurement(IMetadata metadata) { + int nonNullCount = 0; + for (int i = 0, count = metadata.getMeasurementCount(); i < count; i++) { + Statistics valueStats = metadata.getMeasurementStatistics(i).orElse(null); + if (isNonEmpty(valueStats) && ++nonNullCount > 1) { + return false; + } + } + return nonNullCount == 1; + } + + @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 (isNonEmpty(valueStats)) { + if (++nonNullCount > 1) { + return timeStatistics; + } + singleNonNullMeasurementStatistics = valueStats; + } + } + return nonNullCount == 1 ? singleNonNullMeasurementStatistics : timeStatistics; + } + + private boolean timeAllSelected(IMetadata metadata) { + if (!ignoreAllNullRows || metadata.getMeasurementCount() == 0) { return true; } - return metadata.timeAllSelected(); + return metadata.timeAllSelected() || allTimestampsCoveredByDisjointMeasurements(metadata); + } + + private boolean allTimestampsCoveredByDisjointMeasurements(IMetadata metadata) { + Statistics timeStats = metadata.getTimeStatistics(); + int measurementCount = metadata.getMeasurementCount(); + if (timeStats == null || timeStats.isEmpty() || measurementCount < 2) { + return false; + } + long expectedCount = timeStats.getCount(); + if (measurementCount == 2) { + Statistics first = metadata.getMeasurementStatistics(0).orElse(null); + Statistics second = metadata.getMeasurementStatistics(1).orElse(null); + return isNonEmpty(first) + && isNonEmpty(second) + && first.getCount() == expectedCount - second.getCount() + && areDisjoint(first, second); + } + List> nonEmptyStats = collectCoveredMeasurementStats(metadata, expectedCount); + return !nonEmptyStats.isEmpty() && areAllDisjoint(nonEmptyStats); + } + + private static List> collectCoveredMeasurementStats( + IMetadata metadata, long expectedCount) { + int measurementCount = metadata.getMeasurementCount(); + List> nonEmptyStats = new ArrayList<>(measurementCount); + long countSum = 0; + for (int i = 0; i < measurementCount; i++) { + Statistics valueStats = metadata.getMeasurementStatistics(i).orElse(null); + if (!isNonEmpty(valueStats)) { + continue; + } + if (valueStats.getCount() > expectedCount - countSum) { + return Collections.emptyList(); + } + countSum += valueStats.getCount(); + nonEmptyStats.add(valueStats); + } + return countSum == expectedCount && nonEmptyStats.size() >= 2 + ? nonEmptyStats + : Collections.emptyList(); + } + + private static boolean areAllDisjoint(List> statsList) { + statsList.sort(Comparator.comparingLong(Statistics::getStartTime)); + for (int i = 1; i < statsList.size(); i++) { + if (statsList.get(i - 1).getEndTime() >= statsList.get(i).getStartTime()) { + return false; + } + } + return true; + } + + private static boolean areDisjoint(Statistics first, Statistics second) { + return first.getEndTime() < second.getStartTime() || second.getEndTime() < first.getStartTime(); + } + + private static boolean isNonEmpty(Statistics statistics) { + return statistics != null && !statistics.isEmpty(); } } 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..c0bb7f4438d3f 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 @@ -37,9 +37,7 @@ import org.apache.iotdb.db.storageengine.dataregion.read.QueryDataSource; import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.DiskAlignedChunkLoader; import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.DiskChunkLoader; -import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.MemAlignedPageReader; import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.MemChunkLoader; -import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.MemPageReader; import org.apache.iotdb.db.storageengine.dataregion.read.reader.common.DescPriorityMergeReader; import org.apache.iotdb.db.storageengine.dataregion.read.reader.common.MergeReaderPriority; import org.apache.iotdb.db.storageengine.dataregion.read.reader.common.NoDataPointReader; @@ -69,8 +67,10 @@ 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.page.ValuePageReader; import org.apache.tsfile.read.reader.series.PaginationController; import org.apache.tsfile.utils.Accountable; import org.apache.tsfile.utils.RamUsageEstimator; @@ -119,16 +119,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 +347,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. @@ -465,10 +469,11 @@ private void filterFirstChunkMetadata() { } Filter globalTimeFilter = scanOptions.getGlobalTimeFilter(); - if (filterAllSatisfy(globalTimeFilter, firstChunkMetadata) + if (paginationController.hasCurOffset() + && filterAllSatisfy(globalTimeFilter, firstChunkMetadata) && filterAllSatisfy(pushDownFilter, firstChunkMetadata) - && timeAllSelected(firstChunkMetadata)) { - long rowCount = firstChunkMetadata.getStatistics().getCount(); + && canUseTimeStatistics(firstChunkMetadata)) { + long rowCount = currentChunkTimeStatistics().getCount(); if (paginationController.hasCurOffset(rowCount)) { skipCurrentChunk(); paginationController.consumeOffset(rowCount); @@ -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,10 +708,8 @@ private void unpackOneChunkMetaData(IChunkMetadata chunkMetaData) throws IOExcep } else { tsFile = null; } - if ((chunkLoader instanceof MemChunkLoader) - && ((MemChunkLoader) chunkLoader).isStreamingQueryMemChunk()) { - unpackOneFakeMemChunkMetaData( - chunkMetaData, (MemChunkLoader) chunkLoader, timestampInFileName); + if (chunkLoader instanceof MemChunkLoader memChunkLoader) { + unpackOneFakeMemChunkMetaData(chunkMetaData, memChunkLoader, timestampInFileName); return; } List pageReaderList = @@ -871,6 +871,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 +937,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 +957,27 @@ public TsBlock nextPage() throws IOException { return tsBlock == null ? null : getTransferedDataTypeTsBlock(tsBlock); } + // Modified aligned page readers evaluate pushDownFilter.allSatisfy(...) against pre-deletion + // or pre-type-alteration statistics, which can skip row-level filtering when a value deletion + // turns a referenced column's value into null or when a stored column's statistics are + // invalid for its altered target type (e.g. numeric -> STRING). Only fall back to + // decode-convert-then-filter when an affected value column can invalidate + // pushDownFilter.allSatisfy(...), keeping the LIMIT fast path intact for unaffected columns. + if (pushDownFilter != null + && firstPageReader.isModified() + && firstPageReader.getPageReader() instanceof AbstractAlignedPageReader alignedPageReader + && needsModifiedAlignedPagePushDownFallback(pushDownFilter, alignedPageReader)) { + 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 +994,165 @@ public TsBlock nextPage() throws IOException { } } + private boolean needsModifiedAlignedPagePushDownFallback( + Filter pushDownFilter, AbstractAlignedPageReader pageReader) { + List valuePageReaders = pageReader.getValuePageReaderList(); + List targetDataTypes = getTsDataTypeList(); + boolean hasTypeInvalidColumn = + hasValuePageWithInvalidTypeStatistics(valuePageReaders, targetDataTypes); + boolean hasModifiedColumn = hasModifiedValuePage(valuePageReaders); + if (!hasTypeInvalidColumn && !hasModifiedColumn) { + return false; + } + // Evaluate against a stats-aware adapter BEFORE ever calling pushDownFilter.allSatisfy on the + // raw pageReader: a type-altered column (e.g. BOOLEAN -> STRING) can throw when a STRING + // predicate calls BooleanStatistics.getMinValue(), or return a false allSatisfy on pre-alter + // numeric extrema. If the filter touches any type-invalid column, always take the decode -> + // convert -> filter path; if it only references unaffected columns, keep the LIMIT fast path. + boolean[] referencedTypeInvalidColumn = new boolean[1]; + boolean[] referencedModifiedColumn = new boolean[1]; + IMetadata statsAwareMetadata = + createStatsAwarePageMetadata( + pageReader, + valuePageReaders, + targetDataTypes, + true, + referencedTypeInvalidColumn, + referencedModifiedColumn); + boolean allSatisfyWithStatsAware = pushDownFilter.allSatisfy(statsAwareMetadata); + if (referencedTypeInvalidColumn[0]) { + return true; + } + if (allSatisfyWithStatsAware || !referencedModifiedColumn[0]) { + return false; + } + if (!hasTypeInvalidColumn) { + return pushDownFilter.allSatisfy(pageReader); + } + // A compound filter (e.g. modified_col > 0 AND altered_bool_col != 'false') can short-circuit + // on the modified column during the first pass above and still reach the type-altered column + // when re-evaluated against pre-deletion statistics. + IMetadata typeSafePageReaderMetadata = + createStatsAwarePageMetadata( + pageReader, + valuePageReaders, + targetDataTypes, + false, + referencedTypeInvalidColumn, + referencedModifiedColumn); + boolean allSatisfyOnTypeSafe = pushDownFilter.allSatisfy(typeSafePageReaderMetadata); + return referencedTypeInvalidColumn[0] || allSatisfyOnTypeSafe; + } + + private static IMetadata createStatsAwarePageMetadata( + AbstractAlignedPageReader pageReader, + List valuePageReaders, + List targetDataTypes, + boolean treatModifiedAsNull, + boolean[] referencedTypeInvalidColumn, + boolean[] referencedModifiedColumn) { + return new IMetadata() { + @Override + public Statistics getStatistics() { + return pageReader.getStatistics(); + } + + @Override + public Statistics getTimeStatistics() { + return pageReader.getTimeStatistics(); + } + + @Override + public Optional> getMeasurementStatistics( + int measurementIndex) { + if (isValuePageTypeStatisticsInvalid(valuePageReaders, targetDataTypes, measurementIndex)) { + referencedTypeInvalidColumn[0] = true; + return Optional.empty(); + } + return pageReader.getMeasurementStatistics(measurementIndex); + } + + @Override + public boolean hasNullValue(int measurementIndex) { + if (isValuePageTypeStatisticsInvalid(valuePageReaders, targetDataTypes, measurementIndex)) { + referencedTypeInvalidColumn[0] = true; + return true; + } + if (treatModifiedAsNull && isValuePageModified(valuePageReaders, measurementIndex)) { + referencedModifiedColumn[0] = true; + return true; + } + return pageReader.hasNullValue(measurementIndex); + } + + @Override + public boolean timeAllSelected() { + return pageReader.timeAllSelected(); + } + + @Override + public int getMeasurementCount() { + return pageReader.getMeasurementCount(); + } + }; + } + + private static boolean hasValuePageWithInvalidTypeStatistics( + List valuePageReaders, List targetDataTypes) { + for (int i = 0; i < valuePageReaders.size(); i++) { + if (isValuePageTypeStatisticsInvalid(valuePageReaders, targetDataTypes, i)) { + return true; + } + } + return false; + } + + private static boolean hasModifiedValuePage(List valuePageReaders) { + for (ValuePageReader valuePageReader : valuePageReaders) { + if (valuePageReader != null && valuePageReader.isModified()) { + return true; + } + } + return false; + } + + private static boolean isValuePageModified( + List valuePageReaders, int measurementIndex) { + if (measurementIndex < 0 || measurementIndex >= valuePageReaders.size()) { + return false; + } + ValuePageReader valuePageReader = valuePageReaders.get(measurementIndex); + return valuePageReader != null && valuePageReader.isModified(); + } + + private static boolean isValuePageTypeStatisticsInvalid( + List valuePageReaders, + List targetDataTypes, + int measurementIndex) { + if (measurementIndex < 0 || measurementIndex >= valuePageReaders.size()) { + return false; + } + ValuePageReader valuePageReader = valuePageReaders.get(measurementIndex); + return valuePageReader != null + && measurementIndex < targetDataTypes.size() + && !SchemaUtils.canUseStatisticsAfterAlter( + valuePageReader.getDataType(), targetDataTypes.get(measurementIndex)); + } + + 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()) { @@ -1076,10 +1260,11 @@ private void filterFirstPageReader() { } Filter globalTimeFilter = scanOptions.getGlobalTimeFilter(); - if (filterAllSatisfy(globalTimeFilter, pageReader) + if (paginationController.hasCurOffset() + && filterAllSatisfy(globalTimeFilter, pageReader) && filterAllSatisfy(pushDownFilter, pageReader) - && timeAllSelected(pageReader)) { - long rowCount = pageReader.getStatistics().getCount(); + && canUseTimeStatistics(pageReader)) { + long rowCount = currentPageTimeStatistics().getCount(); if (paginationController.hasCurOffset(rowCount)) { skipCurrentPage(); paginationController.consumeOffset(rowCount); @@ -1147,7 +1332,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 +1516,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 @@ -1532,10 +1717,11 @@ private void filterFirstTimeSeriesMetadata() { } Filter globalTimeFilter = scanOptions.getGlobalTimeFilter(); - if (filterAllSatisfy(globalTimeFilter, firstTimeSeriesMetadata) + if (paginationController.hasCurOffset() + && filterAllSatisfy(globalTimeFilter, firstTimeSeriesMetadata) && filterAllSatisfy(pushDownFilter, firstTimeSeriesMetadata) - && timeAllSelected(firstTimeSeriesMetadata)) { - long rowCount = firstTimeSeriesMetadata.getStatistics().getCount(); + && canUseTimeStatistics(firstTimeSeriesMetadata)) { + long rowCount = currentFileTimeStatistics().getCount(); if (paginationController.hasCurOffset(rowCount)) { skipCurrentFile(); paginationController.consumeOffset(rowCount); @@ -1630,8 +1816,8 @@ protected IPointReader getPointReader(TsBlock tsBlock) { return tsBlock.getTsBlockSingleColumnIterator(); } - protected boolean timeAllSelected(IMetadata metadata) { - return true; + protected boolean canUseTimeStatistics(IMetadata metadata) { + return metadata != null; } private boolean filterAllSatisfy(Filter filter, IMetadata metadata) { @@ -1667,7 +1853,6 @@ protected static class VersionPageReader implements IVersionPageReader { protected final boolean isSeq; protected final boolean isAligned; - protected final boolean isMem; protected final File tsFile; VersionPageReader( @@ -1682,11 +1867,7 @@ protected static class VersionPageReader implements IVersionPageReader { this.version = new MergeReaderPriority(fileTimestamp, version, offset, isSeq); this.data = data; this.isSeq = isSeq; - this.isAligned = - data instanceof AlignedPageReader - || data instanceof MemAlignedPageReader - || data instanceof TablePageReader; - this.isMem = data instanceof MemPageReader || data instanceof MemAlignedPageReader; + this.isAligned = data instanceof AlignedPageReader || data instanceof TablePageReader; this.tsFile = tsFile; } @@ -1751,21 +1932,11 @@ public TsBlock getAllSatisfiedPageData(boolean ascending) throws IOException { context.getQueryChunkReaders().release(data); long time = System.nanoTime() - startTime; if (isAligned) { - if (isMem) { - context.getQueryStatistics().getPageReadersDecodeAlignedMemCount().getAndAdd(1); - context.getQueryStatistics().getPageReadersDecodeAlignedMemTime().getAndAdd(time); - } else { - context.getQueryStatistics().getPageReadersDecodeAlignedDiskCount().getAndAdd(1); - context.getQueryStatistics().getPageReadersDecodeAlignedDiskTime().getAndAdd(time); - } + context.getQueryStatistics().getPageReadersDecodeAlignedDiskCount().getAndAdd(1); + context.getQueryStatistics().getPageReadersDecodeAlignedDiskTime().getAndAdd(time); } else { - if (isMem) { - context.getQueryStatistics().getPageReadersDecodeNonAlignedMemCount().getAndAdd(1); - context.getQueryStatistics().getPageReadersDecodeNonAlignedMemTime().getAndAdd(time); - } else { - context.getQueryStatistics().getPageReadersDecodeNonAlignedDiskCount().getAndAdd(1); - context.getQueryStatistics().getPageReadersDecodeNonAlignedDiskTime().getAndAdd(time); - } + context.getQueryStatistics().getPageReadersDecodeNonAlignedDiskCount().getAndAdd(1); + context.getQueryStatistics().getPageReadersDecodeNonAlignedDiskTime().getAndAdd(time); } } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractAggTableScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractAggTableScanOperator.java index 5342b5f61d55b..a96945c86dec8 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractAggTableScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractAggTableScanOperator.java @@ -220,7 +220,6 @@ protected void constructAlignedSeriesScanUtil() { scanOrder, seriesScanOptions, ((OperatorContext) operatorContext).getInstanceContext(), - true, measurementColumnTSDataTypes); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractTableScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractTableScanOperator.java index e2b38821a4cd1..3884d29c2dbc6 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractTableScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/AbstractTableScanOperator.java @@ -408,7 +408,6 @@ protected void constructAlignedSeriesScanUtil() { scanOrder, seriesScanOptions, ((OperatorContext) operatorContext).getInstanceContext(), - true, measurementColumnTSDataTypes); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileAggTableScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileAggTableScanOperator.java index 0fcd4771ed199..c84ea485956f7 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileAggTableScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileAggTableScanOperator.java @@ -66,7 +66,6 @@ protected void constructAlignedSeriesScanUtil() { scanOrder, seriesScanOptions, ((OperatorContext) operatorContext).getInstanceContext(), - true, measurementColumnTSDataTypes, this::loadTimeSeriesMetadata); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileSeriesScanUtil.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileSeriesScanUtil.java index e907218fe8a7b..9db907c6018b6 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileSeriesScanUtil.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileSeriesScanUtil.java @@ -46,10 +46,9 @@ public ExternalTsFileSeriesScanUtil( Ordering scanOrder, SeriesScanOptions scanOptions, FragmentInstanceContext context, - boolean queryAllSensors, List givenDataTypes, ExternalTsFileMetadataLoader metadataLoader) { - super(seriesPath, scanOrder, scanOptions, context, queryAllSensors, givenDataTypes); + super(seriesPath, scanOrder, scanOptions, context, givenDataTypes); this.metadataLoader = metadataLoader; } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileTableScanOperator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileTableScanOperator.java index a38fcacd046f3..785449995d65b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileTableScanOperator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/source/relational/ExternalTsFileTableScanOperator.java @@ -68,7 +68,6 @@ protected void constructAlignedSeriesScanUtil() { scanOrder, seriesScanOptions, ((OperatorContext) operatorContext).getInstanceContext(), - true, measurementColumnTSDataTypes, this::loadTimeSeriesMetadata); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java index 265c3bac1ce27..5c09d5c4c0e74 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/OperatorTreeGenerator.java @@ -482,7 +482,6 @@ public Operator visitAlignedSeriesScan( seriesPath, node.getScanOrder(), scanOptionsBuilder.build(), - node.isQueryAllSensors(), context.getTypeProvider().getTemplatedInfo() != null ? context.getTypeProvider().getTemplatedInfo().getDataTypes() : null, 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..ad5d7bd040cad 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 @@ -66,9 +66,8 @@ public class AlignedReadOnlyMemChunk extends ReadOnlyMemChunk { private final List timeColumnDeletion; private final List> valueColumnsDeletionList; - // time & values statistics + // time statistics private final List> timeStatisticsList; - private final List[]> valueStatisticsList; // AlignedTVList rowCount during query protected Map alignedTvListQueryMap; @@ -77,9 +76,6 @@ public class AlignedReadOnlyMemChunk extends ReadOnlyMemChunk { // When we select two of time series [s1, s3], the column index list should be [0, 2] private final List columnIndexList; - // Only used when StreamingQueryMemChunk is configured as false - private MemPointIterator nonStreamingTimeValuePairIterator; - /** * The constructor for Aligned type. * @@ -106,7 +102,6 @@ public AlignedReadOnlyMemChunk( this.timeColumnDeletion = timeColumnDeletion; this.valueColumnsDeletionList = valueColumnsDeletionList; this.timeStatisticsList = new ArrayList<>(); - this.valueStatisticsList = new ArrayList<>(); this.alignedTvListQueryMap = alignedTvListQueryMap; this.columnIndexList = columnIndexList; this.context.addTVListToSet(alignedTvListQueryMap.keySet()); @@ -146,84 +141,6 @@ public void sortTvLists() { } } - @Override - public void initChunkMetaFromTvLists(Filter globalTimeFilter) { - // init chunk meta - Statistics chunkTimeStatistics = - Statistics.getStatsByType(TSDataType.VECTOR); - IChunkMetadata timeChunkMetadata = - new ChunkMetadata(timeChunkName, TSDataType.VECTOR, null, null, 0, chunkTimeStatistics); - Statistics[] chunkValueStatistics = new Statistics[dataTypes.size()]; - Type[] valueTypes = new Type[dataTypes.size()]; - for (int column = 0; column < dataTypes.size(); column++) { - valueTypes[column] = Type.fromTsDataType(dataTypes.get(column)); - chunkValueStatistics[column] = Statistics.getStatsByType(dataTypes.get(column)); - } - - nonStreamingTimeValuePairIterator = createMemPointIterator(Ordering.ASC, globalTimeFilter); - nonStreamingTimeValuePairIterator.setStreamingQueryMemChunk(false); - - while (nonStreamingTimeValuePairIterator.hasNextBatch()) { - // create pageTimeStatistics and pageValueStatistics for new page - Statistics pageTimeStatistics = - Statistics.getStatsByType(TSDataType.VECTOR); - pageTimeStatistics.setEmpty(false); - timeStatisticsList.add(pageTimeStatistics); - - Statistics[] pageValueStatistics = new Statistics[dataTypes.size()]; - for (int column = 0; column < dataTypes.size(); column++) { - pageValueStatistics[column] = Statistics.getStatsByType(dataTypes.get(column)); - } - valueStatisticsList.add(pageValueStatistics); - - TsBlock tsBlock = nonStreamingTimeValuePairIterator.nextBatch(); - // time column - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - pageTimeStatistics.update(tsBlock.getTimeByIndex(i)); - chunkTimeStatistics.update(tsBlock.getTimeByIndex(i)); - } - // value columns - for (int column = 0; column < tsBlock.getValueColumnCount(); column++) { - Statistics pageValueStats = pageValueStatistics[column]; - Type valueType = valueTypes[column]; - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - if (tsBlock.getColumn(column).isNull(i)) { - continue; - } - valueType.update(pageValueStats, tsBlock, column, i); - valueType.update(chunkValueStatistics[column], tsBlock, column, i); - } - pageValueStatistics[column] = pageValueStats.isEmpty() ? null : pageValueStats; - } - } - - // aligned chunk meta - List valueChunkMetadataList = new ArrayList<>(); - for (int column = 0; column < dataTypes.size(); column++) { - if (!chunkValueStatistics[column].isEmpty()) { - IChunkMetadata valueChunkMetadata = - new ChunkMetadata( - valueChunkNames.get(column), - dataTypes.get(column), - null, - null, - 0, - chunkValueStatistics[column]); - valueChunkMetadataList.add(valueChunkMetadata); - } else { - valueChunkMetadataList.add(null); - } - } - - IChunkMetadata alignedChunkMetadata = - context.isIgnoreAllNullRows() - ? new AlignedChunkMetadata(timeChunkMetadata, valueChunkMetadataList) - : new TableDeviceChunkMetadata(timeChunkMetadata, valueChunkMetadataList); - alignedChunkMetadata.setChunkLoader(new MemAlignedChunkLoader(context, this)); - alignedChunkMetadata.setVersion(Long.MAX_VALUE); - cachedMetaData = alignedChunkMetadata; - } - // To avoid loading too much data from disk when the time range is too large during query, we // segment the data according to the time range and construct false statistics. @Override @@ -248,12 +165,6 @@ public void initChunkMetaFromTVListsWithFakeStatistics() { long pageStartTime = pageTimeRange[0]; long pageEndTime = pageTimeRange[1]; - Statistics[] pageValueStatistics = new Statistics[dataTypes.size()]; - for (int column = 0; column < dataTypes.size(); column++) { - pageValueStatistics[column] = - generateFakeStatistics(dataTypes.get(column), pageStartTime, pageEndTime); - } - valueStatisticsList.add(pageValueStatistics); Statistics pageTimeStatistics = generateFakeStatistics(TSDataType.VECTOR, pageStartTime, pageEndTime); timeStatisticsList.add(pageTimeStatistics); @@ -291,7 +202,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); @@ -400,15 +311,6 @@ public List> getTimeStatisticsList() { return timeStatisticsList; } - public List[]> getValuesStatisticsList() { - return valueStatisticsList; - } - - @Override - public MemPointIterator getMemPointIterator() { - return nonStreamingTimeValuePairIterator; - } - @Override public MemPointIterator createMemPointIterator(Ordering scanOrder, Filter globalTimeFilter) { List tvLists = new ArrayList<>(alignedTvListQueryMap.size()); 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..4186cb2ccead8 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 @@ -81,8 +81,6 @@ public class ReadOnlyMemChunk { // TVList and its rowCount during query private Map tvListQueryMap; - private MemPointIterator timeValuePairIterator; - protected final int MAX_NUMBER_OF_POINTS_IN_PAGE = TSFileDescriptor.getInstance().getConfig().getMaxNumberOfPointsInPage(); @@ -156,34 +154,6 @@ public void sortTvLists() { } } - public void initChunkMetaFromTvLists(Filter globalTimeFilter) { - // create chunk statistics - Statistics chunkStatistics = Statistics.getStatsByType(dataType); - Type type = Type.fromTsDataType(dataType); - timeValuePairIterator = createMemPointIterator(Ordering.ASC, globalTimeFilter); - timeValuePairIterator.setStreamingQueryMemChunk(false); - while (timeValuePairIterator.hasNextBatch()) { - // statistics for current batch - Statistics pageStatistics = Statistics.getStatsByType(dataType); - pageStatisticsList.add(pageStatistics); - - TsBlock tsBlock = timeValuePairIterator.nextBatch(); - if (!tsBlock.isEmpty()) { - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - type.update(chunkStatistics, tsBlock, 0, i); - type.update(pageStatistics, tsBlock, 0, i); - } - } - } - - // chunk meta - IChunkMetadata metaData = - new ChunkMetadata(measurementUid, dataType, null, null, 0, chunkStatistics); - metaData.setChunkLoader(new MemChunkLoader(context, this)); - metaData.setVersion(Long.MAX_VALUE); - cachedMetaData = metaData; - } - // To avoid loading too much data from disk when the time range is too large during query, we // segment the data according to the time range and construct false statistics. public void initChunkMetaFromTVListsWithFakeStatistics() { @@ -211,7 +181,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); @@ -329,10 +299,6 @@ public TsBlock getTsBlock() { return null; } - public MemPointIterator getMemPointIterator() { - return timeValuePairIterator; - } - public MemPointIterator createMemPointIterator(Ordering scanOrder, Filter globalTimeFilter) { List tvLists = new ArrayList<>(tvListQueryMap.size()); List tvListRowCounts = new ArrayList<>(tvListQueryMap.size()); 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..155596767f25e 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 @@ -22,34 +22,10 @@ import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext; import org.apache.iotdb.db.storageengine.dataregion.memtable.AlignedReadOnlyMemChunk; -import org.apache.tsfile.file.metadata.IChunkMetadata; -import org.apache.tsfile.read.filter.basic.Filter; -import org.apache.tsfile.read.reader.IChunkReader; - -import static org.apache.iotdb.db.queryengine.metric.SeriesScanCostMetricSet.INIT_CHUNK_READER_ALIGNED_MEM; - /** To read one aligned chunk from memory, and only used in iotdb server module. */ public class MemAlignedChunkLoader extends MemChunkLoader { 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(); - try { - return new MemAlignedChunkReader((AlignedReadOnlyMemChunk) chunk, globalTimeFilter); - } finally { - long duration = System.nanoTime() - startTime; - context.getQueryStatistics().getConstructAlignedChunkReadersMemCount().getAndAdd(1); - context.getQueryStatistics().getConstructAlignedChunkReadersMemTime().getAndAdd(duration); - SERIES_SCAN_COST_METRIC_SET.recordSeriesScanCost(INIT_CHUNK_READER_ALIGNED_MEM, duration); - } - } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkReader.java deleted file mode 100644 index 61e14f535fcb6..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkReader.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.i18n.StorageEngineMessages; -import org.apache.iotdb.db.storageengine.dataregion.memtable.AlignedReadOnlyMemChunk; -import org.apache.iotdb.db.utils.datastructure.MemPointIterator; - -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.filter.basic.Filter; -import org.apache.tsfile.read.reader.IChunkReader; -import org.apache.tsfile.read.reader.IPageReader; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** To read aligned chunk data in memory. */ -public class MemAlignedChunkReader implements IChunkReader { - private final MemPointIterator timeValuePairIterator; - private final Filter globalTimeFilter; - private final List pageReaderList; - - public MemAlignedChunkReader(AlignedReadOnlyMemChunk readableChunk, Filter globalTimeFilter) { - timeValuePairIterator = readableChunk.getMemPointIterator(); - this.globalTimeFilter = globalTimeFilter; - this.pageReaderList = new ArrayList<>(); - initAllPageReaders( - readableChunk.getDataTypes(), - readableChunk.getTimeStatisticsList(), - readableChunk.getValuesStatisticsList()); - } - - private void initAllPageReaders( - List tsDataTypes, - List> timeStatistics, - List[]> valuesStatistics) { - Supplier tsBlockSupplier = new MemAlignedChunkReader.TsBlockSupplier(); - for (int pageIndex = 0; pageIndex < timeStatistics.size(); pageIndex++) { - MemAlignedPageReader pageReader = - new MemAlignedPageReader( - tsBlockSupplier, - pageIndex, - tsDataTypes, - timeStatistics.get(pageIndex), - valuesStatistics.get(pageIndex), - globalTimeFilter); - this.pageReaderList.add(pageReader); - } - } - - @Override - public boolean hasNextSatisfiedPage() throws IOException { - throw new IOException(StorageEngineMessages.MEM_CHUNK_READER_NOT_SUPPORT_METHOD); - } - - @Override - public BatchData nextPageData() throws IOException { - throw new IOException(StorageEngineMessages.MEM_CHUNK_READER_NOT_SUPPORT_METHOD); - } - - @Override - public void close() { - // Do nothing because mem chunk reader will not open files - } - - @Override - public void markDataTypeModifiedAndCannotUseStatistics() { - for (IPageReader iPageReader : pageReaderList) { - iPageReader.setModified(true); - } - } - - @Override - public List loadPageReaderList() { - return this.pageReaderList; - } - - class TsBlockSupplier implements Supplier { - private int tsBlockIndex; - - public TsBlockSupplier() {} - - public void setTsBlockIndex(int tsBlockIndex) { - this.tsBlockIndex = tsBlockIndex; - } - - @Override - public TsBlock get() { - return timeValuePairIterator.getBatch(tsBlockIndex); - } - } -} 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 deleted file mode 100644 index a673bb6efb140..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedPageReader.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.i18n.StorageEngineMessages; -import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.metadata.AlignedPageMetadata; -import org.apache.iotdb.db.utils.CommonUtils; - -import org.apache.tsfile.block.column.Column; -import org.apache.tsfile.block.column.ColumnBuilder; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.BatchDataFactory; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.common.block.TsBlockBuilder; -import org.apache.tsfile.read.common.type.Type; -import org.apache.tsfile.read.filter.basic.Filter; -import org.apache.tsfile.read.filter.factory.FilterFactory; -import org.apache.tsfile.read.reader.IPageReader; -import org.apache.tsfile.read.reader.series.PaginationController; -import org.apache.tsfile.utils.TsPrimitiveType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.function.LongConsumer; -import java.util.function.Supplier; - -import static org.apache.tsfile.read.reader.series.PaginationController.UNLIMITED_PAGINATION_CONTROLLER; - -public class MemAlignedPageReader implements IPageReader { - - private TsBlock tsBlock; - private final AlignedPageMetadata pageMetadata; - - private final int pageIndex; - private final Supplier tsBlockSupplier; - private final List tsDataTypes; - - private Filter recordFilter; - private PaginationController paginationController = UNLIMITED_PAGINATION_CONTROLLER; - - // data type is modified in query and statistics cannot be used - private boolean modified; - - private TsBlockBuilder builder; - - public MemAlignedPageReader( - Supplier tsBlockSupplier, - int pageIndex, - List tsDataTypes, - Statistics timeStatistics, - Statistics[] valueStatistics, - Filter recordFilter) { - this.tsBlockSupplier = tsBlockSupplier; - this.pageIndex = pageIndex; - this.recordFilter = recordFilter; - this.tsDataTypes = tsDataTypes; - this.pageMetadata = new AlignedPageMetadata(timeStatistics, valueStatistics); - } - - @Override - public BatchData getAllSatisfiedPageData() throws IOException { - return IPageReader.super.getAllSatisfiedPageData(); - } - - @Override - public BatchData getAllSatisfiedPageData(boolean ascending) throws IOException { - getTsBlock(); - - BatchData batchData = BatchDataFactory.createBatchData(TSDataType.VECTOR, ascending, false); - - boolean[] satisfyInfo = buildSatisfyInfoArray(null); - - for (int rowIndex = 0; rowIndex < tsBlock.getPositionCount(); rowIndex++) { - if (satisfyInfo[rowIndex]) { - long time = tsBlock.getTimeByIndex(rowIndex); - TsPrimitiveType[] values = new TsPrimitiveType[tsBlock.getValueColumnCount()]; - for (int column = 0; column < tsBlock.getValueColumnCount(); column++) { - if (tsBlock.getColumn(column) != null && !tsBlock.getColumn(column).isNull(rowIndex)) { - values[column] = tsBlock.getColumn(column).getTsPrimitiveType(rowIndex); - } - } - batchData.putVector(time, values); - } - } - return batchData.flip(); - } - - @Override - public TsBlock getAllSatisfiedData() { - return getAllSatisfiedData(null); - } - - @Override - public TsBlock getAllSatisfiedData(LongConsumer filterRowsRecorder) { - getTsBlock(); - - builder.reset(); - - boolean[] satisfyInfo = buildSatisfyInfoArray(filterRowsRecorder); - - // build time column - int readEndIndex = buildTimeColumn(satisfyInfo); - - // build value column - buildValueColumns(satisfyInfo, readEndIndex); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - StorageEngineMessages.MEM_ALIGNED_PAGE_READER_TSBLOCK, CommonUtils.toString(tsBlock)); - } - return builder.build(); - } - - private static final Logger LOGGER = LoggerFactory.getLogger(MemAlignedPageReader.class); - - private boolean[] buildSatisfyInfoArray(LongConsumer filterRowsRecorder) { - if (recordFilter == null || recordFilter.allSatisfy(this)) { - boolean[] satisfyInfo = new boolean[tsBlock.getPositionCount()]; - Arrays.fill(satisfyInfo, true); - return satisfyInfo; - } - if (filterRowsRecorder == null) { - return recordFilter.satisfyTsBlock(tsBlock); - } else { - boolean[] selection = new boolean[tsBlock.getPositionCount()]; - Arrays.fill(selection, true); - return recordFilter.satisfyTsBlock(selection, tsBlock, filterRowsRecorder); - } - } - - private int buildTimeColumn(boolean[] satisfyInfo) { - int readEndIndex = tsBlock.getPositionCount(); - for (int row = 0; row < readEndIndex; row++) { - - if (needSkipCurrentRow(satisfyInfo, row)) { - continue; - } - - if (paginationController.hasCurLimit()) { - builder.getTimeColumnBuilder().writeLong(tsBlock.getTimeByIndex(row)); - builder.declarePosition(); - paginationController.consumeLimit(); - } else { - readEndIndex = row; - } - } - return readEndIndex; - } - - private boolean needSkipCurrentRow(boolean[] satisfyInfo, int rowIndex) { - if (!satisfyInfo[rowIndex]) { - return true; - } - if (paginationController.hasCurOffset()) { - paginationController.consumeOffset(); - satisfyInfo[rowIndex] = false; - return true; - } - return false; - } - - private void buildValueColumns(boolean[] satisfyInfo, int readEndIndex) { - for (int column = 0; column < tsBlock.getValueColumnCount(); column++) { - Column valueColumn = tsBlock.getColumn(column); - ColumnBuilder valueBuilder = builder.getColumnBuilder(column); - for (int row = 0; row < readEndIndex; row++) { - if (satisfyInfo[row]) { - if (!valueColumn.isNull(row)) { - valueBuilder.write(valueColumn, row); - } else { - valueBuilder.appendNull(); - } - } - } - } - } - - @Override - public Statistics getStatistics() { - return pageMetadata.getStatistics(); - } - - @Override - public Statistics getTimeStatistics() { - return pageMetadata.getTimeStatistics(); - } - - @Override - public Optional> getMeasurementStatistics( - int measurementIndex) { - return pageMetadata.getMeasurementStatistics(measurementIndex); - } - - @Override - public boolean hasNullValue(int measurementIndex) { - return pageMetadata.hasNullValue(measurementIndex); - } - - @Override - public void addRecordFilter(Filter filter) { - this.recordFilter = FilterFactory.and(recordFilter, filter); - } - - @Override - public void setLimitOffset(PaginationController paginationController) { - this.paginationController = paginationController; - } - - @Override - public boolean isModified() { - return modified; - } - - @Override - public void setModified(boolean modified) { - this.modified = modified; - } - - @Override - public void initTsBlockBuilder(List dataTypes) { - builder = new TsBlockBuilder(dataTypes); - } - - private void getTsBlock() { - if (tsBlock == null) { - initializeTsBlockIndex(); - tsBlock = tsBlockSupplier.get(); - if (pageMetadata.getStatistics() == null) { - initPageStatistics(); - } - } - } - - private void initializeTsBlockIndex() { - if (tsBlockSupplier instanceof MemAlignedChunkReader.TsBlockSupplier) { - ((MemAlignedChunkReader.TsBlockSupplier) tsBlockSupplier).setTsBlockIndex(pageIndex); - } - } - - private void initPageStatistics() { - Statistics pageTimeStatistics = - Statistics.getStatsByType(TSDataType.VECTOR); - Statistics[] pageValueStatistics = new Statistics[tsDataTypes.size()]; - for (int column = 0; column < tsDataTypes.size(); column++) { - Statistics valueStatistics = - Statistics.getStatsByType(tsDataTypes.get(column)); - pageValueStatistics[column] = valueStatistics; - } - updatePageStatisticsFromTsBlock(pageTimeStatistics, pageValueStatistics); - pageMetadata.setStatistics(pageTimeStatistics, pageValueStatistics); - } - - private void updatePageStatisticsFromTsBlock( - Statistics timeStatistics, - Statistics[] valueStatistics) { - if (!tsBlock.isEmpty()) { - // update time statistics - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - timeStatistics.update(tsBlock.getTimeByIndex(i)); - } - // timeStatistics.setEmpty(false); - - for (int column = 0; column < tsDataTypes.size(); column++) { - Type type = Type.fromTsDataType(tsDataTypes.get(column)); - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - type.update(valueStatistics[column], tsBlock, column, i); - } - } - } - } -} 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..4421a29ba2d0f 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 @@ -20,7 +20,6 @@ package org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk; import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext; -import org.apache.iotdb.db.queryengine.metric.SeriesScanCostMetricSet; import org.apache.iotdb.db.storageengine.dataregion.memtable.ReadOnlyMemChunk; import org.apache.tsfile.file.metadata.ChunkMetadata; @@ -30,26 +29,14 @@ import org.apache.tsfile.read.filter.basic.Filter; import org.apache.tsfile.read.reader.IChunkReader; -import static org.apache.iotdb.db.queryengine.metric.SeriesScanCostMetricSet.INIT_CHUNK_READER_NONALIGNED_MEM; - /** To read one chunk from memory, and only used in iotdb server module. */ 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 @@ -64,22 +51,10 @@ public void close() { @Override public IChunkReader getChunkReader(IChunkMetadata chunkMetaData, Filter globalTimeFilter) { - long startTime = System.nanoTime(); - try { - return new MemChunkReader(chunk, globalTimeFilter); - } finally { - long duration = System.nanoTime() - startTime; - context.getQueryStatistics().getConstructNonAlignedChunkReadersMemCount().getAndAdd(1); - context.getQueryStatistics().getConstructNonAlignedChunkReadersMemTime().getAndAdd(duration); - SERIES_SCAN_COST_METRIC_SET.recordSeriesScanCost(INIT_CHUNK_READER_NONALIGNED_MEM, duration); - } + throw new UnsupportedOperationException(); } 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/MemChunkReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkReader.java deleted file mode 100644 index 8cee8b970c542..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkReader.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.storageengine.dataregion.memtable.ReadOnlyMemChunk; -import org.apache.iotdb.db.utils.datastructure.MemPointIterator; - -import org.apache.tsfile.file.metadata.IChunkMetadata; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.TimeValuePair; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.block.TsBlock; -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.IPointReader; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** To read chunk data in memory. */ -public class MemChunkReader implements IChunkReader, IPointReader { - - private final MemPointIterator timeValuePairIterator; - private final Filter globalTimeFilter; - private final List pageReaderList; - - private boolean hasCachedTimeValuePair; - private TimeValuePair cachedTimeValuePair; - - public MemChunkReader(ReadOnlyMemChunk readableChunk, Filter globalTimeFilter) { - this.timeValuePairIterator = readableChunk.getMemPointIterator(); - this.globalTimeFilter = globalTimeFilter; - this.pageReaderList = new ArrayList<>(); - initAllPageReaders(readableChunk.getChunkMetaData(), readableChunk.getPageStatisticsList()); - } - - private void initAllPageReaders( - IChunkMetadata metadata, List> pageStats) { - Supplier tsBlockSupplier = new TsBlockSupplier(); - for (int pageIndex = 0; pageIndex < pageStats.size(); pageIndex++) { - MemPageReader pageReader = - new MemPageReader( - tsBlockSupplier, - pageIndex, - metadata.getDataType(), - metadata.getMeasurementUid(), - pageStats.get(pageIndex), - globalTimeFilter); - this.pageReaderList.add(pageReader); - } - } - - @Override - public boolean hasNextTimeValuePair() throws IOException { - if (hasCachedTimeValuePair) { - return true; - } - while (timeValuePairIterator.hasNextTimeValuePair()) { - TimeValuePair timeValuePair = timeValuePairIterator.nextTimeValuePair(); - if (globalTimeFilter == null - || globalTimeFilter.satisfy( - timeValuePair.getTimestamp(), timeValuePair.getValue().getValue())) { - hasCachedTimeValuePair = true; - cachedTimeValuePair = timeValuePair; - break; - } - } - return hasCachedTimeValuePair; - } - - @Override - public TimeValuePair nextTimeValuePair() throws IOException { - if (hasCachedTimeValuePair) { - hasCachedTimeValuePair = false; - return cachedTimeValuePair; - } else { - return timeValuePairIterator.nextTimeValuePair(); - } - } - - @Override - public TimeValuePair currentTimeValuePair() throws IOException { - if (!hasCachedTimeValuePair) { - cachedTimeValuePair = timeValuePairIterator.nextTimeValuePair(); - hasCachedTimeValuePair = true; - } - return cachedTimeValuePair; - } - - @Override - public boolean hasNextSatisfiedPage() throws IOException { - return hasNextTimeValuePair(); - } - - @Override - public BatchData nextPageData() throws IOException { - return pageReaderList.remove(0).getAllSatisfiedPageData(); - } - - @Override - public long getUsedMemorySize() { - // not used - return timeValuePairIterator.getUsedMemorySize(); - } - - @Override - public void close() { - // Do nothing because mem chunk reader will not open files - } - - @Override - public void markDataTypeModifiedAndCannotUseStatistics() { - for (IPageReader pageReader : this.pageReaderList) { - pageReader.setModified(true); - } - } - - @Override - public List loadPageReaderList() { - return this.pageReaderList; - } - - /** - * TsBlockSupplier enables to read pages in MemTable lazily. All MemPageReaders share one - * TsBlockSupplier object. - */ - class TsBlockSupplier implements Supplier { - private int tsBlockIndex; - - public TsBlockSupplier() {} - - public void setTsBlockIndex(int tsBlockIndex) { - this.tsBlockIndex = tsBlockIndex; - } - - @Override - public TsBlock get() { - return timeValuePairIterator.getBatch(tsBlockIndex); - } - } -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReader.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReader.java deleted file mode 100644 index dca6876fb623f..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReader.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.storageengine.dataregion.read.reader.chunk.metadata.PageMetadata; -import org.apache.iotdb.db.utils.TypeServices; - -import org.apache.tsfile.block.column.Column; -import org.apache.tsfile.block.column.ColumnBuilder; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.BatchDataFactory; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.common.block.TsBlockBuilder; -import org.apache.tsfile.read.common.type.Type; -import org.apache.tsfile.read.filter.basic.Filter; -import org.apache.tsfile.read.filter.factory.FilterFactory; -import org.apache.tsfile.read.reader.IPageReader; -import org.apache.tsfile.read.reader.series.PaginationController; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.function.LongConsumer; -import java.util.function.Supplier; - -import static org.apache.tsfile.read.reader.series.PaginationController.UNLIMITED_PAGINATION_CONTROLLER; - -public class MemPageReader implements IPageReader { - - private TsBlock tsBlock; - private Filter recordFilter; - - private final int pageIndex; - private final Supplier tsBlockSupplier; - private final TSDataType tsDataType; - private final PageMetadata pageMetadata; - - private PaginationController paginationController = UNLIMITED_PAGINATION_CONTROLLER; - - // data type is modified in query and statistics cannot be used - private boolean modified; - - public MemPageReader( - Supplier tsBlockSupplier, - int pageIndex, - TSDataType tsDataType, - String measurementUid, - Statistics statistics, - Filter recordFilter) { - this.tsBlockSupplier = tsBlockSupplier; - this.pageIndex = pageIndex; - this.recordFilter = recordFilter; - this.tsDataType = tsDataType; - this.pageMetadata = new PageMetadata(measurementUid, tsDataType, statistics); - } - - @Override - public BatchData getAllSatisfiedPageData(boolean ascending) throws IOException { - getTsBlock(); - - BatchData batchData = BatchDataFactory.createBatchData(tsDataType, ascending, false); - boolean[] satisfyInfo = buildSatisfyInfoArray(null); - TypeServices.BatchDataColumnWriter valueWriter = - TypeServices.StorageEngine.BATCH_DATA_COLUMN_WRITER_SERVICE.call( - Type.fromTsDataType(tsDataType)); - Column valueColumn = tsBlock.getColumn(0); - - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - if (satisfyInfo[i]) { - valueWriter.write(batchData, tsBlock.getTimeByIndex(i), valueColumn, i); - } - } - return batchData.flip(); - } - - @Override - public TsBlock getAllSatisfiedData() { - return getAllSatisfiedData(null); - } - - @Override - public TsBlock getAllSatisfiedData(LongConsumer filterRowsRecorder) { - getTsBlock(); - - TsBlockBuilder builder = new TsBlockBuilder(Collections.singletonList(tsDataType)); - - boolean[] satisfyInfo = buildSatisfyInfoArray(filterRowsRecorder); - - // build time column - int readEndIndex = buildTimeColumn(builder, satisfyInfo); - - // build value column - buildValueColumn(builder, satisfyInfo, readEndIndex); - - return builder.build(); - } - - private boolean[] buildSatisfyInfoArray(LongConsumer filterRowsRecorder) { - if (recordFilter == null || recordFilter.allSatisfy(this)) { - boolean[] satisfyInfo = new boolean[tsBlock.getPositionCount()]; - Arrays.fill(satisfyInfo, true); - return satisfyInfo; - } - - if (filterRowsRecorder == null) { - return recordFilter.satisfyTsBlock(tsBlock); - } else { - boolean[] selection = new boolean[tsBlock.getPositionCount()]; - Arrays.fill(selection, true); - return recordFilter.satisfyTsBlock(selection, tsBlock, filterRowsRecorder); - } - } - - private int buildTimeColumn(TsBlockBuilder builder, boolean[] satisfyInfo) { - int readEndIndex = tsBlock.getPositionCount(); - for (int rowIndex = 0; rowIndex < readEndIndex; rowIndex++) { - - if (needSkipCurrentRow(satisfyInfo, rowIndex)) { - continue; - } - - if (paginationController.hasCurLimit()) { - builder.getTimeColumnBuilder().writeLong(tsBlock.getTimeByIndex(rowIndex)); - builder.declarePosition(); - paginationController.consumeLimit(); - } else { - readEndIndex = rowIndex; - } - } - return readEndIndex; - } - - private boolean needSkipCurrentRow(boolean[] satisfyInfo, int rowIndex) { - if (!satisfyInfo[rowIndex]) { - return true; - } - if (paginationController.hasCurOffset()) { - paginationController.consumeOffset(); - satisfyInfo[rowIndex] = false; - return true; - } - return false; - } - - private void buildValueColumn(TsBlockBuilder builder, boolean[] satisfyInfo, int readEndIndex) { - for (int column = 0; column < tsBlock.getValueColumnCount(); column++) { - Column valueColumn = tsBlock.getColumn(column); - ColumnBuilder valueBuilder = builder.getColumnBuilder(column); - for (int row = 0; row < readEndIndex; row++) { - if (satisfyInfo[row]) { - if (!valueColumn.isNull(row)) { - valueBuilder.write(valueColumn, row); - } else { - valueBuilder.appendNull(); - } - } - } - } - } - - @Override - public Statistics getStatistics() { - return pageMetadata.getStatistics(); - } - - @Override - public Statistics getTimeStatistics() { - return pageMetadata.getTimeStatistics(); - } - - @Override - public Optional> getMeasurementStatistics( - int measurementIndex) { - return pageMetadata.getMeasurementStatistics(measurementIndex); - } - - @Override - public boolean hasNullValue(int measurementIndex) { - return pageMetadata.hasNullValue(measurementIndex); - } - - @Override - public void addRecordFilter(Filter filter) { - this.recordFilter = FilterFactory.and(recordFilter, filter); - } - - @Override - public void setLimitOffset(PaginationController paginationController) { - this.paginationController = paginationController; - } - - @Override - public boolean isModified() { - return modified; - } - - @Override - public void setModified(boolean modified) { - this.modified = modified; - } - - @Override - public void initTsBlockBuilder(List dataTypes) { - // non-aligned page reader don't need to init TsBlockBuilder at the very beginning - } - - private void getTsBlock() { - if (tsBlock == null) { - initializeTsBlockIndex(); - tsBlock = tsBlockSupplier.get(); - if (pageMetadata.getStatistics() == null) { - initPageStatistics(); - } - } - } - - private void initializeTsBlockIndex() { - if (tsBlockSupplier instanceof MemChunkReader.TsBlockSupplier) { - ((MemChunkReader.TsBlockSupplier) tsBlockSupplier).setTsBlockIndex(pageIndex); - } - } - - // memory page statistics should be initialized when constructing ReadOnlyMemChunk object. - // We do the initialization if it is not set, especially in test cases. - private void initPageStatistics() { - Statistics statistics = Statistics.getStatsByType(tsDataType); - updatePageStatisticsFromTsBlock(statistics); - statistics.setEmpty(tsBlock.isEmpty()); - pageMetadata.setStatistics(statistics); - } - - private void updatePageStatisticsFromTsBlock(Statistics statistics) { - if (!tsBlock.isEmpty()) { - Type type = Type.fromTsDataType(tsDataType); - for (int i = 0; i < tsBlock.getPositionCount(); i++) { - type.update(statistics, tsBlock, 0, i); - } - } - } -} 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 deleted file mode 100644 index c06ec112be038..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/AlignedPageMetadata.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk.metadata; - -import org.apache.tsfile.file.metadata.IMetadata; -import org.apache.tsfile.file.metadata.statistics.Statistics; - -import java.io.Serializable; -import java.util.Optional; - -public class AlignedPageMetadata implements IMetadata { - private Statistics timeStatistics; - private Statistics[] valueStatistics; - - public AlignedPageMetadata( - Statistics timeStatistics, - Statistics[] valuesStatistics) { - this.timeStatistics = timeStatistics; - this.valueStatistics = valuesStatistics; - } - - @Override - public Statistics getStatistics() { - return valueStatistics.length == 1 && valueStatistics[0] != null - ? valueStatistics[0] - : timeStatistics; - } - - @Override - public Statistics getTimeStatistics() { - return timeStatistics; - } - - @Override - public Optional> getMeasurementStatistics( - int measurementIndex) { - return Optional.ofNullable( - measurementIndex >= valueStatistics.length ? null : valueStatistics[measurementIndex]); - } - - @Override - public boolean hasNullValue(int measurementIndex) { - if (measurementIndex >= valueStatistics.length) { - return false; - } - long rowCount = getTimeStatistics().getCount(); - Statistics stats = valueStatistics[measurementIndex]; - return stats != null && stats.hasNullValue(rowCount); - } - - public void setStatistics( - Statistics timeStatistics, - Statistics[] valueStatistics) { - this.timeStatistics = timeStatistics; - this.valueStatistics = valueStatistics; - } -} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/PageMetadata.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/PageMetadata.java deleted file mode 100644 index d37e22e44ee8a..0000000000000 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/metadata/PageMetadata.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk.metadata; - -import org.apache.iotdb.db.i18n.StorageEngineMessages; - -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.IMetadata; -import org.apache.tsfile.file.metadata.statistics.Statistics; - -import java.io.Serializable; -import java.util.Optional; - -import static org.apache.tsfile.utils.Preconditions.checkArgument; - -public class PageMetadata implements IMetadata { - private final String measurementUid; - private final TSDataType tsDataType; - private Statistics statistics; - private boolean modified; - - public PageMetadata( - String measurementUid, TSDataType tsDataType, Statistics statistics) { - this.measurementUid = measurementUid; - this.tsDataType = tsDataType; - this.statistics = statistics; - } - - @Override - public String toString() { - return String.format( - "measurementId: %s, datatype: %s, " + "Statistics: %s", - measurementUid, tsDataType, statistics); - } - - public boolean isModified() { - return modified; - } - - public void setModified(boolean modified) { - this.modified = modified; - } - - public String getMeasurementUid() { - return measurementUid; - } - - public void setStatistics(Statistics statistics) { - this.statistics = statistics; - } - - @Override - public Statistics getStatistics() { - return statistics; - } - - @Override - public Statistics getTimeStatistics() { - return getStatistics(); - } - - @Override - public Optional> getMeasurementStatistics( - int measurementIndex) { - checkArgument( - measurementIndex == 0, - StorageEngineMessages - .EXCEPTION_NON_MINUS_ALIGNED_CHUNK_ONLY_HAS_ONE_MEASUREMENT_COMMA_BUT_MEASUREMENTINDEX_IS_E1A87F80 - + measurementIndex); - return Optional.ofNullable(statistics); - } - - @Override - public boolean hasNullValue(int measurementIndex) { - return false; - } -} 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..f05ac526f3c4c 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)) { @@ -2589,7 +2631,6 @@ public TsBlock nextBatch() { } else { tsBlock = paginationController.applyTsBlock(tsBlock); } - addTsBlock(tsBlock); probeNext = false; return tsBlock; diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MemPointIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MemPointIterator.java index 088187b3b4230..2c9429583db95 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MemPointIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MemPointIterator.java @@ -30,8 +30,6 @@ import org.apache.tsfile.write.chunk.IChunkWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; public abstract class MemPointIterator implements IPointReader { @@ -42,8 +40,6 @@ public abstract class MemPointIterator implements IPointReader { protected PaginationController paginationController = PaginationController.UNLIMITED_PAGINATION_CONTROLLER; protected TimeRange timeRange; - protected List tsBlocks; - protected boolean streamingQueryMemChunk = true; protected QueryContext queryContext = null; public MemPointIterator(Ordering scanOrder, QueryContext queryContext) { @@ -51,8 +47,6 @@ public MemPointIterator(Ordering scanOrder, QueryContext queryContext) { this.queryContext = queryContext; } - public abstract TsBlock getBatch(int tsBlockIndex); - // When returned by nextBatch, the pagination controller and push down filter are applied. This // can only be used when there is no overlap with other pages. public abstract boolean hasNextBatch(); @@ -87,18 +81,6 @@ protected boolean isCurrentTimeExceedTimeRange(long time) { && (scanOrder.isAscending() ? (time > timeRange.getMax()) : (time < timeRange.getMin())); } - public void setStreamingQueryMemChunk(boolean streamingQueryMemChunk) { - this.streamingQueryMemChunk = streamingQueryMemChunk; - } - - protected void addTsBlock(TsBlock tsBlock) { - if (streamingQueryMemChunk) { - return; - } - tsBlocks = tsBlocks == null ? new ArrayList<>() : tsBlocks; - tsBlocks.add(tsBlock); - } - public void setQueryContext(QueryContext queryContext) { this.queryContext = queryContext; } @@ -109,8 +91,6 @@ public QueryContext getQueryContext() { @Override public void close() throws IOException { - if (tsBlocks != null) { - tsBlocks.clear(); - } + // nothing to close } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MergeSortMultiAlignedTVListIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MergeSortMultiAlignedTVListIterator.java index f4f0d06c1bd05..7cf5d66ba7305 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MergeSortMultiAlignedTVListIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MergeSortMultiAlignedTVListIterator.java @@ -34,7 +34,6 @@ import org.apache.tsfile.write.chunk.IChunkWriter; import org.apache.tsfile.write.chunk.ValueChunkWriter; -import java.util.Iterator; import java.util.List; import java.util.PriorityQueue; import java.util.Set; @@ -195,18 +194,15 @@ && isPointDeleted( } } - if (ignoreAllNullRows && bitMap.isAllMarked()) { - Iterator it = probeIterators.iterator(); - while (it.hasNext()) { - int idx = it.next(); + if (ignoreAllNullRows && !tsDataTypeList.isEmpty() && bitMap.isAllMarked()) { + for (int idx : probeIterators) { AlignedTVList.AlignedTVListIterator iterator = alignedTvListIterators.get(idx); iterator.next(); if (iterator.hasNextTimeValuePair()) { heap.add(new Pair<>(iterator.currentTime(), idx)); - } else { - it.remove(); } } + probeIterators.clear(); hasNext = false; } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiAlignedTVListIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiAlignedTVListIterator.java index f94a0fb0f6a1b..5c61ffa7e5281 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiAlignedTVListIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiAlignedTVListIterator.java @@ -286,18 +286,9 @@ public TsBlock nextBatch() { } else { tsBlock = paginationController.applyTsBlock(tsBlock); } - addTsBlock(tsBlock); return tsBlock; } - @Override - public TsBlock getBatch(int tsBlockIndex) { - if (tsBlockIndex < 0 || tsBlockIndex >= tsBlocks.size()) { - return null; - } - return tsBlocks.get(tsBlockIndex); - } - @Override public long getUsedMemorySize() { // not used diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiTVListIterator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiTVListIterator.java index 576a7979f8f3d..14e623811bba2 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiTVListIterator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/MultiTVListIterator.java @@ -177,17 +177,7 @@ public TsBlock nextBatch() { // There is no need to process pushDownFilter here because it has been applied when // constructing the tsBlock - TsBlock tsBlock = paginationController.applyTsBlock(builder.build()); - addTsBlock(tsBlock); - return tsBlock; - } - - @Override - public TsBlock getBatch(int tsBlockIndex) { - if (tsBlockIndex < 0 || tsBlockIndex >= tsBlocks.size()) { - return null; - } - return tsBlocks.get(tsBlockIndex); + return paginationController.applyTsBlock(builder.build()); } @Override 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/main/java/org/apache/iotdb/db/utils/datastructure/TVList.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/TVList.java index 0a9bfe4f16f15..82159dd87d3c1 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/TVList.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/datastructure/TVList.java @@ -1024,14 +1024,6 @@ public TimeValuePair currentTimeValuePair() { return getTimeValuePair(getScanOrderIndex(index)); } - @Override - public TsBlock getBatch(int tsBlockIndex) { - if (tsBlockIndex < 0 || tsBlockIndex >= tsBlocks.size()) { - return null; - } - return tsBlocks.get(tsBlockIndex); - } - @Override public boolean hasNextBatch() { if (!paginationController.hasCurLimit()) { @@ -1099,7 +1091,6 @@ public TsBlock nextBatch() { // There is no need to process pushDownFilter and paginationController here because it has // been applied when constructing the tsBlock TsBlock tsBlock = builder.build(); - addTsBlock(tsBlock); probeNext = false; return tsBlock; } @@ -1206,6 +1197,8 @@ public void setIndex(int index) { public void reset() { index = 0; probeNext = false; + deleteCursor[0] = + (deletionList == null || scanOrder.isAscending()) ? 0 : (deletionList.size() - 1); } public TVList getTVList() { diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/AlignedSeriesScanOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/AlignedSeriesScanOperatorTest.java index e6c567fac961a..6f695b8d4b237 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/AlignedSeriesScanOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/AlignedSeriesScanOperatorTest.java @@ -129,7 +129,6 @@ public void batchTest1() throws Exception { alignedPath, Ordering.ASC, getDefaultSeriesScanOptions(alignedPath), - false, null, -1); seriesScanOperator.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); @@ -228,7 +227,6 @@ public void batchTest2() throws Exception { alignedPath1, Ordering.ASC, getDefaultSeriesScanOptions(alignedPath1), - false, null, -1); seriesScanOperator1.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); @@ -252,7 +250,6 @@ public void batchTest2() throws Exception { alignedPath2, Ordering.ASC, getDefaultSeriesScanOptions(alignedPath2), - false, null, -1); seriesScanOperator2.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); @@ -538,7 +535,6 @@ public void batchTest3() throws Exception { alignedPath1, Ordering.DESC, getDefaultSeriesScanOptions(alignedPath1), - false, null, -1); seriesScanOperator1.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); @@ -562,7 +558,6 @@ public void batchTest3() throws Exception { alignedPath2, Ordering.DESC, getDefaultSeriesScanOptions(alignedPath2), - false, null, -1); seriesScanOperator2.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/DeviceIteratorScanOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/DeviceIteratorScanOperatorTest.java index 9b470f71020d4..cd3dd410ff78a 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/DeviceIteratorScanOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/DeviceIteratorScanOperatorTest.java @@ -156,7 +156,6 @@ public void generateCurrentDeviceOperatorTree( alignedPath, Ordering.ASC, getDefaultSeriesScanOptions(alignedPath), - false, null, -1); } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/OperatorMemoryTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/OperatorMemoryTest.java index 22db4661614f2..e38e70945fdd6 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/OperatorMemoryTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/OperatorMemoryTest.java @@ -202,7 +202,6 @@ public void alignedSeriesScanOperatorTest() { alignedPath, Ordering.ASC, SeriesScanOptions.getDefaultSeriesScanOptions(alignedPath), - false, null, -1); diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/ViewFromTreeAdaptorOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/ViewFromTreeAdaptorOperatorTest.java index 92bd6b340850b..92bfb69255932 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/ViewFromTreeAdaptorOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/ViewFromTreeAdaptorOperatorTest.java @@ -131,7 +131,6 @@ public void test1() { alignedPath, Ordering.ASC, getDefaultSeriesScanOptions(alignedPath), - false, null, -1); seriesScanOperator.initQueryDataSource(new QueryDataSource(seqResources, unSeqResources)); 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..1275c17f05ac5 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanMaterializer.java @@ -0,0 +1,684 @@ +/* + * 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.ModEntry; +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.ModificationUtils; +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.AbstractAlignedChunkMetadata; +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(); + writeMods(handle, file, origin); + flushedChunkMetadata = visibleChunkMetadata(handle, writer, origin); + } + 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, with file modifications + * applied. + */ + private static List visibleChunkMetadata( + Handle handle, RestorableTsFileIOWriter writer, TsFileResource resource) { + SeriesScanScenario scenario = handle.scenario; + if (!scenario.aligned()) { + List chunkMetadataList = + new ArrayList<>( + writer.getVisibleMetadataList(DEVICE_ID, MEASUREMENT, scenario.storedTypes.get(0))); + List modifications = + handle.context.getPathModifications(resource, DEVICE_ID, MEASUREMENT); + ModificationUtils.modifyChunkMetaData(chunkMetadataList, modifications); + return chunkMetadataList; + } + List> valueChunkMetadataList = new ArrayList<>(); + List queriedMeasurements = new ArrayList<>(scenario.columnCount()); + for (int column = 0; column < scenario.columnCount(); column++) { + String measurement = measurement(scenario.queriedColumns.get(column)); + queriedMeasurements.add(measurement); + 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)); + } + } + List timeColumnModifications = + handle.context.getPathModifications(resource, DEVICE_ID, AlignedPath.VECTOR_PLACEHOLDER); + List> valueColumnsModifications = + handle.context.getPathModifications(resource, DEVICE_ID, queriedMeasurements); + ModificationUtils.modifyAlignedChunkMetaData( + result, timeColumnModifications, valueColumnsModifications, scenario.ignoreAllNullRows()); + return new ArrayList<>(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..9cbb839c39671 --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenario.java @@ -0,0 +1,1128 @@ +/* + * 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); + Row existing = byTime.get(row.time); + if (existing == null) { + byTime.put(row.time, row); + } else { + Object[] merged = Arrays.copyOf(existing.values, existing.values.length); + for (int i = 0; i < row.values.length && i < merged.length; i++) { + if (row.values[i] != null) { + merged[i] = row.values[i]; + } + } + byTime.put(row.time, new Row(row.time, merged)); + } + 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; + + /** The scenario number accepted by {@code scan_seed}; 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 && file.diskChunks.isEmpty()) { + continue; + } + List rows = file.open ? rowsOfDiskChunks(file) : 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); + } + 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, scenario, file, file.memChunks.size(), writerRows, nullLevel); + } + } + } + + /** Puts the rows of one memory table into one TVList, or into two of them. */ + private static void fillMemChunk( + Random rnd, + SeriesScanScenario scenario, + FileNode file, + int memChunkIndex, + List rows, + int nullLevel) { + 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); + maybeAddDuplicateTimestamp(rnd, scenario, tvList, nullLevel); + 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)); + } + maybeAddDuplicateTimestamp(rnd, scenario, older, nullLevel); + maybeAddDuplicateTimestamp(rnd, scenario, newer, nullLevel); + memChunk.tvLists.add(older); + memChunk.tvLists.add(newer); + } + file.memChunks.add(memChunk); + } + + /** + * Occasionally appends a repeated timestamp with partial nulls inside a single aligned TVList. + */ + private static void maybeAddDuplicateTimestamp( + Random rnd, SeriesScanScenario scenario, Source tvList, int nullLevel) { + if (!scenario.aligned() || tvList.rows().isEmpty() || rnd.nextInt(3) != 0) { + return; + } + Row base = tvList.rows().get(rnd.nextInt(tvList.rows().size())); + tvList.addRow(rewrittenRow(rnd, scenario, base, Math.max(2, nullLevel))); + } + + private static List rowsOfDiskChunks(FileNode file) { + List rows = new ArrayList<>(); + for (Source chunk : file.diskChunks) { + rows.addAll(chunk.rows()); + } + rows.sort((a, b) -> Long.compare(a.time, b.time)); + return rows; + } + + 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 = Long.MAX_VALUE; + long end = Long.MIN_VALUE; + for (Row row : rows) { + start = Math.min(start, row.time); + end = Math.max(end, row.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()); + int nullPick = rnd.nextInt(10); + if (nullPick == 0) { + return ValueFilterApi.isNull(column); + } + if (nullPick == 1) { + return ValueFilterApi.isNotNull(column); + } + 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).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..021cb2dbfcacc --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanScenarioRunner.java @@ -0,0 +1,262 @@ +/* + * 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; + } + + interface ScanAction { + T run(SeriesScanUtil scan, FragmentInstanceContext context) throws Exception; + } + + static T runWithScan( + SeriesScanScenario scenario, boolean withPagination, ScanAction action) + throws IOException { + return withMaterialized( + scenario, handle -> action.run(newScan(handle, withPagination), handle.context)); + } + + /** + * 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, + 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..ea5ad2c60ed4c --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilDefectTest.java @@ -0,0 +1,882 @@ +/* + * 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.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.iotdb.db.queryengine.plan.planner.plan.parameter.SeriesScanOptions; +import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering; +import org.apache.iotdb.db.storageengine.dataregion.read.QueryDataSource; +import org.apache.iotdb.db.storageengine.dataregion.tsfile.TsFileResource; +import org.apache.iotdb.db.utils.datastructure.TVList; + +import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.AbstractAlignedTimeSeriesMetadata; +import org.apache.tsfile.file.metadata.AlignedTimeSeriesMetadata; +import org.apache.tsfile.file.metadata.IMetadata; +import org.apache.tsfile.file.metadata.TimeseriesMetadata; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.apache.tsfile.file.metadata.statistics.Statistics; +import org.apache.tsfile.read.common.TimeRange; +import org.apache.tsfile.read.common.block.TsBlock; +import org.apache.tsfile.read.filter.basic.Filter; +import org.apache.tsfile.read.filter.basic.OperatorType; +import org.apache.tsfile.read.filter.factory.FilterFactory; +import org.apache.tsfile.read.filter.factory.ValueFilterApi; +import org.apache.tsfile.utils.Binary; +import org.apache.tsfile.write.schema.IMeasurementSchema; +import org.apache.tsfile.write.schema.MeasurementSchema; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +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; +import static org.apache.iotdb.db.queryengine.plan.statement.component.Ordering.DESC; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * 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.offset = 3; + s.limit = 5; + + assertRows(s, row(5, 5L, null)); + } + + @Test + public void mergeSortMultiAlignedTVListSkipsDeletedRowsWithoutCorruptingNextRowDesc() + throws IOException { + SeriesScanScenario s = create(Model.ALIGNED_TREE, DESC, TSDataType.DOUBLE); + FileNode open = s.addFile(false, true, 1); + s.addMemChunk(open, page(row(29, 171.9), row(30, 199.4), row(34, 1.0)), page(row(32, 2.0))); + open.memChunks.get(0).valueDeletions.get(0).addAll(ranges(32, 35)); + FileNode other = s.addFile(false, true, 2); + s.addMemChunk(other, page(row(31, 5.0))); + + assertRows(s, row(31, 5.0), row(30, 199.4), row(29, 171.9)); + } + + @Test + public void mergeSortMultiAlignedTVListSkipsDeletedRowsWithoutCorruptingNextRowAsc() + throws IOException { + SeriesScanScenario s = create(Model.ALIGNED_TREE, ASC, TSDataType.INT64); + FileNode open = s.addFile(false, true, 1); + s.addMemChunk( + open, page(row(10, 1L), row(20, 2L), row(30, 3L)), page(row(15, 4L), row(25, 5L))); + open.memChunks.get(0).valueDeletions.get(0).addAll(ranges(10, 15)); + + assertRows(s, row(20, 2L), row(25, 5L), row(30, 3L)); + } + + @Test + public void duplicateTimestampsInSingleAlignedTVListMergePerColumn() throws IOException { + for (Ordering ordering : new Ordering[] {ASC, DESC}) { + SeriesScanScenario s = + create(Model.ALIGNED_TREE, ordering, TSDataType.INT64, TSDataType.INT64); + FileNode open = s.addFile(false, true, 1); + s.addMemChunk(open, page(row(1, 10L, null), row(1, null, 20L))); + + assertRows(s, row(1, 10L, 20L)); + } + } + + @Test + public void tvListIteratorResetReplaysDeletionsInAscAndDesc() { + TVList tvList = TVList.newList(TSDataType.INT64); + tvList.putLong(1, 10L); + tvList.putLong(2, 20L); + tvList.putLong(3, 30L); + tvList.putLong(4, 40L); + tvList.sort(); + List deletions = ranges(2, 3); + for (Ordering ordering : new Ordering[] {ASC, DESC}) { + TVList.TVListIterator iterator = + tvList.iterator( + ordering, tvList.rowCount(), null, deletions, 0, TSEncoding.PLAIN, 10, null); + List expected = ordering.isAscending() ? Arrays.asList(1L, 4L) : Arrays.asList(4L, 1L); + assertEquals(expected, drainTimestamps(iterator)); + iterator.reset(); + assertEquals(expected, drainTimestamps(iterator)); + } + } + + @Test + public void singleSparseColumnOffsetSkipsWholeFileWithoutDecoding() throws IOException { + SeriesScanScenario s = alignedTree(); + FileNode first = s.addFile(true, false, 1); + List firstRows = new ArrayList<>(); + for (long t = 1; t <= 20; t++) { + firstRows.add(t % 2 == 0 ? row(t, t, null) : row(t, null, t)); + } + addDiskChunk(first, firstRows); + FileNode second = s.addFile(true, false, 2); + addDiskChunk(second, page(row(21, 21L, null), row(22, 22L, null), row(23, null, 23L))); + s.queryColumns(0); + s.offset = 10; + s.limit = 1; + + List rows = + SeriesScanScenarioRunner.runWithScan( + s, + true, + (scan, ctx) -> { + List result = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(scan, 1); + assertEquals( + 1L, ctx.getQueryStatistics().getPageReadersDecodeAlignedDiskCount().get()); + return result; + }); + assertEquals(Collections.singletonList(row(21, 21L)).toString(), rows.toString()); + } + + @Test + public void disjointValueRangesUseFileStatisticsForCountTime() throws IOException { + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + List rows = new ArrayList<>(); + for (long t = 1; t <= 10; t++) { + rows.add(row(t, t, null)); + } + for (long t = 11; t <= 20; t++) { + rows.add(row(t, null, t)); + } + addDiskChunk(file, rows); + + SeriesScanScenarioRunner.runWithScan( + s, + false, + (scan, ctx) -> { + assertTrue(scan.hasNextFile().orElse(false)); + assertTrue(scan.canUseCurrentFileTimeStatistics()); + assertEquals(20L, scan.currentFileTimeStatistics().getCount()); + assertEquals(0L, ctx.getQueryStatistics().getPageReadersDecodeAlignedDiskCount().get()); + return null; + }); + assertAggregate(s, SeriesScanScenarioRunner.expectedAggregate(s)); + } + + @Test + public void modifiedAlignedPagePreservesLimitFastPathWhenFilterColumnIsUnaffected() + throws IOException { + SeriesScanScenario unaffected = alignedTree(); + FileNode file1 = unaffected.addFile(true, false, 1); + List rows = new ArrayList<>(); + for (long t = 1; t <= 50; t++) { + rows.add(row(t, t, t)); + } + addDiskChunk(file1, rows); + file1.valueDeletions = unaffected.noValueDeletions(); + file1.valueDeletions.get(1).addAll(ranges(1, 1)); + CountingFilter unaffectedFilter = + new CountingFilter(ValueFilterApi.gt(0, 0L, TSDataType.INT64)); + unaffected.pushDownFilter = unaffectedFilter; + unaffected.limit = 1; + + assertRows(unaffected, row(1, 1L, null)); + assertEquals(0, unaffectedFilter.tsBlockEvaluations.get()); + + SeriesScanScenario affected = alignedTree(); + FileNode file2 = affected.addFile(true, false, 1); + addDiskChunk(file2, rows); + file2.valueDeletions = affected.noValueDeletions(); + file2.valueDeletions.get(0).addAll(ranges(1, 1)); + CountingFilter affectedFilter = new CountingFilter(ValueFilterApi.gt(0, 0L, TSDataType.INT64)); + affected.pushDownFilter = affectedFilter; + affected.limit = 1; + + assertRows(affected, row(2, 2L, 2L)); + assertEquals(1, affectedFilter.tsBlockEvaluations.get()); + } + + @Test + public void alteredDataTypeToStringReevaluatesPushDownPredicateAndPreservesUnaffectedLimit() + throws Exception { + // s0 is written as INT32 with extrema [1, 100]; as STRING, both "1" and "100" sort before "2", + // so StringNotEq("2").allSatisfy(...) returns true against the pre-alteration numeric stats. + SeriesScanScenario stored = create(Model.ALIGNED_TREE, ASC, TSDataType.INT32, TSDataType.INT32); + FileNode file = stored.addFile(true, false, 1); + addDiskChunk(file, page(row(1, 1, 10), row(2, 2, 20), row(3, 100, 30))); + + FragmentInstanceContext context = + FragmentInstanceContext.createFragmentInstanceContextForCompaction(999997L); + context.setIgnoreAllNullRows(true); + try (SeriesScanMaterializer.Handle handle = + SeriesScanMaterializer.materialize(stored, context)) { + List measurements = Arrays.asList("s0", "s1"); + List alteredSchemas = + Arrays.asList( + new MeasurementSchema("s0", TSDataType.STRING), + new MeasurementSchema("s1", TSDataType.INT32)); + AlignedFullPath alteredPath = + new AlignedFullPath(SeriesScanMaterializer.DEVICE_ID, measurements, alteredSchemas); + + CountingFilter notEq2 = + new CountingFilter( + ValueFilterApi.notEq( + 0, new Binary("2", TSFileConfig.STRING_CHARSET), TSDataType.STRING)); + SeriesScanOptions.Builder notEqOptions = new SeriesScanOptions.Builder(); + notEqOptions.withAllSensors(new HashSet<>(measurements)); + notEqOptions.withPushDownFilter(notEq2); + + AlignedSeriesScanUtil alteredScan = + new AlignedSeriesScanUtil(alteredPath, ASC, notEqOptions.build(), context); + alteredScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List filteredRows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(alteredScan, 2); + assertEquals( + Arrays.asList( + row(1, new Binary("1", TSFileConfig.STRING_CHARSET), 10), + row(3, new Binary("100", TSFileConfig.STRING_CHARSET), 30)) + .toString(), + filteredRows.toString()); + assertEquals(1, notEq2.tsBlockEvaluations.get()); + + // Predicate on the unaffected INT32 column s1 keeps the LIMIT fast path intact. + CountingFilter s1Gt0 = new CountingFilter(ValueFilterApi.gt(1, 0, TSDataType.INT32)); + SeriesScanOptions.Builder limitOptions = new SeriesScanOptions.Builder(); + limitOptions.withAllSensors(new HashSet<>(measurements)); + limitOptions.withPushDownFilter(s1Gt0); + limitOptions.withPushDownLimit(1L); + + AlignedSeriesScanUtil limitScan = + new AlignedSeriesScanUtil(alteredPath, ASC, limitOptions.build(), context); + limitScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List limitedRows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(limitScan, 2); + assertEquals( + Collections.singletonList(row(1, new Binary("1", TSFileConfig.STRING_CHARSET), 10)) + .toString(), + limitedRows.toString()); + assertEquals(0, s1Gt0.tsBlockEvaluations.get()); + } + } + + @Test + public void alteredBooleanDataTypeToStringReevaluatesPushDownPredicateAndPreservesUnaffected() + throws Exception { + // s0 is written as BOOLEAN (whose BooleanStatistics throws on getMinValue()). Querying s0 as + // STRING with a pushed-down STRING predicate must check type validity before calling + // allSatisfy(pageReader), while unaffected INT32 predicates still keep the LIMIT fast path. + SeriesScanScenario stored = + create(Model.ALIGNED_TREE, ASC, TSDataType.BOOLEAN, TSDataType.INT32); + FileNode file = stored.addFile(true, false, 1); + addDiskChunk(file, page(row(1, true, 10), row(2, false, 20), row(3, true, 30))); + + FragmentInstanceContext context = + FragmentInstanceContext.createFragmentInstanceContextForCompaction(999996L); + context.setIgnoreAllNullRows(true); + try (SeriesScanMaterializer.Handle handle = + SeriesScanMaterializer.materialize(stored, context)) { + List measurements = Arrays.asList("s0", "s1"); + List alteredSchemas = + Arrays.asList( + new MeasurementSchema("s0", TSDataType.STRING), + new MeasurementSchema("s1", TSDataType.INT32)); + AlignedFullPath alteredPath = + new AlignedFullPath(SeriesScanMaterializer.DEVICE_ID, measurements, alteredSchemas); + + CountingFilter notEqFalse = + new CountingFilter( + ValueFilterApi.notEq( + 0, new Binary("false", TSFileConfig.STRING_CHARSET), TSDataType.STRING)); + SeriesScanOptions.Builder notEqOptions = new SeriesScanOptions.Builder(); + notEqOptions.withAllSensors(new HashSet<>(measurements)); + notEqOptions.withPushDownFilter(notEqFalse); + + AlignedSeriesScanUtil notEqScan = + new AlignedSeriesScanUtil(alteredPath, ASC, notEqOptions.build(), context); + notEqScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List notEqRows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(notEqScan, 2); + assertEquals( + Arrays.asList( + row(1, new Binary("true", TSFileConfig.STRING_CHARSET), 10), + row(3, new Binary("true", TSFileConfig.STRING_CHARSET), 30)) + .toString(), + notEqRows.toString()); + assertEquals(1, notEqFalse.tsBlockEvaluations.get()); + + // Equality on altered BOOLEAN -> STRING must also avoid BooleanStatistics.getMinValue(). + CountingFilter eqTrue = + new CountingFilter( + ValueFilterApi.eq( + 0, new Binary("true", TSFileConfig.STRING_CHARSET), TSDataType.STRING)); + SeriesScanOptions.Builder eqOptions = new SeriesScanOptions.Builder(); + eqOptions.withAllSensors(new HashSet<>(measurements)); + eqOptions.withPushDownFilter(eqTrue); + + AlignedSeriesScanUtil eqScan = + new AlignedSeriesScanUtil(alteredPath, ASC, eqOptions.build(), context); + eqScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List eqRows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(eqScan, 2); + assertEquals( + Arrays.asList( + row(1, new Binary("true", TSFileConfig.STRING_CHARSET), 10), + row(3, new Binary("true", TSFileConfig.STRING_CHARSET), 30)) + .toString(), + eqRows.toString()); + assertEquals(1, eqTrue.tsBlockEvaluations.get()); + + // Predicate on unaffected INT32 column s1 retains the early-stop LIMIT fast path. + CountingFilter s1Gt0 = new CountingFilter(ValueFilterApi.gt(1, 0, TSDataType.INT32)); + SeriesScanOptions.Builder limitOptions = new SeriesScanOptions.Builder(); + limitOptions.withAllSensors(new HashSet<>(measurements)); + limitOptions.withPushDownFilter(s1Gt0); + limitOptions.withPushDownLimit(1L); + + AlignedSeriesScanUtil limitScan = + new AlignedSeriesScanUtil(alteredPath, ASC, limitOptions.build(), context); + limitScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List limitedRows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(limitScan, 2); + assertEquals( + Collections.singletonList(row(1, new Binary("true", TSFileConfig.STRING_CHARSET), 10)) + .toString(), + limitedRows.toString()); + assertEquals(0, s1Gt0.tsBlockEvaluations.get()); + } + + // Compound filter combining a value-deleted column (s1) and an altered BOOLEAN column (s0) + // must never invoke BooleanStatistics.getMinValue() on the second pass either. + SeriesScanScenario compound = + create(Model.ALIGNED_TREE, ASC, TSDataType.BOOLEAN, TSDataType.INT32); + FileNode deletedFile = compound.addFile(true, false, 1); + addDiskChunk(deletedFile, page(row(1, true, 10), row(2, false, 20), row(3, true, 30))); + deletedFile.valueDeletions = compound.noValueDeletions(); + deletedFile.valueDeletions.get(1).addAll(ranges(1, 1)); + FragmentInstanceContext compoundContext = + FragmentInstanceContext.createFragmentInstanceContextForCompaction(999995L); + compoundContext.setIgnoreAllNullRows(true); + try (SeriesScanMaterializer.Handle handle = + SeriesScanMaterializer.materialize(compound, compoundContext)) { + List measurements = Arrays.asList("s0", "s1"); + List alteredSchemas = + Arrays.asList( + new MeasurementSchema("s0", TSDataType.STRING), + new MeasurementSchema("s1", TSDataType.INT32)); + AlignedFullPath alteredPath = + new AlignedFullPath(SeriesScanMaterializer.DEVICE_ID, measurements, alteredSchemas); + Filter compoundFilter = + FilterFactory.and( + ValueFilterApi.gt(1, 0, TSDataType.INT32), + ValueFilterApi.notEq( + 0, new Binary("false", TSFileConfig.STRING_CHARSET), TSDataType.STRING)); + SeriesScanOptions.Builder options = new SeriesScanOptions.Builder(); + options.withAllSensors(new HashSet<>(measurements)); + options.withPushDownFilter(compoundFilter); + + AlignedSeriesScanUtil scan = + new AlignedSeriesScanUtil(alteredPath, ASC, options.build(), compoundContext); + scan.initQueryDataSource(new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List rows = SeriesScanFuzzDriver.scanLikeSeriesScanOperator(scan, 2); + assertEquals( + Collections.singletonList(row(3, new Binary("true", TSFileConfig.STRING_CHARSET), 30)) + .toString(), + rows.toString()); + } + } + + @Test + public void zeroOffsetSkipsPaginationStatisticsOnSparseAlignedScan() throws Exception { + int columnCount = 64; + int pageCount = 16; + int rowsPerPage = 64; + TSDataType[] types = new TSDataType[columnCount]; + Arrays.fill(types, TSDataType.INT64); + SeriesScanScenario s = create(Model.ALIGNED_TREE, ASC, types); + FileNode file = s.addFile(true, false, 1); + SeriesScanScenario.Source chunk = addDiskChunk(file); + long time = 1; + for (int p = 0; p < pageCount; p++) { + chunk.startNewPage(); + for (int r = 0; r < rowsPerPage; r++) { + Object[] values = new Object[columnCount]; + values[(int) ((time - 1) % columnCount)] = time; + chunk.addRow(new Row(time, values)); + time++; + } + } + + FragmentInstanceContext context = + FragmentInstanceContext.createFragmentInstanceContextForCompaction(999998L); + context.setIgnoreAllNullRows(true); + try (SeriesScanMaterializer.Handle handle = SeriesScanMaterializer.materialize(s, context)) { + AtomicInteger zeroOffsetStatsChecks = new AtomicInteger(); + SeriesScanOptions.Builder zeroOffsetOptions = new SeriesScanOptions.Builder(); + zeroOffsetOptions.withAllSensors(new HashSet<>(handle.measurements())); + AlignedSeriesScanUtil zeroOffsetScan = + new AlignedSeriesScanUtil( + (AlignedFullPath) handle.path, ASC, zeroOffsetOptions.build(), context) { + @Override + protected boolean canUseTimeStatistics(IMetadata metadata) { + zeroOffsetStatsChecks.incrementAndGet(); + return super.canUseTimeStatistics(metadata); + } + }; + zeroOffsetScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List allRows = + SeriesScanFuzzDriver.scanLikeSeriesScanOperator(zeroOffsetScan, columnCount); + assertEquals(pageCount * rowsPerPage, allRows.size()); + assertEquals(0, zeroOffsetStatsChecks.get()); + + // Sanity check: a non-zero OFFSET still exercises the pagination statistics path. + AtomicInteger nonZeroOffsetStatsChecks = new AtomicInteger(); + SeriesScanOptions.Builder nonZeroOffsetOptions = new SeriesScanOptions.Builder(); + nonZeroOffsetOptions.withAllSensors(new HashSet<>(handle.measurements())); + nonZeroOffsetOptions.withPushDownOffset(10L); + nonZeroOffsetOptions.withPushDownLimit(5L); + AlignedSeriesScanUtil nonZeroOffsetScan = + new AlignedSeriesScanUtil( + (AlignedFullPath) handle.path, ASC, nonZeroOffsetOptions.build(), context) { + @Override + protected boolean canUseTimeStatistics(IMetadata metadata) { + nonZeroOffsetStatsChecks.incrementAndGet(); + return super.canUseTimeStatistics(metadata); + } + }; + nonZeroOffsetScan.initQueryDataSource( + new QueryDataSource(handle.seqResources(), handle.unseqResources())); + List pagedRows = + SeriesScanFuzzDriver.scanLikeSeriesScanOperator(nonZeroOffsetScan, columnCount); + assertEquals(5, pagedRows.size()); + assertEquals(11L, pagedRows.get(0).time); + assertTrue(nonZeroOffsetStatsChecks.get() > 0); + } + } + + @Test + public void alignedTimeStatisticsRejectAllNullQueriedColumns() throws IOException { + SeriesScanScenario s = alignedTree(); + FileNode file = s.addFile(true, false, 1); + addDiskChunk(file, page(row(1, null, 1L), row(2, null, 2L))); + s.queryColumns(0); + + assertAggregate(s, aggregate(TSDataType.INT64)); + + // Also verify directly when an aligned metadata object has measurementCount > 0 and all + // queried columns are null/empty (nonNullCount == 0): must reject rather than returning the + // unprojected timeStatistics count. + Statistics timeStats = Statistics.getStatsByType(TSDataType.VECTOR); + timeStats.update(1L); + timeStats.update(2L); + TimeseriesMetadata timeMeta = new TimeseriesMetadata(); + timeMeta.setMeasurementId(""); + timeMeta.setTsDataType(TSDataType.VECTOR); + timeMeta.setStatistics(timeStats); + AlignedTimeSeriesMetadata allNullMetadata = + new AlignedTimeSeriesMetadata(timeMeta, Collections.singletonList(null)); + + MeasurementSchema s0Schema = new MeasurementSchema("s0", TSDataType.INT64); + AlignedFullPath path = + new AlignedFullPath( + SeriesScanMaterializer.DEVICE_ID, + Collections.singletonList("s0"), + Collections.singletonList(s0Schema)); + FragmentInstanceContext context = + FragmentInstanceContext.createFragmentInstanceContextForCompaction(999999L); + context.setIgnoreAllNullRows(true); + SeriesScanOptions.Builder optionsBuilder = new SeriesScanOptions.Builder(); + optionsBuilder.withAllSensors(Collections.singleton("s0")); + AlignedSeriesScanUtil scanUtil = + new AlignedSeriesScanUtil(path, ASC, optionsBuilder.build(), context) { + @Override + protected AbstractAlignedTimeSeriesMetadata loadTimeSeriesMetadata( + TsFileResource resource, boolean isSeq) { + return allNullMetadata; + } + }; + TsFileResource dummyResource = new TsFileResource(new File("1-1-0-0.tsfile")); + dummyResource.updateStartTime(SeriesScanMaterializer.DEVICE_ID, 1L); + dummyResource.updateEndTime(SeriesScanMaterializer.DEVICE_ID, 2L); + scanUtil.initQueryDataSource( + new QueryDataSource(Collections.singletonList(dummyResource), Collections.emptyList())); + + assertTrue(scanUtil.hasNextFile().orElse(false)); + assertFalse(scanUtil.canUseCurrentFileTimeStatistics()); + } + + @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()); + } + } + + private static List drainTimestamps(TVList.TVListIterator iterator) { + List timestamps = new ArrayList<>(); + while (iterator.hasNextTimeValuePair()) { + timestamps.add(iterator.nextTimeValuePair().getTimestamp()); + } + return timestamps; + } + + /** Filter wrapper that counts TsBlock-level evaluations while delegating everything else. */ + private static final class CountingFilter extends Filter { + private final Filter delegate; + final AtomicInteger tsBlockEvaluations = new AtomicInteger(); + + CountingFilter(Filter delegate) { + this.delegate = delegate; + } + + @Override + public boolean satisfy(long time, Object value) { + return delegate.satisfy(time, value); + } + + @Override + public boolean satisfyBoolean(long time, boolean value) { + return delegate.satisfyBoolean(time, value); + } + + @Override + public boolean satisfyInteger(long time, int value) { + return delegate.satisfyInteger(time, value); + } + + @Override + public boolean satisfyLong(long time, long value) { + return delegate.satisfyLong(time, value); + } + + @Override + public boolean satisfyFloat(long time, float value) { + return delegate.satisfyFloat(time, value); + } + + @Override + public boolean satisfyDouble(long time, double value) { + return delegate.satisfyDouble(time, value); + } + + @Override + public boolean satisfyBinary(long time, Binary value) { + return delegate.satisfyBinary(time, value); + } + + @Override + public boolean satisfyString(long time, String value) { + return delegate.satisfyString(time, value); + } + + @Override + public boolean satisfyRow(long time, Object[] values) { + return delegate.satisfyRow(time, values); + } + + @Override + public boolean satisfyBooleanRow(long time, boolean[] values) { + return delegate.satisfyBooleanRow(time, values); + } + + @Override + public boolean satisfyIntegerRow(long time, int[] values) { + return delegate.satisfyIntegerRow(time, values); + } + + @Override + public boolean satisfyLongRow(long time, long[] values) { + return delegate.satisfyLongRow(time, values); + } + + @Override + public boolean satisfyFloatRow(long time, float[] values) { + return delegate.satisfyFloatRow(time, values); + } + + @Override + public boolean satisfyDoubleRow(long time, double[] values) { + return delegate.satisfyDoubleRow(time, values); + } + + @Override + public boolean satisfyBinaryRow(long time, Binary[] values) { + return delegate.satisfyBinaryRow(time, values); + } + + @Override + @Deprecated + public boolean[] satisfyTsBlock(TsBlock tsBlock) { + tsBlockEvaluations.incrementAndGet(); + return delegate.satisfyTsBlock(tsBlock); + } + + @Override + public boolean[] satisfyTsBlock(boolean[] selection, TsBlock tsBlock) { + tsBlockEvaluations.incrementAndGet(); + return delegate.satisfyTsBlock(selection, tsBlock); + } + + @Override + public boolean canSkip(IMetadata metadata) { + return delegate.canSkip(metadata); + } + + @Override + public boolean allSatisfy(IMetadata metadata) { + return delegate.allSatisfy(metadata); + } + + @Override + public boolean satisfyStartEndTime(long startTime, long endTime) { + return delegate.satisfyStartEndTime(startTime, endTime); + } + + @Override + public boolean containStartEndTime(long startTime, long endTime) { + return delegate.containStartEndTime(startTime, endTime); + } + + @Override + public List getTimeRanges() { + return delegate.getTimeRanges(); + } + + @Override + public Filter reverse() { + return delegate.reverse(); + } + + @Override + public OperatorType getOperatorType() { + return delegate.getOperatorType(); + } + } +} 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..677e328831bdc --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/source/scanfuzz/SeriesScanUtilFuzzTest.java @@ -0,0 +1,202 @@ +/* + * 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 || index % 3 == 0; + config.subsetSensors = SUBSET_SENSORS || index % 4 == 0; + 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 = seed; + 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(), seed)); + } + } + 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("], scan_seed=") + .append( + ofKind.stream() + .map(example -> String.valueOf(example.seed)) + .limit(8) + .collect(Collectors.joining(","))) + .append(" (model=") + .append(model) + .append(" order=") + .append(ordering) + .append(')'); + // 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 int seed; + + Example(String detail, String scenario, int 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()); + } +} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/AlignedMemPageReaderTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/AlignedMemPageReaderTest.java deleted file mode 100644 index bdfa7d37076ac..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/AlignedMemPageReaderTest.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.AlignedChunkMetadata; -import org.apache.tsfile.file.metadata.IMetadata; -import org.apache.tsfile.file.metadata.statistics.IntegerStatistics; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.file.metadata.statistics.TimeStatistics; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.common.block.TsBlockBuilder; -import org.apache.tsfile.read.filter.basic.Filter; -import org.apache.tsfile.read.filter.factory.TimeFilterApi; -import org.apache.tsfile.read.filter.factory.ValueFilterApi; -import org.apache.tsfile.read.reader.series.PaginationController; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Optional; -import java.util.function.Supplier; - -import static org.apache.tsfile.read.filter.factory.ValueFilterApi.DEFAULT_MEASUREMENT_INDEX; - -public class AlignedMemPageReaderTest { - - private static final TsBlock tsBlock1; - private static final AlignedChunkMetadata chunkMetadata1 = - Mockito.mock(AlignedChunkMetadata.class); - - private static final TsBlock tsBlock2; - private static final AlignedChunkMetadata chunkMetadata2 = - Mockito.mock(AlignedChunkMetadata.class); - - static { - TsBlockBuilder tsBlockBuilder1 = - new TsBlockBuilder(Arrays.asList(TSDataType.INT32, TSDataType.INT32)); - TsBlockBuilder tsBlockBuilder2 = - new TsBlockBuilder(Collections.singletonList(TSDataType.INT32)); - - TimeStatistics timeStatistics = new TimeStatistics(); - IntegerStatistics valueStatistics1 = new IntegerStatistics(); - IntegerStatistics valueStatistics2 = new IntegerStatistics(); - - for (int i = 0; i < 100; i++) { - tsBlockBuilder1.getTimeColumnBuilder().writeLong(i); - tsBlockBuilder2.getTimeColumnBuilder().writeLong(i); - timeStatistics.update(i); - - tsBlockBuilder1.getValueColumnBuilders()[0].writeInt(i); - valueStatistics1.update(i, i); - - if (i >= 10 && i < 90) { - tsBlockBuilder1.getValueColumnBuilders()[1].writeInt(i); - tsBlockBuilder2.getValueColumnBuilders()[0].writeInt(i); - valueStatistics2.update(i, i); - } else { - tsBlockBuilder1.getValueColumnBuilders()[1].appendNull(); - tsBlockBuilder2.getValueColumnBuilders()[0].appendNull(); - } - tsBlockBuilder1.declarePosition(); - tsBlockBuilder2.declarePosition(); - } - - tsBlock1 = tsBlockBuilder1.build(); - Mockito.when(chunkMetadata1.getTimeStatistics()).thenReturn((Statistics) timeStatistics); - Mockito.when(chunkMetadata1.getMeasurementStatistics(0)) - .thenReturn(Optional.of(valueStatistics1)); - Mockito.when(chunkMetadata1.getMeasurementStatistics(1)) - .thenReturn(Optional.of(valueStatistics2)); - - tsBlock2 = tsBlockBuilder2.build(); - Mockito.when(chunkMetadata2.getTimeStatistics()).thenReturn((Statistics) timeStatistics); - Mockito.when(chunkMetadata2.getMeasurementStatistics(0)) - .thenReturn(Optional.of(valueStatistics2)); - } - - private MemAlignedPageReader generateAlignedPageReader() { - Supplier tsBlockSupplier = () -> tsBlock1; - Statistics[] valueStatistcsList = - chunkMetadata1.getValueChunkMetadataList().stream() - .map(IMetadata::getStatistics) - .toArray(Statistics[]::new); - MemAlignedPageReader alignedPageReader = - new MemAlignedPageReader( - tsBlockSupplier, - 0, - Arrays.asList(TSDataType.INT32, TSDataType.INT32), - chunkMetadata1.getTimeStatistics(), - valueStatistcsList, - null); - alignedPageReader.initTsBlockBuilder(Arrays.asList(TSDataType.INT32, TSDataType.INT32)); - return alignedPageReader; - } - - private MemAlignedPageReader generateSingleColumnAlignedPageReader() { - Supplier tsBlockSupplier = () -> tsBlock2; - Statistics[] valueStatistcsList = - chunkMetadata2.getValueChunkMetadataList().stream() - .map(IMetadata::getStatistics) - .toArray(Statistics[]::new); - MemAlignedPageReader alignedPageReader = - new MemAlignedPageReader( - tsBlockSupplier, - 0, - Arrays.asList(TSDataType.INT32), - chunkMetadata2.getTimeStatistics(), - valueStatistcsList, - null); - alignedPageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.INT32)); - return alignedPageReader; - } - - @Test - public void testNullFilter() { - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(100, tsBlock1.getPositionCount()); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(100, tsBlock2.getPositionCount()); - } - - @Test - public void testNullFilterWithLimitOffset() { - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock1.getPositionCount()); - Assert.assertEquals(10, tsBlock1.getTimeByIndex(0)); - Assert.assertEquals(19, tsBlock1.getTimeByIndex(9)); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock2.getPositionCount()); - Assert.assertEquals(10, tsBlock2.getTimeByIndex(0)); - Assert.assertEquals(19, tsBlock2.getTimeByIndex(9)); - } - - @Test - public void testGlobalTimeFilterAllSatisfy() { - Filter globalTimeFilter = TimeFilterApi.gtEq(0L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 50, TSDataType.INT32)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(50, tsBlock1.getPositionCount()); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 50, TSDataType.INT32)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(40, tsBlock2.getPositionCount()); - } - - @Test - public void testGlobalTimeFilterAllSatisfyWithLimitOffset() { - Filter globalTimeFilter = TimeFilterApi.gtEq(0L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 50, TSDataType.INT32)); - alignedPageReader1.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock1.getPositionCount()); - Assert.assertEquals(60, tsBlock1.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock1.getTimeByIndex(9)); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 50, TSDataType.INT32)); - alignedPageReader2.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock2.getPositionCount()); - Assert.assertEquals(60, tsBlock2.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock2.getTimeByIndex(9)); - } - - @Test - public void testPushDownFilterAllSatisfy() { - Filter globalTimeFilter = TimeFilterApi.gtEq(50L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 0, TSDataType.INT32)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(50, tsBlock1.getPositionCount()); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 0, TSDataType.INT32)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(40, tsBlock2.getPositionCount()); - } - - @Test - public void testPushDownFilterAllSatisfyWithLimitOffset() { - Filter globalTimeFilter = TimeFilterApi.gtEq(50L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 0, TSDataType.INT32)); - alignedPageReader1.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock1.getPositionCount()); - Assert.assertEquals(60, tsBlock1.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock1.getTimeByIndex(9)); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.gtEq(DEFAULT_MEASUREMENT_INDEX, 0, TSDataType.INT32)); - alignedPageReader2.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock2.getPositionCount()); - Assert.assertEquals(60, tsBlock2.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock2.getTimeByIndex(9)); - } - - @Test - public void testFilter() { - Filter globalTimeFilter = TimeFilterApi.gtEq(30L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(50, tsBlock1.getPositionCount()); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(50, tsBlock2.getPositionCount()); - } - - @Test - public void testFilterWithLimitOffset() { - Filter globalTimeFilter = TimeFilterApi.gtEq(50L); - MemAlignedPageReader alignedPageReader1 = generateAlignedPageReader(); - alignedPageReader1.addRecordFilter(globalTimeFilter); - alignedPageReader1.addRecordFilter( - ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - alignedPageReader1.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock1 = alignedPageReader1.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock1.getPositionCount()); - Assert.assertEquals(60, tsBlock1.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock1.getTimeByIndex(9)); - - MemAlignedPageReader alignedPageReader2 = generateSingleColumnAlignedPageReader(); - alignedPageReader2.addRecordFilter(globalTimeFilter); - alignedPageReader2.addRecordFilter( - ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - alignedPageReader2.setLimitOffset(new PaginationController(10, 10)); - TsBlock tsBlock2 = alignedPageReader2.getAllSatisfiedData(); - Assert.assertEquals(10, tsBlock2.getPositionCount()); - Assert.assertEquals(60, tsBlock2.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock2.getTimeByIndex(9)); - } -} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoaderTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoaderTest.java deleted file mode 100644 index 897bdc86a9fe9..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemAlignedChunkLoaderTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext; -import org.apache.iotdb.db.storageengine.dataregion.memtable.AlignedReadOnlyMemChunk; -import org.apache.iotdb.db.utils.datastructure.AlignedTVList; -import org.apache.iotdb.db.utils.datastructure.MemPointIterator; -import org.apache.iotdb.db.utils.datastructure.MemPointIteratorFactory; -import org.apache.iotdb.db.utils.datastructure.TVList; - -import org.apache.tsfile.common.conf.TSFileConfig; -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.statistics.Statistics; -import org.apache.tsfile.file.metadata.statistics.TimeStatistics; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.reader.IPageReader; -import org.apache.tsfile.utils.Binary; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.apache.tsfile.read.reader.series.PaginationController.UNLIMITED_PAGINATION_CONTROLLER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -public class MemAlignedChunkLoaderTest { - - private static final String BINARY_STR = "ty love zm"; - private static final int maxNumberOfPointsInPage = 1000; - - @Test - public void testMemAlignedChunkLoader() throws IOException { - AlignedReadOnlyMemChunk chunk = Mockito.mock(AlignedReadOnlyMemChunk.class); - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - QueryContext ctx = new QueryContext(false, false); - MemAlignedChunkLoader memAlignedChunkLoader = new MemAlignedChunkLoader(ctx, chunk); - - try { - memAlignedChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - // Mock getTimeStatisticsList & getValuesStatisticsList - List> timeStatitsticsList = new ArrayList<>(); - Statistics timeStatistics = Mockito.mock(TimeStatistics.class); - Mockito.when(timeStatistics.getCount()).thenReturn(2); - timeStatitsticsList.add(timeStatistics); - Mockito.when(chunk.getTimeStatisticsList()).thenReturn(timeStatitsticsList); - - List[]> valuesStatitsticsList = new ArrayList<>(); - Statistics[] valuesStatistics = new Statistics[6]; - Statistics statistics1 = Mockito.mock(Statistics.class); - Mockito.when(statistics1.hasNullValue(2)).thenReturn(true); - valuesStatistics[0] = statistics1; - Statistics statistics2 = Mockito.mock(Statistics.class); - Mockito.when(statistics2.hasNullValue(2)).thenReturn(true); - valuesStatistics[1] = statistics2; - Statistics statistics3 = Mockito.mock(Statistics.class); - Mockito.when(statistics3.hasNullValue(2)).thenReturn(true); - valuesStatistics[2] = statistics3; - Statistics statistics4 = Mockito.mock(Statistics.class); - Mockito.when(statistics4.hasNullValue(2)).thenReturn(true); - valuesStatistics[3] = statistics4; - Statistics statistics5 = Mockito.mock(Statistics.class); - Mockito.when(statistics5.hasNullValue(2)).thenReturn(true); - valuesStatistics[4] = statistics5; - Statistics statistics6 = Mockito.mock(Statistics.class); - Mockito.when(statistics6.hasNullValue(2)).thenReturn(true); - valuesStatistics[5] = statistics6; - valuesStatitsticsList.add(valuesStatistics); - Mockito.when(chunk.getValuesStatisticsList()).thenReturn(valuesStatitsticsList); - - // Mock AlignedReadOnlyMemChunk Getter - List dataTypes = buildTsDataTypes(); - Mockito.when(chunk.getDataTypes()).thenReturn(dataTypes); - Mockito.when(chunk.getTimeColumnDeletion()).thenReturn(null); - Mockito.when(chunk.getValueColumnsDeletionList()).thenReturn(null); - Mockito.when(chunk.getContext()).thenReturn(ctx); - - Map alignedTvListMap = buildAlignedTvListMap(); - Mockito.when(chunk.getAligendTvListQueryMap()).thenReturn(alignedTvListMap); - List alignedTvLists = - alignedTvListMap.keySet().stream().map(x -> (AlignedTVList) x).collect(Collectors.toList()); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - dataTypes, null, alignedTvLists, false, maxNumberOfPointsInPage, null); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - AlignedChunkMetadata chunkMetadata1 = Mockito.mock(AlignedChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - - MemAlignedChunkReader chunkReader = - (MemAlignedChunkReader) memAlignedChunkLoader.getChunkReader(chunkMetadata1, null); - - try { - chunkReader.hasNextSatisfiedPage(); - fail(); - } catch (IOException e) { - assertEquals("mem chunk reader does not support this method", e.getMessage()); - } - - try { - chunkReader.nextPageData(); - fail(); - } catch (IOException e) { - assertEquals("mem chunk reader does not support this method", e.getMessage()); - } - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemAlignedPageReader pageReader = (MemAlignedPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(buildTsDataTypes()); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertEquals(timeStatistics, pageReader.getStatistics()); - assertEquals(statistics1, pageReader.getMeasurementStatistics(0).orElse(null)); - assertEquals(timeStatistics, pageReader.getTimeStatistics()); - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memAlignedChunkLoader.close(); - } - - private List buildTsDataTypes() { - return Arrays.asList( - TSDataType.BOOLEAN, - TSDataType.INT32, - TSDataType.INT64, - TSDataType.FLOAT, - TSDataType.DOUBLE, - TSDataType.TEXT); - } - - private Map buildAlignedTvListMap() { - List dataTypes = buildTsDataTypes(); - AlignedTVList tvList1 = AlignedTVList.newAlignedList(dataTypes); - tvList1.putAlignedValue( - 1L, - new Object[] { - true, 1, 2L, 1.2f, null, new Binary(BINARY_STR, TSFileConfig.STRING_CHARSET) - }); - tvList1.putAlignedValue(2L, new Object[] {null, null, null, null, 3.14d, null}); - AlignedTVList tvList2 = AlignedTVList.newAlignedList(dataTypes); - tvList2.putAlignedValue( - 1L, - new Object[] { - true, 1, 1L, 1.1f, null, new Binary(BINARY_STR, TSFileConfig.STRING_CHARSET) - }); - - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } -} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoaderTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoaderTest.java deleted file mode 100644 index 885c329b86dc2..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemChunkLoaderTest.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.iotdb.db.queryengine.execution.fragment.QueryContext; -import org.apache.iotdb.db.storageengine.dataregion.memtable.ReadOnlyMemChunk; -import org.apache.iotdb.db.utils.datastructure.MemPointIterator; -import org.apache.iotdb.db.utils.datastructure.MemPointIteratorFactory; -import org.apache.iotdb.db.utils.datastructure.TVList; - -import org.apache.tsfile.common.conf.TSFileConfig; -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.ChunkMetadata; -import org.apache.tsfile.file.metadata.statistics.BinaryStatistics; -import org.apache.tsfile.file.metadata.statistics.BooleanStatistics; -import org.apache.tsfile.file.metadata.statistics.DoubleStatistics; -import org.apache.tsfile.file.metadata.statistics.FloatStatistics; -import org.apache.tsfile.file.metadata.statistics.IntegerStatistics; -import org.apache.tsfile.file.metadata.statistics.LongStatistics; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.BatchData; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.reader.IPageReader; -import org.apache.tsfile.utils.Binary; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static org.apache.tsfile.read.reader.series.PaginationController.UNLIMITED_PAGINATION_CONTROLLER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -public class MemChunkLoaderTest { - - private static final String BINARY_STR = "ty love zm"; - private static final int maxNumberOfPointsInPage = 1000; - - @Test - public void testBooleanMemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.BOOLEAN); - Map booleanTvListMap = buildBooleanTvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(booleanTvListMap); - List booleanTvLists = new ArrayList<>(booleanTvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.BOOLEAN, booleanTvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(BooleanStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(BooleanStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.BOOLEAN); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.BOOLEAN)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildBooleanTvListMap() { - TVList tvList1 = TVList.newList(TSDataType.BOOLEAN); - tvList1.putBoolean(1L, true); - tvList1.putBoolean(2L, true); - TVList tvList2 = TVList.newList(TSDataType.BOOLEAN); - tvList2.putBoolean(1L, true); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } - - @Test - public void testInt32MemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.INT32); - Map int32TvListMap = buildInt32TvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(int32TvListMap); - List int32TvLists = new ArrayList<>(int32TvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.INT32, int32TvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(IntegerStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(IntegerStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.INT32); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.INT32)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildInt32TvListMap() { - TVList tvList1 = TVList.newList(TSDataType.INT32); - tvList1.putInt(1L, 1); - tvList1.putInt(2L, 2); - TVList tvList2 = TVList.newList(TSDataType.INT32); - tvList2.putInt(1L, 1); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } - - @Test - public void testInt64MemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.INT64); - Map int64TvListMap = buildInt64TvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(int64TvListMap); - List int64TvLists = new ArrayList<>(int64TvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.INT64, int64TvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(LongStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(LongStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.INT64); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.INT64)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildInt64TvListMap() { - TVList tvList1 = TVList.newList(TSDataType.INT64); - tvList1.putLong(1L, 1L); - tvList1.putLong(2L, 2L); - TVList tvList2 = TVList.newList(TSDataType.INT64); - tvList2.putLong(1L, 1L); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } - - @Test - public void testFloatMemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.FLOAT); - Map floatTvListMap = buildFloatTvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(floatTvListMap); - List floatTvLists = new ArrayList<>(floatTvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.FLOAT, floatTvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(FloatStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(FloatStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.FLOAT); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.FLOAT)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildFloatTvListMap() { - TVList tvList1 = TVList.newList(TSDataType.FLOAT); - tvList1.putFloat(1L, 1.1f); - tvList1.putFloat(2L, 2.1f); - TVList tvList2 = TVList.newList(TSDataType.FLOAT); - tvList2.putFloat(1L, 1.1f); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } - - @Test - public void testDoubleMemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.DOUBLE); - Map doubleTvListMap = buildDoubleTvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(doubleTvListMap); - List doubleTvLists = new ArrayList<>(doubleTvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.DOUBLE, doubleTvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(DoubleStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(DoubleStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.DOUBLE); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.DOUBLE)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildDoubleTvListMap() { - TVList tvList1 = TVList.newList(TSDataType.DOUBLE); - tvList1.putDouble(1L, 1.1d); - tvList1.putDouble(2L, 2.1d); - TVList tvList2 = TVList.newList(TSDataType.DOUBLE); - tvList2.putDouble(1L, 1.1d); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } - - @Test - public void testTextMemChunkLoader() throws IOException { - ReadOnlyMemChunk chunk = Mockito.mock(ReadOnlyMemChunk.class); - Mockito.when(chunk.getDataType()).thenReturn(TSDataType.TEXT); - Map textTvListMap = buildTextTvListMap(); - Mockito.when(chunk.getTvListQueryMap()).thenReturn(textTvListMap); - List textTvLists = new ArrayList<>(textTvListMap.keySet()); - QueryContext queryContext = new QueryContext(false, false); - MemPointIterator timeValuePairIterator = - MemPointIteratorFactory.create( - TSDataType.TEXT, textTvLists, maxNumberOfPointsInPage, queryContext); - timeValuePairIterator.setStreamingQueryMemChunk(false); - timeValuePairIterator.nextBatch(); - Mockito.when(chunk.getMemPointIterator()).thenReturn(timeValuePairIterator); - - ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - MemChunkLoader memChunkLoader = new MemChunkLoader(queryContext, chunk); - try { - memChunkLoader.loadChunk(chunkMetadata); - fail(); - } catch (UnsupportedOperationException e) { - assertNull(e.getMessage()); - } - - Statistics pageStatistics = Mockito.mock(BinaryStatistics.class); - List> pageStats = Collections.singletonList(pageStatistics); - Mockito.when(chunk.getPageStatisticsList()).thenReturn(pageStats); - - ChunkMetadata chunkMetadata1 = Mockito.mock(ChunkMetadata.class); - Mockito.when(chunk.getChunkMetaData()).thenReturn(chunkMetadata1); - Mockito.when(chunk.getPointReader()).thenReturn(null); - Statistics statistics = Mockito.mock(BinaryStatistics.class); - Mockito.when(statistics.getCount()).thenReturn(2); - - Mockito.doReturn(statistics).when(chunkMetadata1).getStatistics(); - Mockito.when(chunkMetadata1.getDataType()).thenReturn(TSDataType.TEXT); - - MemChunkReader chunkReader = - (MemChunkReader) memChunkLoader.getChunkReader(chunkMetadata1, null); - - List pageReaderList = chunkReader.loadPageReaderList(); - assertEquals(1, pageReaderList.size()); - - MemPageReader pageReader = (MemPageReader) pageReaderList.get(0); - - pageReader.initTsBlockBuilder(Collections.singletonList(TSDataType.TEXT)); - - BatchData batchData = pageReader.getAllSatisfiedPageData(); - assertEquals(2, batchData.length()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - batchData = pageReader.getAllSatisfiedPageData(false); - assertEquals(2, batchData.length()); - assertEquals(BatchData.BatchDataType.DESC_READ, batchData.getBatchDataType()); - assertEquals(1L, batchData.getTimeByIndex(0)); - assertEquals(2L, batchData.getTimeByIndex(1)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - assertEquals(2, tsBlock.getPositionCount()); - assertEquals(1L, tsBlock.getTimeColumn().getLong(0)); - assertEquals(2L, tsBlock.getTimeColumn().getLong(1)); - - assertFalse(pageReader.isModified()); - pageReader.setLimitOffset(UNLIMITED_PAGINATION_CONTROLLER); - pageReader.addRecordFilter(null); - - memChunkLoader.close(); - } - - private Map buildTextTvListMap() { - TVList tvList1 = TVList.newList(TSDataType.TEXT); - tvList1.putBinary(1L, new Binary(BINARY_STR, TSFileConfig.STRING_CHARSET)); - tvList1.putBinary(2L, new Binary(BINARY_STR, TSFileConfig.STRING_CHARSET)); - TVList tvList2 = TVList.newList(TSDataType.TEXT); - tvList2.putBinary(1L, new Binary(BINARY_STR, TSFileConfig.STRING_CHARSET)); - Map tvListMap = new LinkedHashMap<>(); - tvListMap.put(tvList1, 2); - tvListMap.put(tvList2, 1); - return tvListMap; - } -} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReaderTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReaderTest.java deleted file mode 100644 index 689c0671bc305..0000000000000 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/chunk/MemPageReaderTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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.storageengine.dataregion.read.reader.chunk; - -import org.apache.tsfile.enums.TSDataType; -import org.apache.tsfile.file.metadata.ChunkMetadata; -import org.apache.tsfile.file.metadata.statistics.Statistics; -import org.apache.tsfile.read.common.block.TsBlock; -import org.apache.tsfile.read.common.block.TsBlockBuilder; -import org.apache.tsfile.read.filter.factory.TimeFilterApi; -import org.apache.tsfile.read.filter.factory.ValueFilterApi; -import org.apache.tsfile.read.reader.IPageReader; -import org.apache.tsfile.read.reader.series.PaginationController; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.Collections; -import java.util.Optional; -import java.util.function.Supplier; - -import static org.apache.tsfile.read.filter.factory.ValueFilterApi.DEFAULT_MEASUREMENT_INDEX; - -public class MemPageReaderTest { - - private static final TsBlock tsBlock; - private static final ChunkMetadata chunkMetadata = Mockito.mock(ChunkMetadata.class); - - static { - TsBlockBuilder tsBlockBuilder = new TsBlockBuilder(Collections.singletonList(TSDataType.INT32)); - Statistics statistics = Statistics.getStatsByType(TSDataType.INT32); - - for (int i = 0; i < 100; i++) { - tsBlockBuilder.getTimeColumnBuilder().writeLong(i); - tsBlockBuilder.getValueColumnBuilders()[0].writeInt(i); - tsBlockBuilder.declarePosition(); - statistics.update(i, i); - } - - tsBlock = tsBlockBuilder.build(); - Mockito.when(chunkMetadata.getTimeStatistics()).thenReturn(statistics); - Mockito.when(chunkMetadata.getMeasurementStatistics(0)).thenReturn(Optional.of(statistics)); - Mockito.when(chunkMetadata.getDataType()).thenReturn(TSDataType.INT32); - } - - private MemPageReader generatePageReader() { - Supplier tsBlockSupplier = () -> tsBlock; - return new MemPageReader( - tsBlockSupplier, - 0, - chunkMetadata.getDataType(), - chunkMetadata.getMeasurementUid(), - null, - null); - } - - @Test - public void testNullFilter() throws IOException { - IPageReader pageReader = generatePageReader(); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(100, tsBlock.getPositionCount()); - } - - @Test - public void testNullFilterAndLimitOffset() throws IOException { - IPageReader pageReader = generatePageReader(); - pageReader.setLimitOffset(new PaginationController(10, 10)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(10, tsBlock.getPositionCount()); - Assert.assertEquals(10, tsBlock.getTimeByIndex(0)); - Assert.assertEquals(19, tsBlock.getTimeByIndex(9)); - } - - @Test - public void testFilterAllSatisfy() throws IOException { - IPageReader pageReader = generatePageReader(); - pageReader.addRecordFilter(TimeFilterApi.gtEq(0)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(100, tsBlock.getPositionCount()); - } - - @Test - public void testFilterAllSatisfyAndLimitOffset() throws IOException { - IPageReader pageReader = generatePageReader(); - pageReader.addRecordFilter(TimeFilterApi.gtEq(0)); - pageReader.setLimitOffset(new PaginationController(10, 10)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(10, tsBlock.getPositionCount()); - Assert.assertEquals(10, tsBlock.getTimeByIndex(0)); - Assert.assertEquals(19, tsBlock.getTimeByIndex(9)); - } - - @Test - public void testFilter() throws IOException { - IPageReader pageReader = generatePageReader(); - pageReader.addRecordFilter(TimeFilterApi.gtEq(50)); - pageReader.addRecordFilter(ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(30, tsBlock.getPositionCount()); - } - - @Test - public void testFilterAndLimitOffset() throws IOException { - IPageReader pageReader = generatePageReader(); - pageReader.addRecordFilter(TimeFilterApi.gtEq(50)); - pageReader.addRecordFilter(ValueFilterApi.lt(DEFAULT_MEASUREMENT_INDEX, 80, TSDataType.INT32)); - pageReader.setLimitOffset(new PaginationController(10, 10)); - - TsBlock tsBlock = pageReader.getAllSatisfiedData(); - - Assert.assertEquals(10, tsBlock.getPositionCount()); - Assert.assertEquals(60, tsBlock.getTimeByIndex(0)); - Assert.assertEquals(69, tsBlock.getTimeByIndex(9)); - } -} diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/series/AlignedSingleColumnSeriesScanLimitOffsetPushDownTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/series/AlignedSingleColumnSeriesScanLimitOffsetPushDownTest.java index 44e7b87d90350..8a37cfe99f311 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/series/AlignedSingleColumnSeriesScanLimitOffsetPushDownTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/series/AlignedSingleColumnSeriesScanLimitOffsetPushDownTest.java @@ -68,28 +68,22 @@ private AlignedSeriesScanUtil getAlignedSingleColumnSeriesScanUtil(long offset) public void testSkipFile() throws IllegalPathException, IOException { AlignedSeriesScanUtil seriesScanUtil = getAlignedSingleColumnSeriesScanUtil(20); - // File 1 skipped - // File 2 + // File 1 skipped (10 points) + // File 2 skipped (6 points via single selected column statistics) + // File 3 (10 points, skips remaining 4 points) SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); Assert.assertTrue(seriesScanUtil.hasNextPage()); TsBlock tsBlock = seriesScanUtil.nextPage(); - Assert.assertEquals(0, tsBlock.getPositionCount()); - - Assert.assertFalse(seriesScanUtil.hasNextPage()); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); - - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); - Assert.assertTrue(seriesScanUtil.hasNextPage()); - - tsBlock = seriesScanUtil.nextPage(); Assert.assertEquals(5, tsBlock.getPositionCount()); long expectedTime = 24; for (int i = 0, size = tsBlock.getPositionCount(); i < size; i++) { Assert.assertEquals(expectedTime++, tsBlock.getTimeByIndex(i)); } + Assert.assertFalse(seriesScanUtil.hasNextPage()); + SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); + SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, false); } @Test @@ -97,17 +91,7 @@ public void testSkipChunk() throws IllegalPathException, IOException { AlignedSeriesScanUtil seriesScanUtil = getAlignedSingleColumnSeriesScanUtil(30); // File 1 skipped (10 points) - // File 2 skipped (6 points) - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); - Assert.assertTrue(seriesScanUtil.hasNextPage()); - - TsBlock tsBlock = seriesScanUtil.nextPage(); - Assert.assertEquals(0, tsBlock.getPositionCount()); - - Assert.assertFalse(seriesScanUtil.hasNextPage()); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); - + // File 2 skipped (6 points via single selected column statistics) // File 3 SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); // File 3 Chunk 1 skipped (10 points) @@ -115,7 +99,7 @@ public void testSkipChunk() throws IllegalPathException, IOException { SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); Assert.assertTrue(seriesScanUtil.hasNextPage()); - tsBlock = seriesScanUtil.nextPage(); + TsBlock tsBlock = seriesScanUtil.nextPage(); Assert.assertEquals(2, tsBlock.getPositionCount()); long expectedTime = 34; for (int i = 0, size = tsBlock.getPositionCount(); i < size; i++) { @@ -126,7 +110,7 @@ public void testSkipChunk() throws IllegalPathException, IOException { Assert.assertFalse(seriesScanUtil.hasNextPage()); SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); - // File 3 + // File 4 SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); Assert.assertTrue(seriesScanUtil.hasNextPage()); @@ -147,39 +131,16 @@ public void testSkipPage() throws IllegalPathException, IOException { AlignedSeriesScanUtil seriesScanUtil = getAlignedSingleColumnSeriesScanUtil(45); // File 1 skipped (10 points) - // File 2 skipped (6 points) - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); - Assert.assertTrue(seriesScanUtil.hasNextPage()); - - TsBlock tsBlock = seriesScanUtil.nextPage(); - Assert.assertEquals(0, tsBlock.getPositionCount()); - - Assert.assertFalse(seriesScanUtil.hasNextPage()); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); - - // File 3 - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); - - // File 3 - Chunk 1 skipped (10 points) - // File 3 - Chunk 2 skipped (6 points) - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); - Assert.assertTrue(seriesScanUtil.hasNextPage()); - - tsBlock = seriesScanUtil.nextPage(); - Assert.assertEquals(0, tsBlock.getPositionCount()); - - Assert.assertFalse(seriesScanUtil.hasNextPage()); - SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); - + // File 2 skipped (6 points via single selected column statistics) + // File 3 skipped (16 points via single selected column statistics) // File 4 SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, true); // File 4 - Chunk 1 - Page 1 skipped (10 points) - // File 4 - Chunk 1 - Page 2 (6 points should skip 3 points) + // File 4 - Chunk 1 - Page 2 (6 points should skip 3 points) SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); Assert.assertTrue(seriesScanUtil.hasNextPage()); - tsBlock = seriesScanUtil.nextPage(); + TsBlock tsBlock = seriesScanUtil.nextPage(); Assert.assertEquals(3, tsBlock.getPositionCount()); long expectedTime = 53; for (int i = 0, size = tsBlock.getPositionCount(); i < size; i++) { @@ -187,7 +148,7 @@ public void testSkipPage() throws IllegalPathException, IOException { } Assert.assertFalse(seriesScanUtil.hasNextPage()); - // File 4 - Chunk 1 - Page 2 (remaining 2 points) + // File 4 - Chunk 1 - Page 3 (remaining 2 points) SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, true); Assert.assertTrue(seriesScanUtil.hasNextPage()); @@ -197,5 +158,8 @@ public void testSkipPage() throws IllegalPathException, IOException { for (int i = 0, size = tsBlock.getPositionCount(); i < size; i++) { Assert.assertEquals(expectedTime++, tsBlock.getTimeByIndex(i)); } + Assert.assertFalse(seriesScanUtil.hasNextPage()); + SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextChunk, false); + SeriesReaderTestUtil.assertWithHasNext(seriesScanUtil::hasNextFile, false); } }