diff --git a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppCommonConfig.java b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppCommonConfig.java index 31f26def31815..225e6e3eaa25d 100644 --- a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppCommonConfig.java +++ b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppCommonConfig.java @@ -447,6 +447,12 @@ public CommonConfig setSortBufferSize(long sortBufferSize) { return this; } + @Override + public CommonConfig setLttbBufferSize(long lttbBufferSize) { + setProperty("lttb_buffer_size_in_bytes", String.valueOf(lttbBufferSize)); + return this; + } + @Override public CommonConfig setMaxTsBlockSizeInByte(long maxTsBlockSizeInByte) { setProperty("max_tsblock_size_in_bytes", String.valueOf(maxTsBlockSizeInByte)); diff --git a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppSharedCommonConfig.java b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppSharedCommonConfig.java index da61b00e8b11b..cbde483a4137a 100644 --- a/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppSharedCommonConfig.java +++ b/integration-test/src/main/java/org/apache/iotdb/it/env/cluster/config/MppSharedCommonConfig.java @@ -456,6 +456,13 @@ public CommonConfig setSortBufferSize(long sortBufferSize) { return this; } + @Override + public CommonConfig setLttbBufferSize(long lttbBufferSize) { + dnConfig.setLttbBufferSize(lttbBufferSize); + cnConfig.setLttbBufferSize(lttbBufferSize); + return this; + } + @Override public CommonConfig setMaxTsBlockSizeInByte(long maxTsBlockSizeInByte) { dnConfig.setMaxTsBlockSizeInByte(maxTsBlockSizeInByte); diff --git a/integration-test/src/main/java/org/apache/iotdb/it/env/remote/config/RemoteCommonConfig.java b/integration-test/src/main/java/org/apache/iotdb/it/env/remote/config/RemoteCommonConfig.java index 1eb7757da4ff6..9c7eaa1c404b5 100644 --- a/integration-test/src/main/java/org/apache/iotdb/it/env/remote/config/RemoteCommonConfig.java +++ b/integration-test/src/main/java/org/apache/iotdb/it/env/remote/config/RemoteCommonConfig.java @@ -323,6 +323,11 @@ public CommonConfig setSortBufferSize(long sortBufferSize) { return this; } + @Override + public CommonConfig setLttbBufferSize(long lttbBufferSize) { + return this; + } + @Override public CommonConfig setMaxTsBlockSizeInByte(long maxTsBlockSizeInByte) { return this; diff --git a/integration-test/src/main/java/org/apache/iotdb/itbase/env/CommonConfig.java b/integration-test/src/main/java/org/apache/iotdb/itbase/env/CommonConfig.java index f5324f3610124..0a5cdbd58909c 100644 --- a/integration-test/src/main/java/org/apache/iotdb/itbase/env/CommonConfig.java +++ b/integration-test/src/main/java/org/apache/iotdb/itbase/env/CommonConfig.java @@ -149,6 +149,8 @@ CommonConfig setEnableAutoLeaderBalanceForRatisConsensus( CommonConfig setSortBufferSize(long sortBufferSize); + CommonConfig setLttbBufferSize(long lttbBufferSize); + CommonConfig setMaxTsBlockSizeInByte(long maxTsBlockSizeInByte); CommonConfig setDataRegionPerDataNode(int dataRegionPerDataNode); diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLTTBTableFunctionIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLTTBTableFunctionIT.java new file mode 100644 index 0000000000000..feec9a7961e49 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLTTBTableFunctionIT.java @@ -0,0 +1,639 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.relational.it.db.it; + +import org.apache.iotdb.isession.SessionConfig; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.TableClusterIT; +import org.apache.iotdb.itbase.category.TableLocalStandaloneIT; +import org.apache.iotdb.itbase.env.BaseEnv; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.StringJoiner; + +import static org.apache.iotdb.db.it.utils.TestUtils.tableAssertTestFail; +import static org.apache.iotdb.db.it.utils.TestUtils.tableResultSetEqualTest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +@RunWith(IoTDBTestRunner.class) +@Category({TableLocalStandaloneIT.class, TableClusterIT.class}) +public class IoTDBLTTBTableFunctionIT { + + private static final String DATABASE_NAME = "lttb"; + + @BeforeClass + public static void setUp() throws Exception { + // Four data region groups per database, so a partition can be split across regions and a + // per-fragment LTTB or an unordered merge would produce visibly wrong results. + // + // The IT DataNode gives query operators about 16 MB. LTTB reserves its budget twice and the + // sort above an ORDER BY reserves its own buffer, so the defaults (about 2 MB and 8 MB) make + // one query take about 12 MB. A finished fragment keeps that reservation for about a second, + // and the next query is then rejected with error 719. These tables hold a few dozen points. + EnvFactory.getEnv() + .getConfig() + .getCommonConfig() + .setDataRegionGroupExtensionPolicy("CUSTOM") + .setDefaultDataRegionGroupNumPerDatabase(4) + .setLttbBufferSize(256 * 1024L) + .setSortBufferSize(128 * 1024L); + EnvFactory.getEnv().initClusterEnvironment(); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE DATABASE " + DATABASE_NAME); + statement.execute("USE " + DATABASE_NAME); + statement.execute( + "CREATE TABLE metrics(device STRING TAG, s1 DOUBLE FIELD, s2 DOUBLE FIELD)"); + statement.execute( + "INSERT INTO metrics(time, device, s1, s2) VALUES " + + "(0, 'd1', 0.0, 0.0)," + + "(1, 'd1', 1.0, 0.0)," + + "(2, 'd1', 8.0, null)," + + "(3, 'd1', 2.0, 9.0)," + + "(4, 'd1', 0.0, 1.0)," + + "(5, 'd1', 0.0, 0.0)," + + "(0, 'd2', 0.0, 0.0)," + + "(1, 'd2', null, null)"); + statement.execute( + "CREATE TABLE sparse(device STRING TAG, value DOUBLE FIELD, marker INT32 FIELD)"); + statement.execute( + "INSERT INTO sparse(time, device, value, marker) VALUES " + + "(0, 'd1', 0.0, 1), (1, 'd1', 1.0, 1), (2, 'd1', 2.0, 1)," + + "(3, 'd1', null, 1), (4, 'd1', null, 1), (5, 'd1', null, 1)," + + "(6, 'd1', 0.0, 1), (7, 'd1', 0.0, 1), (8, 'd1', 0.0, 1)"); + statement.execute( + "CREATE TABLE observations(observed_at TIMESTAMP FIELD, value INT32 FIELD)"); + statement.execute( + "INSERT INTO observations(time, observed_at, value) VALUES " + + "(1, 1970-01-01T00:00:00.000+00:00, 10), (2, null, 20)"); + // Two devices share one site tag; both write t = 0 so the partition has a duplicate + // timestamp. + statement.execute("CREATE TABLE shared(site STRING TAG, device STRING TAG, s1 DOUBLE FIELD)"); + statement.execute( + "INSERT INTO shared(time, site, device, s1) VALUES " + + "(0, 'a', 'x1', 1.0), (1, 'a', 'x1', 2.0), (0, 'a', 'x2', 3.0), (1, 'a', 'x2', 4.0)"); + statement.execute("CREATE TABLE integral_values(device STRING TAG, value INT64 FIELD)"); + long baseline = 1L << 60; + long[] deltas = {0, 1, 8, 2, 0, 0}; + for (int i = 0; i < deltas.length; i++) { + statement.execute( + "INSERT INTO integral_values(time, device, value) VALUES (" + + i + + ", 'd1', " + + (baseline + deltas[i]) + + ")"); + } + // Two partitions ('p' and 'q'), eight devices each, interleaved timestamps: the devices of + // one + // partition carry disjoint time ranges, so the partition is ordered once the rows are merged + // and a fragment-local sample would return one sample per region. + statement.execute( + "CREATE TABLE regions(part STRING TAG, device STRING TAG, s1 DOUBLE FIELD)"); + for (int device = 0; device < 8; device++) { + for (int row = 0; row < 4; row++) { + long time = device * 4L + row; + statement.execute( + "INSERT INTO regions(time, part, device, s1) VALUES (" + + time + + ", 'p', 'p" + + device + + "', " + + (time % 7) + + ".0)"); + statement.execute( + "INSERT INTO regions(time, part, device, s1) VALUES (" + + time + + ", 'q', 'q" + + device + + "', " + + (time % 5) + + ".0)"); + } + } + statement.execute("FLUSH"); + } catch (Exception e) { + fail("insertData failed: " + e.getMessage()); + } + } + + @AfterClass + public static void tearDown() throws Exception { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void testSinglePointInHighlyOverlappingTimeWindows() { + tableResultSetEqualTest( + "SELECT CAST(window_start AS INT64) AS start_ms, CAST(window_end AS INT64) AS end_ms, " + + "CAST(s1_time AS INT64) AS sample_ms, s1 FROM LTTB(" + + "DATA => (SELECT time, s1 FROM metrics WHERE device = 'd1' AND time = 0) " + + "ORDER BY time, TIMECOL => 'time', SIZE => 1h, SLIDE => 10ms)", + new String[] {"start_ms", "end_ms", "sample_ms", "s1"}, + new String[] {"-3599990,10,0,0.0,"}, + DATABASE_NAME); + } + + @Test + public void testSparseTailInOverlappingCountWindows() throws SQLException { + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE_NAME); + statement.execute("CREATE TABLE sparse_tail(a DOUBLE FIELD, b DOUBLE FIELD)"); + StringJoiner values = new StringJoiner(","); + for (int t = 0; t < 1000; t++) { + values.add("(" + t + "," + (t < 2 ? Integer.toString(t) : "NULL") + "," + t + ")"); + } + statement.execute("INSERT INTO sparse_tail(time, a, b) VALUES " + values); + } + tableResultSetEqualTest( + "SELECT count(*) AS rows_sampled, count(a) AS a_points, count(b) AS b_points, " + + "max(a_time) AS last_a FROM LTTB(DATA => sparse_tail ORDER BY time, " + + "TIMECOL => 'time', SIZE => 3, SLIDE => 2)", + new String[] {"rows_sampled", "a_points", "b_points", "last_a"}, + new String[] {"502,2,502,1970-01-01T00:00:00.001Z,"}, + DATABASE_NAME); + } + + @Test + public void testTargetCountPreservesEndpointsAndAlignsColumns() { + tableResultSetEqualTest( + "SELECT * FROM LTTB(DATA => metrics PARTITION BY metrics.device ORDER BY metrics.time, " + + "TIMECOL => 'time', N => 3) ORDER BY device, s1_time", + new String[] {"window_index", "device", "s1_time", "s1", "s2_time", "s2"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,1970-01-01T00:00:00.000Z,0.0,", + "0,d1,1970-01-01T00:00:00.002Z,8.0,1970-01-01T00:00:00.003Z,9.0,", + "0,d1,1970-01-01T00:00:00.005Z,0.0,1970-01-01T00:00:00.005Z,0.0,", + "0,d2,1970-01-01T00:00:00.000Z,0.0,1970-01-01T00:00:00.000Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testTargetCountPadsShorterParticipantColumns() { + tableResultSetEqualTest( + "SELECT * FROM LTTB(DATA => (SELECT time, s1, " + + "CASE WHEN time = 3 THEN s2 END AS sparse_value, CAST(NULL AS DOUBLE) AS empty_value " + + "FROM metrics WHERE device = 'd1' AND time <= 3) ORDER BY time, " + + "TIMECOL => 'time', N => 3) ORDER BY s1_time", + new String[] { + "window_index", + "s1_time", + "s1", + "sparse_value_time", + "sparse_value", + "empty_value_time", + "empty_value" + }, + new String[] { + "0,1970-01-01T00:00:00.000Z,0.0,1970-01-01T00:00:00.003Z,9.0,null,null,", + "0,1970-01-01T00:00:00.002Z,8.0,null,null,null,null,", + "0,1970-01-01T00:00:00.003Z,2.0,null,null,null,null," + }, + DATABASE_NAME); + } + + @Test + public void testCountWindowAndTimeWindowOutput() { + tableResultSetEqualTest( + "SELECT * FROM LTTB(DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', SIZE => 2) " + + "ORDER BY window_index", + new String[] {"window_index", "device", "s1_time", "s1"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,", + "0,d1,1970-01-01T00:00:00.001Z,1.0,", + "1,d1,1970-01-01T00:00:00.002Z,8.0,", + "2,d1,1970-01-01T00:00:00.004Z,0.0,", + "2,d1,1970-01-01T00:00:00.005Z,0.0," + }, + DATABASE_NAME); + + tableResultSetEqualTest( + "SELECT * FROM LTTB(DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', SIZE => 2ms, " + + "ORIGIN => 1970-01-01T00:00:00.000+00:00) ORDER BY window_start", + new String[] {"window_start", "window_end", "device", "s1_time", "s1"}, + new String[] { + "1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.002Z,d1,1970-01-01T00:00:00.000Z,0.0,", + "1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.002Z,d1,1970-01-01T00:00:00.001Z,1.0,", + "1970-01-01T00:00:00.002Z,1970-01-01T00:00:00.004Z,d1,1970-01-01T00:00:00.002Z,8.0,", + "1970-01-01T00:00:00.004Z,1970-01-01T00:00:00.006Z,d1,1970-01-01T00:00:00.004Z,0.0,", + "1970-01-01T00:00:00.004Z,1970-01-01T00:00:00.006Z,d1,1970-01-01T00:00:00.005Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testDuplicateTimestampsAreRejectedWith701() { + // the same six d1 rows twice: (0, 1, 2, 3, 4, 5) each occurs twice in one partition + String duplicated = + "SELECT * FROM LTTB(DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1' " + + "UNION ALL SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + String expected = + "701: LTTB does not support duplicate timestamps, but timestamp 0 appears more than once" + + " in the same partition."; + + tableAssertTestFail(duplicated + "N => 3)", expected, DATABASE_NAME); + tableAssertTestFail(duplicated + "SIZE => 2)", expected, DATABASE_NAME); + tableAssertTestFail( + duplicated + "SIZE => 2ms, ORIGIN => 1970-01-01T00:00:00.000+00:00)", + expected, + DATABASE_NAME); + } + + @Test + public void testNullableTimeColumn() { + String query = "SELECT * FROM LTTB(DATA => (SELECT observed_at, value FROM observations"; + String args = ") ORDER BY observed_at, TIMECOL => 'observed_at', "; + for (String mode : new String[] {"N => 3", "SIZE => 2", "SIZE => 2ms"}) { + tableAssertTestFail( + query + args + mode + ")", "701: Time column should never be null", DATABASE_NAME); + } + tableResultSetEqualTest( + query + " WHERE observed_at IS NOT NULL" + args + "N => 3)", + new String[] {"window_index", "value_time", "value"}, + new String[] {"0,1970-01-01T00:00:00.000Z,10,"}, + DATABASE_NAME); + } + + @Test + public void testDuplicateTimestampsInDifferentPartitionsRemainValid() { + // each partition is unique on its own, so the query must succeed and keep both rows + tableResultSetEqualTest( + "SELECT * FROM LTTB(DATA => (SELECT time, device, s1 FROM metrics " + + "WHERE time = 0 AND (device = 'd1' OR device = 'd2')) " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', N => 3) " + + "ORDER BY device", + new String[] {"window_index", "device", "s1_time", "s1"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,", "0,d2,1970-01-01T00:00:00.000Z,0.0,", + }, + DATABASE_NAME); + } + + @Test + public void testWindowSkipsNullBucketForLookahead() { + String data = + "DATA => (SELECT time, device, value FROM sparse) PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + data + "SIZE => 3) ORDER BY window_index", + new String[] {"window_index", "device", "value_time", "value"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,", + "0,d1,1970-01-01T00:00:00.002Z,2.0,", + "2,d1,1970-01-01T00:00:00.006Z,0.0,", + "2,d1,1970-01-01T00:00:00.008Z,0.0," + }, + DATABASE_NAME); + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + data + "SIZE => 3ms) ORDER BY window_start", + new String[] {"window_start", "window_end", "device", "value_time", "value"}, + new String[] { + "1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.003Z,d1,1970-01-01T00:00:00.000Z,0.0,", + "1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.003Z,d1,1970-01-01T00:00:00.002Z,2.0,", + "1970-01-01T00:00:00.006Z,1970-01-01T00:00:00.009Z,d1,1970-01-01T00:00:00.006Z,0.0,", + "1970-01-01T00:00:00.006Z,1970-01-01T00:00:00.009Z,d1,1970-01-01T00:00:00.008Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testNonFiniteValuesAreKeptInShortSeries() { + // three non-NULL input points whose values are NaN/Infinity for N => 3 + String nonFinite = + "SELECT * FROM LTTB(DATA => (SELECT time, device, s1 / 0.0 AS s1 FROM metrics " + + "WHERE device = 'd1' AND time <= 2) " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + + tableResultSetEqualTest( + nonFinite + "N => 3) ORDER BY s1_time", + new String[] {"window_index", "device", "s1_time", "s1"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,NaN,", + "0,d1,1970-01-01T00:00:00.001Z,Infinity,", + "0,d1,1970-01-01T00:00:00.002Z,Infinity,", + }, + DATABASE_NAME); + } + + @Test + public void testInt64SamplingPreservesSmallPeaksAtLargeBaselines() { + String prefix = + "SELECT * FROM LTTB(DATA => integral_values PARTITION BY device ORDER BY time, " + + "TIMECOL => 'time', "; + tableResultSetEqualTest( + prefix + "N => 3) ORDER BY value_time", + new String[] {"window_index", "device", "value_time", "value"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,1152921504606846976,", + "0,d1,1970-01-01T00:00:00.002Z,1152921504606846984,", + "0,d1,1970-01-01T00:00:00.005Z,1152921504606846976," + }, + DATABASE_NAME); + tableResultSetEqualTest( + prefix + "SIZE => 2) ORDER BY window_index", + new String[] {"window_index", "device", "value_time", "value"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,1152921504606846976,", + "0,d1,1970-01-01T00:00:00.001Z,1152921504606846977,", + "1,d1,1970-01-01T00:00:00.002Z,1152921504606846984,", + "2,d1,1970-01-01T00:00:00.004Z,1152921504606846976,", + "2,d1,1970-01-01T00:00:00.005Z,1152921504606846976," + }, + DATABASE_NAME); + } + + @Test + public void testSlideSmallerThanSizeKeepsOneAnchorChain() { + // SIZE => 2, SLIDE => 1: overlapping count windows. F(t0) is reported by the first window and + // L(t5) by the last one, and the windows in between continue the same anchor chain. + String data = + "DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + data + "SIZE => 2, SLIDE => 1) ORDER BY window_index, s1_time", + new String[] {"window_index", "device", "s1_time", "s1"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,", + "0,d1,1970-01-01T00:00:00.001Z,1.0,", + "1,d1,1970-01-01T00:00:00.002Z,8.0,", + "2,d1,1970-01-01T00:00:00.003Z,2.0,", + "3,d1,1970-01-01T00:00:00.003Z,2.0,", + "4,d1,1970-01-01T00:00:00.004Z,0.0,", + "5,d1,1970-01-01T00:00:00.005Z,0.0," + }, + DATABASE_NAME); + // The time-window form with SLIDE < SIZE starts a window one slide before the first point. + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + data + "SIZE => 2ms, SLIDE => 1ms) ORDER BY window_start, s1_time", + new String[] {"window_start", "window_end", "device", "s1_time", "s1"}, + new String[] { + "1969-12-31T23:59:59.999Z,1970-01-01T00:00:00.001Z,d1,1970-01-01T00:00:00.000Z,0.0,", + "1970-01-01T00:00:00.000Z,1970-01-01T00:00:00.002Z,d1,1970-01-01T00:00:00.001Z,1.0,", + "1970-01-01T00:00:00.001Z,1970-01-01T00:00:00.003Z,d1,1970-01-01T00:00:00.002Z,8.0,", + "1970-01-01T00:00:00.002Z,1970-01-01T00:00:00.004Z,d1,1970-01-01T00:00:00.003Z,2.0,", + "1970-01-01T00:00:00.003Z,1970-01-01T00:00:00.005Z,d1,1970-01-01T00:00:00.003Z,2.0,", + "1970-01-01T00:00:00.004Z,1970-01-01T00:00:00.006Z,d1,1970-01-01T00:00:00.004Z,0.0,", + "1970-01-01T00:00:00.005Z,1970-01-01T00:00:00.007Z,d1,1970-01-01T00:00:00.005Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testSlideLargerThanSizeSkipsTheGap() { + // SIZE => 1, SLIDE => 2 keeps only the windows that receive a row: [0,1), [2,3), [4,5). + String data = + "DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + data + "SIZE => 1, SLIDE => 2) ORDER BY window_index, s1_time", + new String[] {"window_index", "device", "s1_time", "s1"}, + new String[] { + "0,d1,1970-01-01T00:00:00.000Z,0.0,", + "1,d1,1970-01-01T00:00:00.002Z,8.0,", + "2,d1,1970-01-01T00:00:00.004Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testTimeWindowWithUnalignedOriginShiftsBoundaries() { + String data = + "DATA => (SELECT time, device, s1 FROM metrics WHERE device = 'd1') " + + "PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + tableResultSetEqualTest( + "SELECT * FROM LTTB(" + + data + + "SIZE => 2ms, ORIGIN => 1970-01-01T00:00:00.001+00:00) " + + "ORDER BY window_start, s1_time", + new String[] {"window_start", "window_end", "device", "s1_time", "s1"}, + new String[] { + "1969-12-31T23:59:59.999Z,1970-01-01T00:00:00.001Z,d1,1970-01-01T00:00:00.000Z,0.0,", + "1970-01-01T00:00:00.001Z,1970-01-01T00:00:00.003Z,d1,1970-01-01T00:00:00.002Z,8.0,", + "1970-01-01T00:00:00.003Z,1970-01-01T00:00:00.005Z,d1,1970-01-01T00:00:00.003Z,2.0,", + "1970-01-01T00:00:00.005Z,1970-01-01T00:00:00.007Z,d1,1970-01-01T00:00:00.005Z,0.0," + }, + DATABASE_NAME); + } + + @Test + public void testInvalidTimeColumnIsRejected() { + tableAssertTestFail( + "SELECT * FROM LTTB(DATA => metrics PARTITION BY device ORDER BY time, " + + "TIMECOL => 's1', N => 3)", + "701: The type of the column [s1] is not as expected.", + DATABASE_NAME); + tableAssertTestFail( + "SELECT * FROM LTTB(DATA => metrics PARTITION BY device ORDER BY time, " + + "TIMECOL => 'missing', N => 3)", + "701: Required column [missing] not found in the source table argument.", + DATABASE_NAME); + } + + @Test + public void testDuplicateTimestampsAcrossDevicesInOnePartitionAreRejected() { + // Both devices are tagged 'shared', so PARTITION BY site puts t = 0 of each device into one + // partition and the duplicate check has to reject it. + tableAssertTestFail( + "SELECT * FROM LTTB(DATA => (SELECT time, site, s1 FROM shared ORDER BY time) " + + "PARTITION BY site ORDER BY time, TIMECOL => 'time', N => 3)", + "701: LTTB does not support duplicate timestamps, but timestamp 0 appears more than once" + + " in the same partition.", + DATABASE_NAME); + } + + @Test + public void testDuplicateTimestampsAcrossDistributedFragmentsAreRejected() throws SQLException { + try (Connection connection = + EnvFactory.getEnv() + .getConnection( + EnvFactory.getEnv().getDataNodeWrapper(0), + SessionConfig.DEFAULT_USER, + SessionConfig.DEFAULT_PASSWORD, + BaseEnv.TABLE_SQL_DIALECT); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE_NAME); + statement.execute( + "CREATE TABLE frag_dup(part STRING TAG, device STRING TAG, s1 DOUBLE FIELD)"); + // The probe rows have unique timestamps in the same time partition as the duplicate pair. + // EXPLAIN identifies each device's actual DataRegion even when all regions use one node. + int firstRegion = -1; + int otherDevice = -1; + for (int device = 0; device < 32; device++) { + statement.execute( + "INSERT INTO frag_dup(time, part, device, s1) VALUES (" + + (device + 1) + + ", 'p', 'f" + + device + + "', 1.0)"); + int region = fragDupDeviceRegion(statement, device); + if (device == 0) { + firstRegion = region; + } else if (region != firstRegion) { + otherDevice = device; + break; + } + } + assertTrue("Expected frag_dup devices in two different DataRegions", otherDevice > 0); + statement.execute( + "INSERT INTO frag_dup(time, part, device, s1) VALUES (0, 'p', 'f0', 1.0), (0, 'p', 'f" + + otherDevice + + "', 2.0)"); + } + String expected = + "701: LTTB does not support duplicate timestamps, but timestamp 0 appears more than once" + + " in the same partition."; + String[] inputs = { + "(SELECT time, part, s1 FROM frag_dup)", + "(SELECT time, part, s1, " + + "row_number() OVER (PARTITION BY part, device ORDER BY time) AS rn FROM frag_dup)", + "(SELECT time, part, s1 FROM SESSION(DATA => frag_dup PARTITION BY (part, device) " + + "ORDER BY time, TIMECOL => 'time', GAP => 1m))" + }; + for (String input : inputs) { + String prefix = + "SELECT * FROM LTTB(DATA => " + + input + + " PARTITION BY part ORDER BY time, TIMECOL => 'time', "; + tableAssertTestFail(prefix + "N => 3)", expected, DATABASE_NAME); + tableAssertTestFail(prefix + "SIZE => 3)", expected, DATABASE_NAME); + tableAssertTestFail( + prefix + "SIZE => 2ms, ORIGIN => 1970-01-01T00:00:00.000+00:00)", + expected, + DATABASE_NAME); + } + } + + private static int fragDupDeviceRegion(Statement statement, int device) throws SQLException { + try (ResultSet rs = + statement.executeQuery( + "EXPLAIN (FORMAT JSON) SELECT time, s1 FROM frag_dup WHERE part = 'p' AND device = 'f" + + device + + "'")) { + assertTrue(rs.next()); + JsonObject node = JsonParser.parseString(rs.getString(1)).getAsJsonObject(); + while (node.has("children") && !node.getAsJsonArray("children").isEmpty()) { + assertEquals( + "Expected a single scan for one device", 1, node.getAsJsonArray("children").size()); + node = node.getAsJsonArray("children").get(0).getAsJsonObject(); + } + return node.getAsJsonObject("properties").get("RegionId").getAsInt(); + } + } + + /** + * A partitioned GroupNode does not make a partition complete within one branch, so LTTB has to + * run once over the partitions merged in order. With four data region groups and a partition + * whose devices carry disjoint time ranges, all three inputs must agree. {@code N => 1000} + * returns every point, so it checks that each partition receives exactly its rows; {@code N => 8} + * samples, so it also catches an LTTB that runs once per region. + */ + @Test + public void testNonDirectScanInputsMatchTheDirectScan() throws SQLException { + for (int n : new int[] {1000, 8}) { + String rest = + " PARTITION BY part ORDER BY time, TIMECOL => 'time', N => " + + n + + ") ORDER BY part, s1_time"; + String direct = + "SELECT window_index, part, s1_time, s1 FROM LTTB(" + + "DATA => (SELECT time, part, s1 FROM regions)" + + rest; + String windowFunctionInput = + "SELECT window_index, part, s1_time, s1 FROM LTTB(" + + "DATA => (SELECT time, part, s1, " + + "row_number() OVER (PARTITION BY part, device ORDER BY time) AS rn FROM regions)" + + rest; + String sessionInput = + "SELECT window_index, part, s1_time, s1 FROM LTTB(" + + "DATA => (SELECT time, part, s1 FROM SESSION(" + + "DATA => regions PARTITION BY (part, device) ORDER BY time, TIMECOL => 'time', " + + "GAP => 1m))" + + rest; + + List expected = queryRows(direct); + // 2 partitions of 32 points each: all of them for N => 1000, 8 each for N => 8. + assertEquals(n == 1000 ? 64 : 16, expected.size()); + assertEquals(expected, queryRows(windowFunctionInput)); + assertEquals(expected, queryRows(sessionInput)); + } + } + + private static List queryRows(String sql) throws SQLException { + List rows = new ArrayList<>(); + try (Connection connection = EnvFactory.getEnv().getTableConnection(); + Statement statement = connection.createStatement()) { + statement.execute("USE " + DATABASE_NAME); + try (ResultSet resultSet = statement.executeQuery(sql)) { + int columnCount = resultSet.getMetaData().getColumnCount(); + while (resultSet.next()) { + StringBuilder row = new StringBuilder(); + for (int i = 1; i <= columnCount; i++) { + row.append(resultSet.getString(i)).append('|'); + } + rows.add(row.toString()); + } + } + } + return rows; + } + + @Test + public void testInvalidParameterCombinations() { + String prefix = + "SELECT * FROM LTTB(DATA => metrics PARTITION BY device ORDER BY time, TIMECOL => 'time', "; + tableAssertTestFail( + "SELECT * FROM LTTB(DATA => metrics PARTITION BY device ORDER BY time, TIMECOL => 'time')", + "701: Exactly one of the N and SIZE arguments must be specified for LTTB.", + DATABASE_NAME); + tableAssertTestFail( + prefix + "N => 3, SIZE => 2)", + "701: Exactly one of the N and SIZE arguments must be specified for LTTB.", + DATABASE_NAME); + tableAssertTestFail( + prefix + "N => 2)", "701: The N argument of LTTB must be at least 3.", DATABASE_NAME); + tableAssertTestFail( + prefix + "N => 3, SLIDE => 2)", + "701: The N argument of LTTB cannot be combined with the SLIDE or ORIGIN arguments.", + DATABASE_NAME); + tableAssertTestFail( + prefix + "SIZE => 2, ORIGIN => 1970-01-01T00:00:00.000+00:00)", + "701: The ORIGIN argument is only supported in time window mode.", + DATABASE_NAME); + } +} diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLoadConfigurationTableIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLoadConfigurationTableIT.java index f573426334087..0c3f413938b4b 100644 --- a/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLoadConfigurationTableIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/db/it/IoTDBLoadConfigurationTableIT.java @@ -119,13 +119,19 @@ public void showConfigurationDisplaysEffectiveValue() throws Exception { // Case 2: a valid value is not rewritten, so display must equal the file value (regression). Map afterValidReload = - appendLinesLoadAndShow(dataNodeId, confPath, "cte_buffer_size_in_bytes=262144"); + appendLinesLoadAndShow( + dataNodeId, + confPath, + "cte_buffer_size_in_bytes=262144", + "lttb_buffer_size_in_bytes=262144"); Assert.assertEquals("262144", afterValidReload.get("cte_buffer_size_in_bytes")); + Assert.assertEquals("262144", afterValidReload.get("lttb_buffer_size_in_bytes")); // Case 3: params whose template default is 0 are always rewritten to a computed default, // so they must never display 0 (this was always wrong, even without a bad file value). Map defaultsReload = appendLinesLoadAndShow(dataNodeId, confPath); assertPositiveNonZero(defaultsReload, "sort_buffer_size_in_bytes"); + assertPositiveNonZero(defaultsReload, "lttb_buffer_size_in_bytes"); assertPositiveNonZero(defaultsReload, "mods_cache_size_limit_per_fi_in_bytes"); } diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java index 1956d81e145ea..f539cdbc65291 100644 --- a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/execution/operator/process/function/TableFunctionOperator.java @@ -29,6 +29,7 @@ import org.apache.iotdb.calc.i18n.CalcMessages; import org.apache.iotdb.calc.plan.planner.CommonOperatorUtils; import org.apache.iotdb.commons.queryengine.execution.MemoryEstimationHelper; +import org.apache.iotdb.commons.queryengine.plan.relational.function.BatchedTableFunctionDataProcessor; import org.apache.iotdb.udf.api.IoTDBLocal; import org.apache.iotdb.udf.api.relational.access.Record; import org.apache.iotdb.udf.api.relational.table.TableFunctionProcessorProvider; @@ -73,8 +74,16 @@ public class TableFunctionOperator extends AbstractOperator implements ProcessOp private final boolean isDeclaredAsPassThrough; private final IoTDBLocal ioTDBLocal; + /** + * Bytes the data processors may buffer internally while a partition is processed. It is resolved + * once from the provider, which also gives the same value to every processor it creates, so the + * reservation and the enforced limit cannot diverge. + */ + private final long estimatedMaxBufferedBytes; + private TableFunctionDataProcessor processor; private PartitionState partitionState; + private Iterator batchedInput; private ListenableFuture isBlocked; private boolean finished = false; @@ -83,6 +92,7 @@ public class TableFunctionOperator extends AbstractOperator implements ProcessOp public TableFunctionOperator( CommonOperatorContext operatorContext, TableFunctionProcessorProvider processorProvider, + long estimatedMaxBufferedBytes, Operator inputOperator, List inputDataTypes, List outputDataTypes, @@ -104,6 +114,7 @@ public TableFunctionOperator( new PartitionRecognizer( partitionChannels, requiredChannels, passThroughChannels, inputDataTypes); this.isDeclaredAsPassThrough = isDeclaredAsPassThrough; + this.estimatedMaxBufferedBytes = estimatedMaxBufferedBytes; this.needPassThrough = properChannelCount != outputDataTypes.size(); this.partitionState = null; this.properBlockBuilder = new TsBlockBuilder(outputDataTypes.subList(0, properChannelCount)); @@ -144,6 +155,9 @@ public TsBlock next() throws Exception { if (retainedTsBlock != null || !resultTsBlocks.isEmpty()) { return getNextResultTsBlock(); } + if (batchedInput != null) { + return processInputBatch(); + } if (partitionState == null) { partitionState = partitionRecognizer.nextState(); } @@ -157,29 +171,25 @@ public TsBlock next() throws Exception { } else { List properColumnBuilders = getProperColumnBuilders(); ColumnBuilder passThroughIndexBuilder = getPassThroughIndexBuilder(); - if (stateType == PartitionState.StateType.FINISHED) { - if (processor != null) { - processor.finish(properColumnBuilders, passThroughIndexBuilder, ioTDBLocal); - } - finished = true; + if (stateType == PartitionState.StateType.FINISHED + || (stateType == PartitionState.StateType.NEW_PARTITION && processor != null)) { + boolean drained = finishPartition(properColumnBuilders, passThroughIndexBuilder); resultTsBlocks.addAll(buildTsBlock(properColumnBuilders, passThroughIndexBuilder)); - partitionCache.clear(); - consumeCurrentPartitionState(); + if (drained) { + partitionCache.clear(); + if (stateType == PartitionState.StateType.FINISHED) { + finished = true; + consumeCurrentPartitionState(); + } else { + destroyProcessor(processor); + processor = null; + } + } return getNextResultTsBlock(); } if (stateType == PartitionState.StateType.NEW_PARTITION) { - if (processor != null) { - // previous partition state has not finished consuming yet - processor.finish(properColumnBuilders, passThroughIndexBuilder, ioTDBLocal); - resultTsBlocks.addAll(buildTsBlock(properColumnBuilders, passThroughIndexBuilder)); - partitionCache.clear(); - destroyProcessor(processor); - processor = null; - return getNextResultTsBlock(); - } else { - processor = processorProvider.getDataProcessor(); - processor.beforeStart(ioTDBLocal); - } + processor = processorProvider.getDataProcessor(); + processor.beforeStart(ioTDBLocal); } // the cached slices are only needed when the output has // columns declared as pass-through. Without them every output column is written by the @@ -188,6 +198,10 @@ public TsBlock next() throws Exception { partitionCache.addSlice(slice); } Iterator recordIterator = slice.getRequiredRecordIterator(requireRecordSnapshot); + if (processor instanceof BatchedTableFunctionDataProcessor) { + batchedInput = recordIterator; + return processInputBatch(); + } while (recordIterator.hasNext()) { processor.process( recordIterator.next(), properColumnBuilders, passThroughIndexBuilder, ioTDBLocal); @@ -215,6 +229,39 @@ private List getProperColumnBuilders() { return Arrays.asList(properBlockBuilder.getValueColumnBuilders()); } + private TsBlock processInputBatch() { + BatchedTableFunctionDataProcessor batched = (BatchedTableFunctionDataProcessor) processor; + List builders = getProperColumnBuilders(); + while (batched.drainOutput(builders, this::isOutputBlockFull) && !isOutputBlockFull()) { + if (!batchedInput.hasNext()) { + batchedInput = null; + consumeCurrentPartitionState(); + break; + } + batched.processInput(batchedInput.next(), builders, ioTDBLocal); + } + resultTsBlocks.addAll(buildTsBlock(builders, null)); + return getNextResultTsBlock(); + } + + private boolean isOutputBlockFull() { + // Positions are declared in buildTsBlock, after the processor finishes writing this batch. + return properBlockBuilder.isFull() + || properBlockBuilder.getColumnBuilder(0).getPositionCount() + >= properBlockBuilder.getMaxTsBlockLineNumber(); + } + + private boolean finishPartition(List builders, ColumnBuilder passThroughIndex) { + if (processor instanceof BatchedTableFunctionDataProcessor) { + return ((BatchedTableFunctionDataProcessor) processor) + .finishBatch(builders, this::isOutputBlockFull); + } + if (processor != null) { + processor.finish(builders, passThroughIndex, ioTDBLocal); + } + return true; + } + private ColumnBuilder getPassThroughIndexBuilder() { return isDeclaredAsPassThrough ? new LongColumnBuilder(null, 1) : null; } @@ -282,6 +329,7 @@ public boolean hasNext() throws Exception { public void close() throws Exception { partitionCache.close(); resultTsBlocks.clear(); + batchedInput = null; resultTsBlock = null; retainedTsBlock = null; inputOperator.close(); @@ -299,7 +347,10 @@ public boolean isFinished() throws Exception { @Override public long calculateMaxPeekMemory() { + // A processor that buffers its input (LTTB) holds up to estimatedMaxBufferedBytes while the + // partition is processed, in addition to the input it reads and the block it builds. return inputOperator.calculateMaxPeekMemory() + + estimatedMaxBufferedBytes + Math.max(maxReturnSize, properBlockBuilder.getRetainedSizeInBytes()); } @@ -310,7 +361,12 @@ public long calculateMaxReturnSize() { @Override public long calculateRetainedSizeAfterCallingNext() { - return inputOperator.calculateRetainedSizeAfterCallingNext(); + // The buffers survive across next() calls until the partition completes, so they belong to the + // retained size as well as the peak. Parents read one or the other (FilterAndProjectOperator + // adds the child's retained size and never reads the child's peak; sinks and LimitOperator + // take the child's peak), so keep both. Sort adds the two together; the LTTB default budget is + // sized so that sum still fits one query thread. + return inputOperator.calculateRetainedSizeAfterCallingNext() + estimatedMaxBufferedBytes; } @Override diff --git a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java index fcfd0c31ef523..affed0ef3e017 100644 --- a/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java +++ b/iotdb-core/calc-commons/src/main/java/org/apache/iotdb/calc/plan/planner/TableOperatorGenerator.java @@ -108,6 +108,7 @@ import org.apache.iotdb.commons.queryengine.plan.relational.function.BoundSignature; import org.apache.iotdb.commons.queryengine.plan.relational.function.FunctionKind; import org.apache.iotdb.commons.queryengine.plan.relational.function.ITableFunctionFactory; +import org.apache.iotdb.commons.queryengine.plan.relational.function.TableFunctionProcessorMemoryBudget; import org.apache.iotdb.commons.queryengine.plan.relational.metadata.ResolvedFunction; import org.apache.iotdb.commons.queryengine.plan.relational.planner.OrderingScheme; import org.apache.iotdb.commons.queryengine.plan.relational.planner.SortOrder; @@ -1684,6 +1685,12 @@ public Operator visitTableFunctionProcessor(TableFunctionProcessorNode node, C c return new TableFunctionOperator( operatorContext, processorProvider, + // The budget is taken from the provider itself, so the operator reserves exactly what the + // processors of this provider enforce. A user-defined function reports nothing. + processorProvider instanceof TableFunctionProcessorMemoryBudget + ? ((TableFunctionProcessorMemoryBudget) processorProvider) + .getEstimatedMaxBufferedBytes() + : 0L, operator, inputDataTypes, outputDataTypes, diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java index 04fe3381b7541..bc012f0100174 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java @@ -1122,6 +1122,15 @@ public void loadProperties(TrimProperties properties) throws BadNodeUrlException commonConfig.setCteBufferSize(cteBufferSizeInBytes); } + // The per-processor buffer budget of the LTTB table function. The budget is reserved in both + // the peak and the retained size, and a sort above LTTB adds those two on top of its own + // buffer. The non-positive default therefore takes one eighth of one query thread's operator + // memory, which keeps 2 * lttb + sort within that thread. Half, which is what + // sort_buffer_size_in_bytes uses, makes the sum larger than the free operator memory on the + // 1C1D integration-test heap and the fragment is rejected with error 719. + loadFixedSizeLimitForQuery( + properties, "lttb_buffer_size_in_bytes", commonConfig::setLttbBufferSize, 8); + // max number of rows for cte materialization int maxRowsInCteBuffer = Integer.parseInt( @@ -1298,12 +1307,23 @@ public void loadProperties(TrimProperties properties) throws BadNodeUrlException private void loadFixedSizeLimitForQuery( TrimProperties properties, String name, LongConsumer setFunction) { + loadFixedSizeLimitForQuery(properties, name, setFunction, 2); + } + + /** + * Resolves a per-fragment byte budget. A non-positive configured value becomes {@code min(32 MiB, + * operator memory / query_thread_count / threadDivisor)}. Sort and the mods cache split one query + * thread's operator memory in two. LTTB splits it in eight: its budget is counted in the peak and + * again in the retained size, and the sort buffer is reserved beside those two. + */ + private void loadFixedSizeLimitForQuery( + TrimProperties properties, String name, LongConsumer setFunction, int threadDivisor) { long defaultValue = Math.min( 32 * 1024 * 1024L, memoryConfig.getOperatorsMemoryManager().getTotalMemorySizeInBytes() / memoryConfig.getQueryThreadCount() - / 2); + / threadDivisor); long size = Long.parseLong(properties.getProperty(name, Long.toString(defaultValue))); if (size <= 0) { size = defaultValue; @@ -2405,6 +2425,14 @@ public synchronized void loadHotModifiedProps(TrimProperties properties) if (cteBufferSizeInBytes > 0) { commonConfig.setCteBufferSize(cteBufferSizeInBytes); } + // The per-processor buffer budget of the LTTB table function. The budget is reserved in both + // the peak and the retained size, and a sort above LTTB adds those two on top of its own + // buffer. The non-positive default therefore takes one eighth of one query thread's operator + // memory, which keeps 2 * lttb + sort within that thread. Half, which is what + // sort_buffer_size_in_bytes uses, makes the sum larger than the free operator memory on the + // 1C1D integration-test heap and the fragment is rejected with error 719. + loadFixedSizeLimitForQuery( + properties, "lttb_buffer_size_in_bytes", commonConfig::setLttbBufferSize, 8); // max number of rows for cte materialization int maxRowsInCteBuffer = Integer.parseInt( @@ -2452,6 +2480,8 @@ public synchronized void loadHotModifiedProps(TrimProperties properties) private void overlayEffectiveConfigurationValues() { ConfigurationFileUtils.updateAppliedProperties( "cte_buffer_size_in_bytes", Long.toString(commonConfig.getCteBufferSize())); + ConfigurationFileUtils.updateAppliedProperties( + "lttb_buffer_size_in_bytes", Long.toString(commonConfig.getLttbBufferSize())); ConfigurationFileUtils.updateAppliedProperties( "max_rows_in_cte_buffer", Integer.toString(commonConfig.getMaxRowsInCteBuffer())); ConfigurationFileUtils.updateAppliedProperties( diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java index ec52a103f8a65..4e69634ddbb1a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java @@ -126,6 +126,7 @@ import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory; import org.apache.iotdb.commons.schema.table.column.TsTableColumnSchema; import org.apache.iotdb.commons.udf.builtin.relational.tvf.FFTTableFunction; +import org.apache.iotdb.commons.udf.builtin.relational.tvf.LTTBTableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.M4TableFunction; import org.apache.iotdb.commons.udf.utils.UDFDataTypeTransformer; import org.apache.iotdb.commons.utils.FileUtils; @@ -138,6 +139,7 @@ import org.apache.iotdb.db.queryengine.execution.warnings.WarningCollector; import org.apache.iotdb.db.queryengine.plan.analyze.AnalyzeUtils; import org.apache.iotdb.db.queryengine.plan.analyze.QueryType; +import org.apache.iotdb.db.queryengine.plan.analyze.TypeProvider; import org.apache.iotdb.db.queryengine.plan.analyze.load.LoadTsFileAnalyzer; import org.apache.iotdb.db.queryengine.plan.analyze.lock.DataNodeSchemaLockManager; import org.apache.iotdb.db.queryengine.plan.analyze.lock.SchemaLockType; @@ -148,6 +150,7 @@ import org.apache.iotdb.db.queryengine.plan.relational.analyzer.tablefunction.TableFunctionInvocationAnalysis; import org.apache.iotdb.db.queryengine.plan.relational.function.tvf.read_tsfile.ReadTsFileTableFunction; import org.apache.iotdb.db.queryengine.plan.relational.metadata.Metadata; +import org.apache.iotdb.db.queryengine.plan.relational.planner.IrTypeAnalyzer; import org.apache.iotdb.db.queryengine.plan.relational.planner.PlannerContext; import org.apache.iotdb.db.queryengine.plan.relational.planner.ScopeAware; import org.apache.iotdb.db.queryengine.plan.relational.planner.TranslationMap; @@ -319,6 +322,8 @@ import static org.apache.iotdb.db.queryengine.plan.relational.sql.util.AstUtil.preOrder; import static org.apache.iotdb.db.queryengine.plan.relational.utils.NodeUtils.getSortItemsFromOrderBy; import static org.apache.tsfile.read.common.type.BooleanType.BOOLEAN; +import static org.apache.tsfile.read.common.type.IntType.INT32; +import static org.apache.tsfile.read.common.type.LongType.INT64; public class StatementAnalyzer { @@ -6074,7 +6079,7 @@ private ArgumentsAnalysis analyzeArguments( ParameterSpecification parameterSpecification = argumentSpecificationsByName.remove(argumentName); ArgumentAnalysis argumentAnalysis = - analyzeArgument(parameterSpecification, argument, scope); + analyzeArgument(functionName, parameterSpecification, argument, scope); passedArguments.put(argumentName, argumentAnalysis.getArgument()); argumentAnalysis.getTableArgumentAnalysis().ifPresent(tableArgumentAnalyses::add); } @@ -6094,7 +6099,7 @@ private ArgumentsAnalysis analyzeArguments( TableFunctionArgument argument = arguments.get(i); ParameterSpecification parameterSpecification = parameterSpecifications.get(i); ArgumentAnalysis argumentAnalysis = - analyzeArgument(parameterSpecification, argument, scope); + analyzeArgument(functionName, parameterSpecification, argument, scope); passedArguments.put(parameterSpecification.getName(), argumentAnalysis.getArgument()); argumentAnalysis.getTableArgumentAnalysis().ifPresent(tableArgumentAnalyses::add); } @@ -6107,6 +6112,7 @@ private ArgumentsAnalysis analyzeArguments( } } tryAppendM4ModeArgument(functionName, arguments, parameterSpecifications, passedArguments); + tryAppendLTTBModeArgument(functionName, arguments, parameterSpecifications, passedArguments); tryAppendFFTInternalArguments( functionName, arguments, parameterSpecifications, passedArguments); return new ArgumentsAnalysis(passedArguments.buildOrThrow(), tableArgumentAnalyses.build()); @@ -6114,6 +6120,7 @@ private ArgumentsAnalysis analyzeArguments( private boolean isPartitionColumnsProvidedByProperSchema(String functionName) { return TableBuiltinTableFunction.M4.getFunctionName().equalsIgnoreCase(functionName) + || TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName) || TableBuiltinTableFunction.LOWPASS.getFunctionName().equalsIgnoreCase(functionName) || TableBuiltinTableFunction.HIGHPASS.getFunctionName().equalsIgnoreCase(functionName) || TableBuiltinTableFunction.XCORR.getFunctionName().equalsIgnoreCase(functionName) @@ -6201,6 +6208,86 @@ && containsTableFunctionArgument( new ScalarArgument(org.apache.iotdb.udf.api.type.Type.BOOLEAN, isTimeWindow)); } + /** + * Resolves the LTTB execution mode from the SQL literals. The mode (target-count vs. time + * window vs. count window) depends on whether {@code SIZE} is a duration literal, which is only + * visible at this level, so it is injected as the internal boolean argument {@link + * LTTBTableFunction#WINDOW_MODE_PARAMETER_NAME}. Parameter-combination checks that only need + * the presence of arguments are also performed here so they fail before analysis. + */ + private void tryAppendLTTBModeArgument( + String functionName, + List arguments, + List parameterSpecifications, + ImmutableMap.Builder passedArguments) { + if (!TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName)) { + return; + } + + Optional nArgument = + findOptionalTableFunctionArgument( + arguments, parameterSpecifications, LTTBTableFunction.N_PARAMETER_NAME); + Optional sizeArgument = + findOptionalTableFunctionArgument( + arguments, parameterSpecifications, LTTBTableFunction.SIZE_PARAMETER_NAME); + Optional slideArgument = + findOptionalTableFunctionArgument( + arguments, parameterSpecifications, LTTBTableFunction.SLIDE_PARAMETER_NAME); + boolean originSpecified = + containsTableFunctionArgument( + arguments, parameterSpecifications, LTTBTableFunction.ORIGIN_PARAMETER_NAME); + + if (nArgument.isPresent() == sizeArgument.isPresent()) { + throw new SemanticException( + CommonMessages + .EXCEPTION_EXACTLY_ONE_OF_THE_N_AND_SIZE_ARGUMENTS_MUST_BE_SPECIFIED_FOR_LTTB_54AF0733); + } + + boolean isTimeWindow = false; + if (nArgument.isPresent()) { + if (slideArgument.isPresent() || originSpecified) { + throw new SemanticException( + CommonMessages + .EXCEPTION_THE_N_ARGUMENT_OF_LTTB_CANNOT_BE_COMBINED_WITH_THE_SLIDE_OR_ORIGIN_ARGUMENTS_C2FF1FE1); + } + } else { + if (!(sizeArgument.get().getValue() instanceof Expression)) { + throw new SemanticException( + String.format( + QueryMessages.EXCEPTION_INVALID_ARGUMENT_ARG_EXPECTED_SCALAR_ARGUMENT_4AD4E32F, + LTTBTableFunction.SIZE_PARAMETER_NAME)); + } + isTimeWindow = sizeArgument.get().getValue() instanceof TimeDurationLiteral; + if (slideArgument.isPresent()) { + if (!(slideArgument.get().getValue() instanceof Expression)) { + throw new SemanticException( + String.format( + QueryMessages.EXCEPTION_INVALID_ARGUMENT_ARG_EXPECTED_SCALAR_ARGUMENT_4AD4E32F, + LTTBTableFunction.SLIDE_PARAMETER_NAME)); + } + boolean isTimeSlide = slideArgument.get().getValue() instanceof TimeDurationLiteral; + if (isTimeWindow != isTimeSlide) { + throw new SemanticException( + QueryMessages + .EXCEPTION_THE_SLIDE_ARGUMENT_MUST_HAVE_THE_SAME_WINDOW_MODE_AS_THE_SIZE_ARGUMENT_419C9844); + } + } + if (!isTimeWindow && originSpecified) { + throw new SemanticException( + QueryMessages + .EXCEPTION_THE_ORIGIN_ARGUMENT_IS_ONLY_SUPPORTED_IN_TIME_WINDOW_MODE_B3F358B9); + } + } + passedArguments.put( + LTTBTableFunction.WINDOW_MODE_PARAMETER_NAME, + new ScalarArgument(org.apache.iotdb.udf.api.type.Type.BOOLEAN, isTimeWindow)); + // Presence, not value: Long.MIN_VALUE is a legal timestamp, so the value alone cannot tell + // an explicit ORIGIN from the injected default. + passedArguments.put( + LTTBTableFunction.ORIGIN_SPECIFIED_PARAMETER_NAME, + new ScalarArgument(org.apache.iotdb.udf.api.type.Type.BOOLEAN, originSpecified)); + } + private boolean containsTableFunctionArgument( List arguments, List parameterSpecifications, @@ -6346,6 +6433,7 @@ private void tryUpdateOrderByForForecast( } private ArgumentAnalysis analyzeArgument( + String functionName, ParameterSpecification parameterSpecification, TableFunctionArgument argument, Optional scope) { @@ -6372,7 +6460,8 @@ private ArgumentAnalysis analyzeArgument( return analyzeTableArgument( (TableFunctionTableArgument) argument.getValue(), (TableParameterSpecification) parameterSpecification, - scope); + scope, + TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName)); } else if (parameterSpecification instanceof ScalarParameterSpecification) { if (!(argument.getValue() instanceof Expression)) { throw new SemanticException( @@ -6383,7 +6472,8 @@ private ArgumentAnalysis analyzeArgument( } return analyzeScalarArgument( (Expression) argument.getValue(), - (ScalarParameterSpecification) parameterSpecification); + (ScalarParameterSpecification) parameterSpecification, + TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName)); } else { throw new IllegalStateException( String.format( @@ -6395,7 +6485,8 @@ private ArgumentAnalysis analyzeArgument( private ArgumentAnalysis analyzeTableArgument( TableFunctionTableArgument tableArgument, TableParameterSpecification argumentSpecification, - Optional scope) { + Optional scope, + boolean useResolvedColumnNames) { List> fieldNames; List fieldTypes; List partitionBy = Collections.emptyList(); @@ -6453,7 +6544,10 @@ private ArgumentAnalysis analyzeTableArgument( if (expression instanceof Identifier) { return ((Identifier) expression).getValue(); } else if (expression instanceof DereferenceExpression) { - return expression.toString(); + return tableArgumentColumnName( + (DereferenceExpression) expression, + argumentScope, + useResolvedColumnNames); } else { throw new IllegalStateException( String.format( @@ -6511,7 +6605,10 @@ private ArgumentAnalysis analyzeTableArgument( if (expression instanceof Identifier) { return ((Identifier) expression).getValue(); } else if (expression instanceof DereferenceExpression) { - return expression.toString(); + return tableArgumentColumnName( + (DereferenceExpression) expression, + argumentScope, + useResolvedColumnNames); } else { throw new IllegalStateException( String.format( @@ -6533,6 +6630,17 @@ private ArgumentAnalysis analyzeTableArgument( Optional.of(analysisBuilder.build())); } + private String tableArgumentColumnName( + DereferenceExpression column, Scope scope, boolean useResolvedColumnNames) { + if (!useResolvedColumnNames) { + return column.toString(); + } + // TableArgument exposes unqualified field names. Resolving the short name also catches + // qualified keys that would otherwise match more than one input column in LTTB. + QualifiedName name = QualifiedName.of(ImmutableList.of(column.getField().get())); + return scope.resolveField(column, name).getField().getName().get(); + } + private static void validateOrderByDirection( OrderByRequirement orderByRequirement, OrderBy orderBy, String argumentName) { if (orderByRequirement == OrderByRequirement.ORDERED) { @@ -6558,23 +6666,55 @@ private static void validateOrderByDirection( } private ArgumentAnalysis analyzeScalarArgument( - Expression expression, ScalarParameterSpecification argumentSpecification) { + Expression expression, ScalarParameterSpecification argumentSpecification, boolean isLttb) { if (expression instanceof TimeDurationLiteral) { + if (isLttb + && LTTBTableFunction.ORIGIN_PARAMETER_NAME.equals(argumentSpecification.getName())) { + throw new SemanticException( + String.format( + DataNodeQueryMessages.INVALID_SCALAR_ARGUMENT_S_EXPECTED_TYPE_S_GOT_S, + argumentSpecification.getName(), + argumentSpecification.getType(), + "DURATION")); + } if (((TimeDurationLiteral) expression).getValue().monthDuration != 0) { throw new SemanticException( DataNodeQueryMessages.SETTING_MONTHLY_INTERVALS_IS_NOT_SUPPORTED); } } // currently, only constant arguments are supported - Object constantValue = - evaluateConstantExpression( - expression, new PlannerContext(metadata, typeManager), sessionContext); + PlannerContext plannerContext = new PlannerContext(metadata, typeManager); + Object constantValue = evaluateConstantExpression(expression, plannerContext, sessionContext); if (constantValue == null) { throw new SemanticException( String.format( DataNodeQueryMessages.THE_ARGUMENT_CANNOT_BE_NULL, argumentSpecification.getName())); } + if (isLttb && argumentSpecification.getType() == org.apache.iotdb.udf.api.type.Type.INT64) { + // TIMESTAMP and INT64 constants share the same Java representation. + Type type = + new IrTypeAnalyzer(plannerContext) + .getType(sessionContext, TypeProvider.empty(), expression); + boolean targetCount = + LTTBTableFunction.N_PARAMETER_NAME.equals(argumentSpecification.getName()); + boolean validType = + expression instanceof TimeDurationLiteral + ? !targetCount + : INT32.equals(type) || INT64.equals(type); + if (!validType) { + throw new SemanticException( + targetCount + ? CommonMessages + .EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_A_POSITIVE_INTEGER_21795D8E + : String.format( + DataNodeQueryMessages.INVALID_SCALAR_ARGUMENT_S_EXPECTED_TYPE_S_GOT_S, + argumentSpecification.getName(), + argumentSpecification.getType(), + type.getDisplayName())); + } + constantValue = ((Number) constantValue).longValue(); + } if (!argumentSpecification.getType().checkObjectType(constantValue)) { if ((argumentSpecification.getType().equals(org.apache.iotdb.udf.api.type.Type.STRING) || argumentSpecification.getType().equals(org.apache.iotdb.udf.api.type.Type.TEXT)) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java index 199ed70de7af5..9938ecedc32f5 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/RelationPlanner.java @@ -1610,6 +1610,7 @@ public RelationPlan visitTableFunctionInvocation(TableFunctionInvocation node, V private boolean needAddPartitionColumn(String functionName) { return !TableBuiltinTableFunction.M4.getFunctionName().equalsIgnoreCase(functionName) + && !TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName) && !TableBuiltinTableFunction.LOWPASS.getFunctionName().equalsIgnoreCase(functionName) && !TableBuiltinTableFunction.HIGHPASS.getFunctionName().equalsIgnoreCase(functionName) && !TableBuiltinTableFunction.XCORR.getFunctionName().equalsIgnoreCase(functionName) diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java index 0b013515f8686..73aca5ad3b035 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/distribute/TableDistributedPlanGenerator.java @@ -3410,9 +3410,10 @@ static boolean canSplitTableFunctionProcessor(TableFunctionProcessorNode node) { // A partitioned GroupNode only guarantees that its children are partitioned, not that one // logical partition lives in one child. SAMPLE has to draw N rows for the whole partition and // DERIVATIVE needs the adjacent pairs crossing fragment boundaries, so neither may run once - // per child. + // per child. LTTB also needs the whole partition to select representative points. String functionName = node.getName(); return !TableBuiltinTableFunction.FFT.getFunctionName().equalsIgnoreCase(functionName) + && !TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(functionName) && !TableBuiltinTableFunction.SAMPLE.getFunctionName().equalsIgnoreCase(functionName) && !TableBuiltinTableFunction.DERIVATIVE.getFunctionName().equalsIgnoreCase(functionName); } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java index 19de1ebd88621..e75ab12285b33 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java @@ -27,6 +27,7 @@ import org.apache.iotdb.commons.exception.SemanticException; import org.apache.iotdb.commons.path.PartialPath; import org.apache.iotdb.commons.queryengine.common.SqlDialect; +import org.apache.iotdb.commons.queryengine.plan.relational.function.TableBuiltinTableFunction; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.AliasedRelation; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.AllColumns; import org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.AllRows; @@ -329,6 +330,7 @@ import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SkipTo.skipToFirst; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SkipTo.skipToLast; import static org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SkipTo.skipToNextRow; +import static org.apache.iotdb.commons.queryengine.plan.relational.type.TypeSignatureTranslator.toSqlType; import static org.apache.iotdb.commons.schema.column.ColumnHeaderConstant.DATA_NODE_ID_TABLE_MODEL; import static org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory.ATTRIBUTE; import static org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory.FIELD; @@ -344,10 +346,12 @@ import static org.apache.iotdb.db.queryengine.plan.relational.sql.ast.AsofJoinOn.constructAsofJoinOn; import static org.apache.iotdb.db.queryengine.plan.relational.sql.util.QueryUtil.selectList; import static org.apache.iotdb.db.queryengine.plan.relational.sql.util.QueryUtil.table; +import static org.apache.tsfile.read.common.type.TimestampType.TIMESTAMP; public class AstBuilder extends RelationalSqlBaseVisitor { private int parameterPosition; + private boolean preserveDateTimeLiteralType; @Nullable private final NodeLocation baseLocation; @@ -2921,9 +2925,20 @@ public Node visitTableFunctionInvocationWithTableKeyWord( @Override public Node visitTableFunctionCall(RelationalSqlParser.TableFunctionCallContext context) { QualifiedName name = getQualifiedName(context.qualifiedName()); - List arguments = - visit(context.tableFunctionArgument(), TableFunctionArgument.class); - + boolean isLttb = + TableBuiltinTableFunction.LTTB.getFunctionName().equalsIgnoreCase(name.toString()); + List arguments = new ArrayList<>(); + boolean previous = preserveDateTimeLiteralType; + try { + for (RelationalSqlParser.TableFunctionArgumentContext argument : + context.tableFunctionArgument()) { + // LTTB distinguishes integer counts from timestamps when it analyzes scalar arguments. + preserveDateTimeLiteralType = isLttb && argument.scalarArgument() != null; + arguments.add((TableFunctionArgument) visit(argument)); + } + } finally { + preserveDateTimeLiteralType = previous; + } return new TableFunctionInvocation(getLocation(context), name, arguments); } @@ -3328,10 +3343,14 @@ public Node visitSpecialDateTimeFunction(RelationalSqlParser.SpecialDateTimeFunc @Override public Node visitDateTimeExpression(RelationalSqlParser.DateTimeExpressionContext ctx) { - return new LongLiteral( - getLocation(ctx), - String.valueOf( - parseDateExpression(ctx.dateExpression(), CommonDateTimeUtils.currentTime()))); + return dateTimeLiteral( + ctx, parseDateExpression(ctx.dateExpression(), CommonDateTimeUtils.currentTime())); + } + + private Node dateTimeLiteral(ParserRuleContext context, long timestamp) { + NodeLocation location = getLocation(context); + LongLiteral epoch = new LongLiteral(location, Long.toString(timestamp)); + return preserveDateTimeLiteralType ? new Cast(location, epoch, toSqlType(TIMESTAMP)) : epoch; } private Long parseDateExpression( @@ -3904,11 +3923,9 @@ public Node visitBooleanLiteral(RelationalSqlParser.BooleanLiteralContext ctx) { @Override public Node visitDatetimeLiteral(RelationalSqlParser.DatetimeLiteralContext ctx) { - return new LongLiteral( - getLocation(ctx), - String.valueOf( - parseDateTimeFormat( - ctx.getChild(0).getText(), CommonDateTimeUtils.currentTime(), zoneId))); + return dateTimeLiteral( + ctx, + parseDateTimeFormat(ctx.getChild(0).getText(), CommonDateTimeUtils.currentTime(), zoneId)); } @Override diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java index 6606db879a830..d010d2689ac02 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/tvf/TableFunctionOperatorTest.java @@ -25,7 +25,11 @@ import org.apache.iotdb.calc.execution.operator.process.function.partition.PartitionState; import org.apache.iotdb.calc.execution.operator.process.function.partition.Slice; import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory; +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNodeId; +import org.apache.iotdb.commons.queryengine.plan.relational.function.BatchedTableFunctionDataProcessor; +import org.apache.iotdb.commons.udf.builtin.relational.tvf.LTTBTableFunction; import org.apache.iotdb.db.queryengine.common.FragmentInstanceId; import org.apache.iotdb.db.queryengine.common.PlanFragmentId; import org.apache.iotdb.db.queryengine.common.QueryId; @@ -33,8 +37,10 @@ import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext; import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceStateMachine; import org.apache.iotdb.db.queryengine.execution.operator.OperatorContext; +import org.apache.iotdb.rpc.TSStatusCode; import org.apache.iotdb.udf.api.IoTDBLocal; import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; import org.apache.iotdb.udf.api.relational.table.TableFunctionProcessorProvider; import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; @@ -50,6 +56,7 @@ import org.junit.Assert; import org.junit.Test; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -61,9 +68,15 @@ import static org.apache.iotdb.calc.plan.planner.CommonOperatorUtils.TIME_COLUMN_TEMPLATE; import static org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext.createFragmentInstanceContext; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class TableFunctionOperatorTest { private static final ExecutorService instanceNotificationExecutor = @@ -371,6 +384,7 @@ private void appendRows( new TableFunctionOperator( operatorContext, provider, + 0L, singleRowChild, Collections.singletonList(TSDataType.INT64), withPassThrough @@ -444,6 +458,7 @@ public void process( new TableFunctionOperator( operatorContext, provider, + 0L, twoPartitionChild, Collections.singletonList(TSDataType.INT64), Collections.singletonList(TSDataType.INT64), @@ -475,6 +490,274 @@ public void process( } } + @Test + public void testLttbDrainsEachPartitionInBoundedBatches() throws Exception { + assertLttbTargetCountBatches(16, 1024); + assertLttbTargetCountBatches(1024 * 1024, 1); + } + + private void assertLttbTargetCountBatches(int maxBytes, int maxRows) throws Exception { + OperatorContext context = createOperatorContext("lttb_partition_batches"); + TSFileConfig config = TSFileDescriptor.getInstance().getConfig(); + int previousSize = config.getMaxTsBlockSizeInBytes(); + int previousRows = config.getMaxTsBlockLineNumber(); + try { + config.setMaxTsBlockSizeInBytes(maxBytes); + config.setMaxTsBlockLineNumber(maxRows); + TableFunctionProcessorProvider lttb = + new LTTBTableFunction() + .getProcessorProvider( + new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, "TARGET_COUNT") + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "STRING") + .addProperty(LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, "INT32") + .addProperty(LTTBTableFunction.N_PARAMETER_NAME, 3L) + .build()); + List processors = new ArrayList<>(); + TableFunctionProcessorProvider provider = + new TableFunctionProcessorProvider() { + @Override + public TableFunctionDataProcessor getDataProcessor() { + BatchedTableFunctionDataProcessor processor = + mock( + BatchedTableFunctionDataProcessor.class, + delegatesTo(lttb.getDataProcessor())); + processors.add(processor); + return processor; + } + }; + List input = + Arrays.asList( + TSDataType.TIMESTAMP, TSDataType.STRING, TSDataType.DOUBLE, TSDataType.INT32); + List output = + Arrays.asList( + TSDataType.INT64, TSDataType.STRING, TSDataType.TIMESTAMP, TSDataType.INT32); + List keys = + Arrays.asList( + D1_BINARY, D1_BINARY, D1_BINARY, D2_BINARY, D2_BINARY, D2_BINARY, D3_BINARY, + D3_BINARY, D5_BINARY, D5_BINARY, D5_BINARY); + long[] timestamps = { + 1717171200000L, + 1719763200000L, + 1722441600000L, + 1725120000000L, + 1725130000000L, + 1725140000000L, + 1722441600000L, + 1722441800000L, + 1722551600000L, + 1722552800000L, + 1722553000000L + }; + int[] values = {60, 60, 61, 62, 62, 63, 63, 64, 64, 65, 65}; + int row = 0; + try (TableFunctionOperator operator = + new TableFunctionOperator( + context, + provider, + 0L, + constructChildOperator(context.getDriverContext()), + input, + output, + 4, + Arrays.asList(0, 1, 3), + Collections.emptyList(), + false, + Collections.singletonList(1), + false, + mock(IoTDBLocal.class))) { + while (!operator.isFinished()) { + operator.isBlocked(); + TsBlock block = operator.next(); + if (block != null) { + assertEquals(1, block.getPositionCount()); + assertEquals(0L, block.getColumn(0).getLong(0)); + assertEquals(keys.get(row), block.getColumn(1).getBinary(0)); + assertEquals(timestamps[row], block.getColumn(2).getLong(0)); + assertEquals(values[row++], block.getColumn(3).getInt(0)); + } + } + } + assertEquals(keys.size(), row); + assertEquals(4, processors.size()); + for (int i = 0; i < processors.size(); i++) { + verify(processors.get(i), times(i == 2 ? 2 : 3)).finishBatch(any(), any()); + } + } finally { + config.setMaxTsBlockSizeInBytes(previousSize); + config.setMaxTsBlockLineNumber(previousRows); + } + } + + @Test + public void testLttbDuplicateTimestampsAcrossInputBlocks() throws Exception { + for (LTTBTableFunction.Mode mode : LTTBTableFunction.Mode.values()) { + SemanticException duplicate = + assertThrows(SemanticException.class, () -> readLttbPartitionsAcrossBlocks(mode, 1)); + assertEquals( + mode.name(), TSStatusCode.SEMANTIC_ERROR.getStatusCode(), duplicate.getErrorCode()); + assertEquals( + mode.name(), + String.format( + CommonMessages + .EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD, + 7L), + duplicate.getMessage()); + assertEquals(mode.name(), Arrays.asList(1, 2), readLttbPartitionsAcrossBlocks(mode, 2)); + } + } + + private List readLttbPartitionsAcrossBlocks( + LTTBTableFunction.Mode mode, int secondPartition) throws Exception { + List input = + Arrays.asList(TSDataType.TIMESTAMP, TSDataType.INT32, TSDataType.INT32); + TsBlockBuilder rows = new TsBlockBuilder(input); + for (int partition : new int[] {1, secondPartition}) { + rows.getColumnBuilder(0).writeLong(7L); + rows.getColumnBuilder(1).writeInt(partition); + rows.getColumnBuilder(2).writeInt(42); + rows.declarePosition(); + } + TsBlock data = rows.build(new RunLengthEncodedColumn(TIME_COLUMN_TEMPLATE, 2)); + MapTableFunctionHandle.Builder handle = + new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, mode.name()) + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "INT32") + .addProperty(LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, "INT32"); + if (mode == LTTBTableFunction.Mode.TARGET_COUNT) { + handle.addProperty(LTTBTableFunction.N_PARAMETER_NAME, 3L); + } else { + handle + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, 2L) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, 2L); + } + List output = new ArrayList<>(); + if (mode == LTTBTableFunction.Mode.TIME_WINDOW) { + handle.addProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME, 0L); + output.add(TSDataType.TIMESTAMP); + output.add(TSDataType.TIMESTAMP); + } else { + output.add(TSDataType.INT64); + } + int partitionChannel = output.size(); + output.addAll(Arrays.asList(TSDataType.INT32, TSDataType.TIMESTAMP, TSDataType.INT32)); + TableFunctionProcessorProvider lttb = + new LTTBTableFunction().getProcessorProvider(handle.build()); + List partitions = new ArrayList<>(); + try (TableFunctionOperator operator = + new TableFunctionOperator( + createOperatorContext("lttb_duplicate_across_blocks"), + lttb, + 0L, + childWithBlocks(Arrays.asList(data.getRegion(0, 1), data.getRegion(1, 1)).iterator()), + input, + output, + output.size(), + Arrays.asList(0, 1, 2), + Collections.emptyList(), + false, + Collections.singletonList(1), + false, + mock(IoTDBLocal.class))) { + while (!operator.isFinished()) { + operator.isBlocked(); + TsBlock block = operator.next(); + if (block != null) { + for (int i = 0; i < block.getPositionCount(); i++) { + partitions.add(block.getColumn(partitionChannel).getInt(i)); + assertEquals(7L, block.getColumn(partitionChannel + 1).getLong(i)); + assertEquals(42, block.getColumn(partitionChannel + 2).getInt(i)); + } + } + } + } + return partitions; + } + + @Test + public void testLttbWindowBatchesDuringInputAndAtPartitionEnd() throws Exception { + OperatorContext context = createOperatorContext("lttb_window_batches"); + List input = + Arrays.asList(TSDataType.TIMESTAMP, TSDataType.INT32, TSDataType.DOUBLE); + TsBlockBuilder rows = new TsBlockBuilder(input); + for (int t = 0; t < 18; t++) { + rows.getColumnBuilder(0).writeLong(t); + rows.getColumnBuilder(1).writeInt(t < 15 ? 1 : 2); + rows.getColumnBuilder(2).writeDouble(t >= 3 && t < 9 ? Double.NaN : t); + rows.declarePosition(); + } + TsBlock data = rows.build(new RunLengthEncodedColumn(TIME_COLUMN_TEMPLATE, 18)); + Iterator blocks = + Arrays.asList(data.getRegion(0, 14), data.getRegion(14, 4)).iterator(); + Operator child = childWithBlocks(blocks); + TableFunctionProcessorProvider provider = + new LTTBTableFunction() + .getProcessorProvider( + new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, "COUNT_WINDOW") + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "INT32") + .addProperty(LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, "DOUBLE") + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, 3L) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, 3L) + .build()); + + TSFileConfig config = TSFileDescriptor.getInstance().getConfig(); + int previousSize = config.getMaxTsBlockSizeInBytes(); + int previousRows = config.getMaxTsBlockLineNumber(); + try { + config.setMaxTsBlockSizeInBytes(1024 * 1024); + config.setMaxTsBlockLineNumber(1); + try (TableFunctionOperator operator = + new TableFunctionOperator( + context, + provider, + 0L, + child, + input, + Arrays.asList( + TSDataType.INT64, TSDataType.INT32, TSDataType.TIMESTAMP, TSDataType.DOUBLE), + 4, + Arrays.asList(0, 1, 2), + Collections.emptyList(), + false, + Collections.singletonList(1), + false, + mock(IoTDBLocal.class)) { + @Override + public TsBlock checkTsBlockSizeAndGetResult() { + // Check the materialized block before AbstractOperator has a chance to split it. + assertEquals(1, resultTsBlock.getPositionCount()); + return super.checkTsBlockSizeAndGetResult(); + } + }) { + // Closing the first finite lookahead after the NaNs releases three pending windows. + // The second partition has just one window and must emit F, its interior pick, then L. + int[] times = {0, 1, 3, 6, 9, 12, 14, 15, 16, 17}; + int output = 0; + while (!operator.isFinished()) { + operator.isBlocked(); + TsBlock block = operator.next(); + if (block == null) { + continue; + } + int t = times[output++]; + if (t <= 6) { + assertTrue( + "Ready windows should drain before reading the next input block", blocks.hasNext()); + } + assertEquals(t < 15 ? t / 3 : 0, block.getColumn(0).getLong(0)); + assertEquals(t < 15 ? 1 : 2, block.getColumn(1).getInt(0)); + assertEquals(t, block.getColumn(2).getLong(0)); + assertEquals(t >= 3 && t < 9 ? Double.NaN : t, block.getColumn(3).getDouble(0), 0.0); + } + assertEquals(times.length, output); + } + } finally { + config.setMaxTsBlockSizeInBytes(previousSize); + config.setMaxTsBlockLineNumber(previousRows); + } + } + @Test public void testCloseReleasesPendingResultState() throws Exception { int originalMaxBlockSize = @@ -516,6 +799,7 @@ public void beforeDestroy() { new TableFunctionOperator( operatorContext, provider, + 0L, child, Collections.singletonList(TSDataType.INT64), // the extra output column is a pass-through column, which makes the operator cache @@ -604,10 +888,61 @@ public long ramBytesUsed() { }; } + /** + * The processor buffers survive until a partition completes, so the operator charges them to both + * the peak and the retained size. FilterAndProjectOperator reserves only the retained size, while + * sinks and LimitOperator reserve only the peak. + */ + @Test + public void testBufferedBytesAreChargedToPeakAndRetainedSize() throws Exception { + long budget = 4096L; + OperatorContext operatorContext = createOperatorContext("lttb_buffer_estimate"); + Operator child = constructLongChildOperator(operatorContext, new long[] {1}); + try (TableFunctionOperator operator = + new TableFunctionOperator( + operatorContext, + new TableFunctionProcessorProvider() { + @Override + public TableFunctionDataProcessor getDataProcessor() { + return new TableFunctionDataProcessor() { + @Override + public void process( + Record input, + List properColumnBuilders, + ColumnBuilder passThroughIndexBuilder) {} + }; + } + }, + budget, + child, + Collections.singletonList(TSDataType.INT64), + Collections.singletonList(TSDataType.INT64), + 1, + Collections.singletonList(0), + Collections.emptyList(), + false, + Collections.emptyList(), + false, + mock(IoTDBLocal.class))) { + assertEquals(budget, operator.calculateRetainedSizeAfterCallingNext()); + // peek = child peak (0) + budget + max(return size, block builder retained) + assertTrue(operator.calculateMaxPeekMemory() >= budget + operator.calculateMaxReturnSize()); + } + } + private Operator constructLongChildOperator(OperatorContext operatorContext, long[] values) { return constructLongChildOperator(operatorContext, values, new AtomicBoolean()); } + private Operator childWithBlocks(Iterator blocks) throws Exception { + Operator child = mock(Operator.class); + when(child.isBlocked()).thenAnswer(call -> Operator.NOT_BLOCKED); + when(child.isFinished()).thenAnswer(call -> !blocks.hasNext()); + when(child.hasNextWithTimer()).thenAnswer(call -> blocks.hasNext()); + when(child.nextWithTimer()).thenAnswer(call -> blocks.next()); + return child; + } + private OperatorContext createOperatorContext(String queryName) { QueryId queryId = new QueryId(queryName); FragmentInstanceId instanceId = diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/TableFunctionTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/TableFunctionTest.java index caff03df4a4b8..ea4df0c18e449 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/TableFunctionTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/TableFunctionTest.java @@ -20,9 +20,14 @@ package org.apache.iotdb.db.queryengine.plan.relational.analyzer; import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; import org.apache.iotdb.commons.queryengine.plan.relational.function.tvf.ForecastTableFunction; import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.JoinNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TableFunctionProcessorNode; +import org.apache.iotdb.commons.queryengine.plan.relational.planner.node.WindowNode; import org.apache.iotdb.commons.udf.builtin.relational.tvf.FFTTableFunction; +import org.apache.iotdb.commons.udf.builtin.relational.tvf.LTTBTableFunction; +import org.apache.iotdb.db.i18n.DataNodeQueryMessages; import org.apache.iotdb.db.queryengine.plan.planner.plan.LogicalQueryPlan; import org.apache.iotdb.db.queryengine.plan.relational.planner.PlanTester; import org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern; @@ -57,6 +62,7 @@ import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.group; import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.join; import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.mergeSort; +import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.node; import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.output; import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.project; import static org.apache.iotdb.db.queryengine.plan.relational.planner.assertions.PlanMatchPattern.sort; @@ -1093,4 +1099,283 @@ public void testM4RejectsDescendingOrderBy() { "The ORDER BY clause of the DATA argument must be in ascending order.", e.getMessage()); } } + + // Aliases use the planner's actual symbol names so the same matcher also resolves them through + // the ExchangeNodes of the distributed plan (which bind symbols to their own names). + private static final ImmutableMap TABLE1_COLUMNS = + ImmutableMap.builder() + .put("time", "time") + .put("tag1_0", "tag1") + .put("tag2_1", "tag2") + .put("tag3_2", "tag3") + .put("attr1_3", "attr1") + .put("attr2_4", "attr2") + .put("s1_5", "s1") + .put("s2_6", "s2") + .put("s3_7", "s3") + .buildOrThrow(); + + private static final String LTTB_DATA_ARGUMENT = + "DATA => table1 PARTITION BY (tag1, tag2, tag3, attr1, attr2) ORDER BY time"; + + private static MapTableFunctionHandle.Builder lttbHandle(String mode) { + return new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, mode) + .addProperty( + LTTBTableFunction.PARTITION_TYPES_PROPERTY, "STRING,STRING,STRING,STRING,STRING") + .addProperty(LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, "INT64,INT64,DOUBLE"); + } + + private static TableFunctionProcessorMatcher.Builder lttbMatcher( + TableFunctionProcessorMatcher.Builder builder, String... windowColumns) { + ImmutableList.Builder properOutputs = ImmutableList.builder(); + properOutputs.add(windowColumns); + properOutputs.add( + "lttb_tag1", + "lttb_tag2", + "lttb_tag3", + "lttb_attr1", + "lttb_attr2", + "lttb_s1_time", + "lttb_s1", + "lttb_s2_time", + "lttb_s2", + "lttb_s3_time", + "lttb_s3"); + return builder + .name("lttb") + .properOutputs(properOutputs.build().toArray(new String[0])) + .requiredSymbols( + "time", "tag1_0", "tag2_1", "tag3_2", "attr1_3", "attr2_4", "s1_5", "s2_6", "s3_7"); + } + + @Test + public void testLTTBTargetCountMode() { + PlanTester planTester = new PlanTester(); + String sql = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', N => 100)"; + LogicalQueryPlan logicalQueryPlan = planTester.createPlan(sql); + PlanMatchPattern tableScan = tableScan("testdb.table1", TABLE1_COLUMNS); + + Consumer tableFunctionMatcher = + builder -> + lttbMatcher(builder, "window_index") + .handle( + lttbHandle("TARGET_COUNT") + .addProperty(LTTBTableFunction.N_PARAMETER_NAME, 100L) + .build()); + + // PARTITION BY several columns plans a GroupNode (a SortNode subclass) below the function + assertPlan( + logicalQueryPlan, anyTree(tableFunctionProcessor(tableFunctionMatcher, group(tableScan)))); + // LTTB is not mergeable: the whole partition is gathered and ordered before the function runs + assertPlan( + planTester.getFragmentPlan(0), + output( + tableFunctionProcessor( + tableFunctionMatcher, mergeSort(exchange(), exchange(), exchange())))); + } + + @Test + public void testLTTBTargetCountRequiresIntegralSqlType() { + String prefix = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', N => "; + assertAnalyzeFails( + prefix + "CAST('2026-01-01T00:00:00.000+00:00' AS TIMESTAMP))", + CommonMessages.EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_A_POSITIVE_INTEGER_21795D8E); + analyzeSQL(prefix + "CAST(4 AS INT32))", TEST_MATADATA, QUERY_CONTEXT); + analyzeSQL(prefix + "CAST(4 AS INT64))", TEST_MATADATA, QUERY_CONTEXT); + } + + @Test + public void testLTTBQualifiedInputColumns() { + String prefix = "SELECT * FROM LTTB(DATA => table1 PARTITION BY ("; + String suffix = ", TIMECOL => 'time', N => 4)"; + analyzeSQL( + prefix + "tag1, tag2, tag3, attr1, attr2) ORDER BY \"table1\".\"time\"" + suffix, + TEST_MATADATA, + QUERY_CONTEXT); + analyzeSQL( + prefix + "\"table1\".\"tag1\", tag2, tag3, attr1, attr2) ORDER BY time" + suffix, + TEST_MATADATA, + QUERY_CONTEXT); + } + + @Test + public void testLTTBDateTimeLiteralsRetainTheirType() { + String prefix = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', "; + String timestamp = "1970-01-01T00:00:00.004+00:00"; + String countError = + CommonMessages.EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_A_POSITIVE_INTEGER_21795D8E; + assertAnalyzeFails(prefix + "N => " + timestamp + ")", countError); + assertAnalyzeFails(prefix + "N => (" + timestamp + " + 1ms))", countError); + for (String argument : ImmutableList.of("SIZE", "SLIDE")) { + String arguments = argument.equals("SIZE") ? "SIZE => " : "SIZE => 4, SLIDE => "; + assertAnalyzeFails( + prefix + arguments + timestamp + ")", + String.format( + DataNodeQueryMessages.INVALID_SCALAR_ARGUMENT_S_EXPECTED_TYPE_S_GOT_S, + argument, + "INT64", + "TIMESTAMP")); + } + analyzeSQL(prefix + "N => CAST(" + timestamp + " AS INT64))", TEST_MATADATA, QUERY_CONTEXT); + analyzeSQL(prefix + "SIZE => 1ms, ORIGIN => " + timestamp + ")", TEST_MATADATA, QUERY_CONTEXT); + } + + @Test + public void testLTTBWindowArgumentsAcceptIntegerCastsAndDurations() { + String prefix = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', "; + analyzeSQL( + prefix + "SIZE => CAST(4 AS INT32), SLIDE => CAST(2 AS INT64))", + TEST_MATADATA, + QUERY_CONTEXT); + analyzeSQL( + prefix + "SIZE => CAST(4 AS INT64), SLIDE => CAST(2 AS INT32))", + TEST_MATADATA, + QUERY_CONTEXT); + analyzeSQL(prefix + "SIZE => 4s, SLIDE => 2s)", TEST_MATADATA, QUERY_CONTEXT); + } + + @Test + public void testLTTBTimeWindowOriginRequiresTimestampInsteadOfDuration() { + String prefix = + "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', SIZE => 2s, ORIGIN => "; + assertAnalyzeFails( + prefix + "1s)", + String.format( + DataNodeQueryMessages.INVALID_SCALAR_ARGUMENT_S_EXPECTED_TYPE_S_GOT_S, + "ORIGIN", + "TIMESTAMP", + "DURATION")); + analyzeSQL(prefix + "CAST(1000 AS TIMESTAMP))", TEST_MATADATA, QUERY_CONTEXT); + } + + @Test + public void testLTTBWindowArgumentsRejectNonIntegralSqlTypes() { + String prefix = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', "; + for (String type : ImmutableList.of("TIMESTAMP", "DOUBLE")) { + String value = "CAST(4 AS " + type + ")"; + for (String argument : ImmutableList.of("SIZE", "SLIDE")) { + String arguments = argument.equals("SIZE") ? "SIZE => " : "SIZE => 4, SLIDE => "; + assertAnalyzeFails( + prefix + arguments + value + ")", + String.format( + DataNodeQueryMessages.INVALID_SCALAR_ARGUMENT_S_EXPECTED_TYPE_S_GOT_S, + argument, + "INT64", + type)); + } + } + } + + @Test + public void testLTTBTimeWindowMode() { + PlanTester planTester = new PlanTester(); + String sql = + "SELECT * FROM LTTB(" + + LTTB_DATA_ARGUMENT + + ", TIMECOL => 'time', SIZE => 1h, SLIDE => 30m, " + + "ORIGIN => 1970-01-01T00:00:00.000+00:00)"; + Consumer tableFunctionMatcher = + builder -> + lttbMatcher(builder, "window_start", "window_end") + .handle( + lttbHandle("TIME_WINDOW") + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, 3600000L) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, 1800000L) + .addProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME, 0L) + .build()); + assertPlan( + planTester.createPlan(sql), + anyTree( + tableFunctionProcessor( + tableFunctionMatcher, group(tableScan("testdb.table1", TABLE1_COLUMNS))))); + } + + @Test + public void testLTTBCountWindowMode() { + PlanTester planTester = new PlanTester(); + String sql = "SELECT * FROM LTTB(" + LTTB_DATA_ARGUMENT + ", TIMECOL => 'time', SIZE => 5)"; + Consumer tableFunctionMatcher = + builder -> + lttbMatcher(builder, "window_index") + .handle( + lttbHandle("COUNT_WINDOW") + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, 5L) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, 5L) + .build()); + assertPlan( + planTester.createPlan(sql), + anyTree( + tableFunctionProcessor( + tableFunctionMatcher, group(tableScan("testdb.table1", TABLE1_COLUMNS))))); + } + + /** + * A window partitioned by every tag is planned per region, so each branch below the LTTB ends in + * a GroupNode. The branch therefore does not hold a complete partition, and the function has to + * run once over the branches merged in order: a CollectNode would interleave the partitions of + * different regions, and an LTTB inside the region fragments would sample each region on its own. + */ + @Test + public void testLTTBOverWindowFunctionInputIsMergedInOrder() { + PlanTester planTester = new PlanTester(); + String sql = + "SELECT * FROM LTTB(DATA => (SELECT time, tag3, s1, row_number() OVER " + + "(PARTITION BY tag3, tag1, tag2 ORDER BY time) AS rn FROM table1 WHERE time < 100) " + + "PARTITION BY tag3 ORDER BY time, TIMECOL => 'time', N => 4)"; + planTester.createPlan(sql); + + /* + * fragment 0: Output - TableFunctionProcessor (lttb) - MergeSort - Exchange, Exchange + * fragments 1-2: Group - Project - Window - DeviceTableScan (one region each) + */ + assertPlan( + planTester.getFragmentPlan(0), + output(node(TableFunctionProcessorNode.class, mergeSort(exchange(), exchange())))); + assertPlan( + planTester.getFragmentPlan(1), + group(project(node(WindowNode.class, tableScan("testdb.table1"))))); + assertPlan( + planTester.getFragmentPlan(2), + group(project(node(WindowNode.class, tableScan("testdb.table1"))))); + } + + @Test + public void testLTTBRejectsInvalidArguments() { + String data = "DATA => (SELECT time, tag1, s3 FROM table1) PARTITION BY tag1 ORDER BY time"; + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time')", + "Exactly one of the N and SIZE arguments must be specified for LTTB."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time', N => 10, SIZE => 1h)", + "Exactly one of the N and SIZE arguments must be specified for LTTB."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time', N => 2)", + "The N argument of LTTB must be at least 3."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time', N => 1h)", + "The N argument of LTTB must be a positive integer."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + + data + + ", TIMECOL => 'time', N => 10, ORIGIN => 1970-01-01T00:00:00.000+00:00)", + "The N argument of LTTB cannot be combined with the SLIDE or ORIGIN arguments."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time', SLIDE => 1h)", + "Exactly one of the N and SIZE arguments must be specified for LTTB."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + + data + + ", TIMECOL => 'time', SIZE => 5, ORIGIN => 1970-01-01T00:00:00.000+00:00)", + "The ORIGIN argument is only supported in time window mode."); + assertAnalyzeFails( + "SELECT * FROM LTTB(" + data + ", TIMECOL => 'time', SIZE => 1h, SLIDE => 5)", + "The SLIDE argument must have the same window mode as the SIZE argument."); + assertAnalyzeFails( + "SELECT * FROM LTTB(DATA => (SELECT time, tag1, s3 FROM table1) PARTITION BY tag1 ORDER BY time DESC, TIMECOL => 'time', N => 10)", + "The ORDER BY clause of the DATA argument must be in ascending order."); + assertAnalyzeFails( + "SELECT * FROM LTTB(DATA => (SELECT time, tag1, attr1, s3 FROM table1) PARTITION BY tag1 ORDER BY time, TIMECOL => 'time', N => 10)", + "Only column with double, float, int32, int64 can be calculated by the function, attr1 is the STRING."); + } } diff --git a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template index c5117185e7040..96847aa491939 100644 --- a/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template +++ b/iotdb-core/node-commons/src/assembly/resources/conf/iotdb-system.properties.template @@ -1347,6 +1347,16 @@ sort_buffer_size_in_bytes=0 # Unit: bytes cte_buffer_size_in_bytes=131072 +# The per-processor buffer budget of the LTTB table function. It is charged to both the peak and the retained size of +# every fragment that runs LTTB, and a sort above it reserves its own buffer too. If lttb_buffer_size_in_bytes <= 0 a +# default value is used, default value = min(32MB, memory for query operators / query_thread_count / 8), so those three +# reservations fit one query thread. Raise it for queries with very large partitions or many overlapping windows. +# effectiveMode: hot_reload +# Datatype: long +# Privilege: SYSTEM +# Unit: bytes +lttb_buffer_size_in_bytes=0 + # Max rows for CTE materialization # effectiveMode: hot_reload diff --git a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/CommonMessages.java b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/CommonMessages.java index a3982df1e36f4..d9194d322f17d 100644 --- a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/CommonMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/CommonMessages.java @@ -350,6 +350,37 @@ private CommonMessages() {} EXCEPTION_XCORR_REQUIRES_EXACTLY_TWO_CALCULATION_COLUMNS_BUT_FOUND_ARG_2FF8EB0C = "XCorr requires exactly two calculation columns, but found %d."; public static final String EXCEPTION_COLUMN_LACK_OF_NAME = "the column in table lack of the name"; + public static final String + EXCEPTION_EXACTLY_ONE_OF_THE_N_AND_SIZE_ARGUMENTS_MUST_BE_SPECIFIED_FOR_LTTB_54AF0733 = + "Exactly one of the N and SIZE arguments must be specified for LTTB."; + public static final String EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_AT_LEAST_3_29CE2B87 = + "The N argument of LTTB must be at least 3."; + public static final String + EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_A_POSITIVE_INTEGER_21795D8E = + "The N argument of LTTB must be a positive integer."; + public static final String + EXCEPTION_THE_N_ARGUMENT_OF_LTTB_CANNOT_BE_COMBINED_WITH_THE_SLIDE_OR_ORIGIN_ARGUMENTS_C2FF1FE1 = + "The N argument of LTTB cannot be combined with the SLIDE or ORIGIN arguments."; + public static final String + EXCEPTION_INVALID_SCALAR_ARGUMENT_SIZE_SHOULD_BE_A_POSITIVE_VALUE_3ECF76E0 = + "Invalid scalar argument SIZE, should be a positive value"; + public static final String + EXCEPTION_LTTB_BUFFERS_AT_MOST_ARG_ELIGIBLE_POINTS_PER_COLUMN_IN_ONE_PARTITION_OR_WINDOW_4C746D82 = + "LTTB buffers at most %d eligible points per column in one partition or window."; + public static final String + EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD = + "LTTB does not support duplicate timestamps, but timestamp %s appears more than once in" + + " the same partition."; + public static final String EXCEPTION_UNSUPPORTED_LTTB_VALUE_TYPE_ARG_3E60F6FE = + "Unsupported LTTB value type: %s"; + public static final String + EXCEPTION_LTTB_COUNT_WINDOW_BOUNDARIES_EXCEED_THE_INT64_RANGE_5BC980CA = + "LTTB count window boundaries exceed the INT64 range."; + public static final String EXCEPTION_LTTB_WINDOW_BOUNDARIES_EXCEED_THE_TIMESTAMP_RANGE_7C0FC7E2 = + "LTTB window boundaries exceed the TIMESTAMP range."; + public static final String + EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D = + "LTTB buffers exceed lttb_buffer_size_in_bytes (%d bytes)."; public static final String EXCEPTION_SNAPSHOT_BUFFER_SIZE_MUST_NOT_EXCEED_ARG_BYTES_BUT_WAS_ARG_D1DA6F7E = "Snapshot buffer size must not exceed %d bytes, but was %d."; diff --git a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/CommonMessages.java b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/CommonMessages.java index f690013c58a0b..6a77650844c40 100644 --- a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/CommonMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/CommonMessages.java @@ -237,6 +237,36 @@ private CommonMessages() {} EXCEPTION_XCORR_REQUIRES_EXACTLY_TWO_CALCULATION_COLUMNS_BUT_FOUND_ARG_2FF8EB0C = "XCorr 要求必须正好有两列计算列,但实际找到 %d 列。"; public static final String EXCEPTION_COLUMN_LACK_OF_NAME = "表参数中列缺少名字"; + public static final String + EXCEPTION_EXACTLY_ONE_OF_THE_N_AND_SIZE_ARGUMENTS_MUST_BE_SPECIFIED_FOR_LTTB_54AF0733 = + "LTTB 必须且只能指定 N 和 SIZE 参数中的一个。"; + public static final String EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_AT_LEAST_3_29CE2B87 = + "LTTB 的 N 参数必须至少为 3。"; + public static final String + EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_A_POSITIVE_INTEGER_21795D8E = + "LTTB 的 N 参数必须是正整数。"; + public static final String + EXCEPTION_THE_N_ARGUMENT_OF_LTTB_CANNOT_BE_COMBINED_WITH_THE_SLIDE_OR_ORIGIN_ARGUMENTS_C2FF1FE1 = + "LTTB 的 N 参数不能与 SLIDE 或 ORIGIN 参数同时使用。"; + public static final String + EXCEPTION_INVALID_SCALAR_ARGUMENT_SIZE_SHOULD_BE_A_POSITIVE_VALUE_3ECF76E0 = + "无效的标量参数 SIZE,应为正数"; + public static final String + EXCEPTION_LTTB_BUFFERS_AT_MOST_ARG_ELIGIBLE_POINTS_PER_COLUMN_IN_ONE_PARTITION_OR_WINDOW_4C746D82 = + "LTTB 在单个分区或窗口内每列最多缓存 %d 个有效点。"; + public static final String + EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD = + "LTTB 不支持重复的时间戳,但时间戳 %s 在同一分区中出现了多次。"; + public static final String EXCEPTION_UNSUPPORTED_LTTB_VALUE_TYPE_ARG_3E60F6FE = + "不支持的 LTTB 值类型:%s"; + public static final String + EXCEPTION_LTTB_COUNT_WINDOW_BOUNDARIES_EXCEED_THE_INT64_RANGE_5BC980CA = + "LTTB 计数窗口边界超出 INT64 的取值范围。"; + public static final String EXCEPTION_LTTB_WINDOW_BOUNDARIES_EXCEED_THE_TIMESTAMP_RANGE_7C0FC7E2 = + "LTTB 窗口边界超出 TIMESTAMP 的取值范围。"; + public static final String + EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D = + "LTTB 缓冲区超过 lttb_buffer_size_in_bytes 限制(%d 字节)。"; public static final String EXCEPTION_SNAPSHOT_BUFFER_SIZE_MUST_NOT_EXCEED_ARG_BYTES_BUT_WAS_ARG_D1DA6F7E = "快照缓冲区大小不得超过 %d 字节,但实际为 %d。"; diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java index d2a92a958f46e..01b871b711d18 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/conf/CommonConfig.java @@ -579,6 +579,15 @@ public class CommonConfig { /** Max number of rows for cte materialization */ private int maxRowsInCteBuffer = 1000; + /** + * The per-processor memory budget of the LTTB table function. The shipped value is {@code 0}, + * which the DataNode resolves to {@code min(32 MiB, operator memory / query_thread_count / 8)}. + * The divisor is 8 rather than the 2 used by {@link #sortBufferSize}: the LTTB budget is reserved + * twice and the sort budget once, and that sum has to fit one query thread. This initial value + * matches {@link #sortBufferSize}. + */ + private long lttbBufferSize = 32 * 1024 * 1024L; + CommonConfig() { // Empty constructor } @@ -3370,4 +3379,12 @@ public void setMaxRowsInCteBuffer(int maxRowsInCteBuffer) { public int getMaxRowsInCteBuffer() { return maxRowsInCteBuffer; } + + public void setLttbBufferSize(long lttbBufferSize) { + this.lttbBufferSize = lttbBufferSize; + } + + public long getLttbBufferSize() { + return lttbBufferSize; + } } diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/BatchedTableFunctionDataProcessor.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/BatchedTableFunctionDataProcessor.java new file mode 100644 index 0000000000000..de4361928bcd1 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/BatchedTableFunctionDataProcessor.java @@ -0,0 +1,56 @@ +/* + * 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.commons.queryengine.plan.relational.function; + +import org.apache.iotdb.udf.api.IoTDBLocal; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; + +import org.apache.tsfile.block.column.ColumnBuilder; + +import java.util.List; +import java.util.function.BooleanSupplier; + +/** A built-in processor whose proper output can span blocks even for a single input row. */ +public interface BatchedTableFunctionDataProcessor extends TableFunctionDataProcessor { + + /** + * Accepts a row. The caller keeps the record valid until drainOutput returns true, before + * advancing the input iterator or finishing the partition. + */ + default void processInput(Record input, List builders, IoTDBLocal local) { + process(input, builders, null, local); + } + + /** Writes ready rows until the block is full. Returns true when more input can be accepted. */ + default boolean drainOutput(List builders, BooleanSupplier blockFull) { + return true; + } + + /** + * Writes until the block is full or output is exhausted. Returns true when all rows are written. + */ + boolean finishBatch(List builders, BooleanSupplier blockFull); + + @Override + default void finish(List builders, ColumnBuilder passThroughIndexBuilder) { + finishBatch(builders, () -> false); + } +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableBuiltinTableFunction.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableBuiltinTableFunction.java index b263e3c5ab651..181fd130d6d07 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableBuiltinTableFunction.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableBuiltinTableFunction.java @@ -29,6 +29,7 @@ import org.apache.iotdb.commons.udf.builtin.relational.tvf.FFTTableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.HOPTableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.HighPassTableFunction; +import org.apache.iotdb.commons.udf.builtin.relational.tvf.LTTBTableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.LowPassTableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.M4TableFunction; import org.apache.iotdb.commons.udf.builtin.relational.tvf.SampleTableFunction; @@ -52,6 +53,7 @@ public enum TableBuiltinTableFunction { VARIATION("variation", true), CAPACITY("capacity", true), M4("m4"), + LTTB("lttb"), FFT("fft"), FORECAST("forecast"), PATTERN_MATCH("pattern_match"), @@ -125,6 +127,8 @@ public static TableFunction getBuiltinTableFunction(String functionName) { return new CapacityTableFunction(); case "m4": return new M4TableFunction(); + case "lttb": + return new LTTBTableFunction(); case "fft": return new FFTTableFunction(); case "forecast": diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableFunctionProcessorMemoryBudget.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableFunctionProcessorMemoryBudget.java new file mode 100644 index 0000000000000..62618fb3f76de --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/plan/relational/function/TableFunctionProcessorMemoryBudget.java @@ -0,0 +1,39 @@ +/* + * 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.commons.queryengine.plan.relational.function; + +/** + * Engine-internal memory accounting for the processors of a built-in table function. + * + *

It is deliberately kept out of {@code udf-api}: a user-defined table function does not declare + * any buffered bytes, and the engine treats every provider that does not implement this interface + * as keeping no state across calls. The value is resolved once per provider, and the processors + * created by that provider must enforce exactly the same limit, so the estimate the operator + * reserves and the limit the processors apply cannot diverge, not even when the configuration is + * hot-reloaded while a query runs. + */ +public interface TableFunctionProcessorMemoryBudget { + + /** + * Bytes the processors of this provider may buffer internally while one partition is processed, + * above what {@code process} returns. + */ + long getEstimatedMaxBufferedBytes(); +} diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunction.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunction.java new file mode 100644 index 0000000000000..187c33566c615 --- /dev/null +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunction.java @@ -0,0 +1,2098 @@ +/* + * 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.commons.udf.builtin.relational.tvf; + +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; +import org.apache.iotdb.commons.i18n.QueryMessages; +import org.apache.iotdb.commons.queryengine.plan.relational.function.BatchedTableFunctionDataProcessor; +import org.apache.iotdb.commons.queryengine.plan.relational.function.TableFunctionProcessorMemoryBudget; +import org.apache.iotdb.udf.api.IoTDBLocal; +import org.apache.iotdb.udf.api.exception.UDFException; +import org.apache.iotdb.udf.api.relational.TableFunction; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.TableFunctionAnalysis; +import org.apache.iotdb.udf.api.relational.table.TableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.TableFunctionProcessorProvider; +import org.apache.iotdb.udf.api.relational.table.argument.Argument; +import org.apache.iotdb.udf.api.relational.table.argument.DescribedSchema; +import org.apache.iotdb.udf.api.relational.table.argument.ScalarArgument; +import org.apache.iotdb.udf.api.relational.table.argument.TableArgument; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; +import org.apache.iotdb.udf.api.relational.table.specification.ParameterSpecification; +import org.apache.iotdb.udf.api.relational.table.specification.ScalarParameterSpecification; +import org.apache.iotdb.udf.api.relational.table.specification.TableParameterSpecification; +import org.apache.iotdb.udf.api.type.Type; + +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.utils.RamUsageEstimator; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BooleanSupplier; + +import static org.apache.iotdb.udf.api.relational.table.argument.ScalarArgumentChecker.POSITIVE_LONG_CHECKER; + +/** + * Largest-Triangle-Three-Buckets (LTTB) downsampling as a built-in Table Model table function. + * + *

The function shares its table-argument conventions with {@link M4TableFunction}: {@code DATA} + * has set semantics, {@code TIMECOL} names the {@code TIMESTAMP} ordering column, partition columns + * are echoed into the proper output, and every other numeric column is a participant column that is + * downsampled independently. Two mutually exclusive execution modes exist: + * + *

    + *
  • Target-count mode ({@code N}): the whole partition is buffered and the standard LTTB + * algorithm reduces each participant column to exactly {@code N} points (or all points when + * the column has no more than {@code N} eligible points). The output uses a fixed {@code + * window_index = 0}. + *
  • Window/bucket mode ({@code SIZE}, optional {@code SLIDE}/{@code ORIGIN}): windows + * are built exactly like M4 (time windows for duration literals, count windows for integers), + * but {@code SIZE} defines a bucket rather than the input range of a separate standard LTTB + * invocation. The result is standard LTTB whose buckets are the windows: + *
      + *
    • Per partition and participant column, the first eligible point {@code F} and the last + * eligible point {@code L} that fall in a window are buckets of their own and are + * always returned, as in the original algorithm. {@code F} is reported by the first + * window that contains it and {@code L} by the last one. + *
    • Every other window contributes one bucket made of its remaining eligible points. The + * anchor chain starts at {@code F}: for a window bucket {@code A} is the previously + * selected point, {@code C} is the average point of the next window bucket that has + * points ({@code L} when there is none), ties go to the earliest point, and buckets + * without points are skipped. Overlapping windows ({@code SLIDE < SIZE}) keep one + * chain, and the state is independent between partitions and columns. + *
    + *
+ * + *

Bucket mode emits, per window, up to three rows per participant column: {@code F}, the point + * selected from the window bucket, and {@code L}. Rows are padded by position as in M4, and a + * window in which no participant column has an eligible point emits no row. Target-count mode emits + * as many rows as the column with the most selected points and no row when that number is zero. + * + *

{@code NULL} participant values are ignored per column; every non-null value, including {@code + * NaN} and the infinities, is eligible and is reproduced in the output. A non-finite value cannot + * serve as a triangle vertex, though: the anchor is the most recent finite selected point (or the + * first finite eligible point), {@code C} averages only the finite points of the next bucket that + * has one — where the final point is the last bucket, and the last finite eligible point stands in + * when no later bucket has a finite point — and a bucket without a finite candidate returns its + * earliest point without moving the anchor. Ties in the triangle area are broken deterministically + * by the earliest timestamp (stable input order). + * + *

The timestamps of the input rows of one partition must be unique. As soon as two rows of the + * same partition carry the same timestamp the query fails with a semantic error ({@code 701}); the + * check runs at the partition input boundary, before per-column {@code NULL} filtering and before + * window expansion, so a row that several overlapping windows share is still a single input row. + * Equal timestamps in different partitions remain valid. Since the input is ordered by {@code + * TIMECOL}, equal timestamps are adjacent, and the check compares each row with the previous one + * and carries the last seen timestamp across input blocks. + */ +public class LTTBTableFunction implements TableFunction { + + public static final String DATA_PARAMETER_NAME = "DATA"; + public static final String TIMECOL_PARAMETER_NAME = "TIMECOL"; + public static final String N_PARAMETER_NAME = "N"; + public static final String SIZE_PARAMETER_NAME = "SIZE"; + public static final String SLIDE_PARAMETER_NAME = "SLIDE"; + public static final String ORIGIN_PARAMETER_NAME = "ORIGIN"; + + /** Internal boolean argument injected by the analyzer: {@code true} if SIZE is a duration. */ + public static final String WINDOW_MODE_PARAMETER_NAME = "__LTTB_WINDOW_MODE"; + + /** + * Internal boolean argument injected by the analyzer: {@code true} if the user passed {@code + * ORIGIN}. The analyzer knows this from the argument list, which is more precise than comparing + * against {@link #UNSPECIFIED_ORIGIN}: {@link Long#MIN_VALUE} is a legal timestamp. + */ + public static final String ORIGIN_SPECIFIED_PARAMETER_NAME = "__LTTB_ORIGIN_SPECIFIED"; + + public static final long UNSPECIFIED_N = Long.MIN_VALUE; + public static final long UNSPECIFIED_SIZE = Long.MIN_VALUE; + public static final long UNSPECIFIED_SLIDE = Long.MIN_VALUE; + + /** + * Marks {@code ORIGIN} as not specified. The user-visible default of the argument is still {@code + * 0} (the epoch); the sentinel only lets {@link #analyze} distinguish an explicit {@code ORIGIN} + * from the injected default, so the function rejects the argument in modes that do not use it. + */ + public static final long UNSPECIFIED_ORIGIN = Long.MIN_VALUE; + + public static final long MIN_TARGET_COUNT = 3L; + + /** Hard cap on eligible points buffered per participant column in one partition or window. */ + public static final int MAX_BUFFERED_POINTS = 1 << 22; + + /** + * Fallback for {@code lttb_buffer_size_in_bytes} when it is not positive. The configured default + * in {@code iotdb-system.properties.template} is {@code 0}, which {@code IoTDBDescriptor} + * resolves to {@code min(32 MiB, operator memory / query_thread_count / 8)}; this constant + * therefore only matches {@link org.apache.iotdb.commons.conf.CommonConfig}'s initial value and + * keeps a misconfigured node bounded. + */ + public static final long DEFAULT_MAX_BUFFER_BYTES = 32L * 1024 * 1024; + + public static final String MODE_PROPERTY = "__LTTB_MODE"; + public static final String PARTITION_TYPES_PROPERTY = "__LTTB_PARTITION_TYPES"; + public static final String PARTICIPANT_TYPES_PROPERTY = "__LTTB_PARTICIPANT_TYPES"; + + private static final String OUTPUT_WINDOW_START_COLUMN = "window_start"; + private static final String OUTPUT_WINDOW_END_COLUMN = "window_end"; + private static final String OUTPUT_WINDOW_INDEX_COLUMN = "window_index"; + private static final String TIME_SUFFIX = "_time"; + private static final int INITIAL_CAPACITY = 64; + private static final int NOT_SELECTED = -1; + + /** Execution mode persisted in the {@link MapTableFunctionHandle}. */ + public enum Mode { + TARGET_COUNT, + TIME_WINDOW, + COUNT_WINDOW + } + + /** + * The live value of the hot-reloadable {@code lttb_buffer_size_in_bytes} configuration parameter. + * Values that are not positive fall back to {@link #DEFAULT_MAX_BUFFER_BYTES} so a misconfigured + * node still bounds memory instead of buffering without limit. + * + *

This is read once per {@linkplain TableFunctionProcessorProvider}, in {@link + * #getProcessorProvider(TableFunctionHandle)}. Every processor of that provider enforces the same + * value, and the operator reserves the same value, so a hot reload cannot make the two differ for + * a running query; it applies to providers created afterwards. + */ + public static long maxBufferBytes() { + long configured = CommonDescriptor.getInstance().getConfig().getLttbBufferSize(); + return configured > 0 ? configured : DEFAULT_MAX_BUFFER_BYTES; + } + + @Override + public List getArgumentsSpecifications() { + return Arrays.asList( + TableParameterSpecification.builder() + .name(DATA_PARAMETER_NAME) + .setSemantics() + .ascendingOrder() + .build(), + ScalarParameterSpecification.builder() + .name(TIMECOL_PARAMETER_NAME) + .type(Type.STRING) + .build(), + ScalarParameterSpecification.builder() + .name(N_PARAMETER_NAME) + .type(Type.INT64) + .defaultValue(UNSPECIFIED_N) + .build(), + ScalarParameterSpecification.builder() + .name(SIZE_PARAMETER_NAME) + .type(Type.INT64) + .defaultValue(UNSPECIFIED_SIZE) + .addChecker(POSITIVE_LONG_CHECKER) + .build(), + ScalarParameterSpecification.builder() + .name(SLIDE_PARAMETER_NAME) + .type(Type.INT64) + .defaultValue(UNSPECIFIED_SLIDE) + .addChecker(POSITIVE_LONG_CHECKER) + .build(), + ScalarParameterSpecification.builder() + .name(ORIGIN_PARAMETER_NAME) + .type(Type.TIMESTAMP) + .defaultValue(UNSPECIFIED_ORIGIN) + .build()); + } + + @Override + public TableFunctionAnalysis analyze(Map arguments) throws UDFException { + int timeColumnIndex = + WindowTVFUtils.checkOrderByColumn(arguments, DATA_PARAMETER_NAME, TIMECOL_PARAMETER_NAME); + TableArgument tableArgument = (TableArgument) arguments.get(DATA_PARAMETER_NAME); + List partitionIndexes = WindowTVFUtils.getPartitionIndexes(tableArgument); + Set excludedIndexes = new HashSet<>(partitionIndexes); + excludedIndexes.add(timeColumnIndex); + + long n = getLong(arguments, N_PARAMETER_NAME); + long size = getLong(arguments, SIZE_PARAMETER_NAME); + long slide = getLong(arguments, SLIDE_PARAMETER_NAME); + long origin = getLong(arguments, ORIGIN_PARAMETER_NAME); + boolean nSpecified = n != UNSPECIFIED_N; + boolean sizeSpecified = size != UNSPECIFIED_SIZE; + boolean slideSpecified = slide != UNSPECIFIED_SLIDE; + boolean originSpecified = + arguments.containsKey(ORIGIN_SPECIFIED_PARAMETER_NAME) + ? (boolean) ((ScalarArgument) arguments.get(ORIGIN_SPECIFIED_PARAMETER_NAME)).getValue() + : origin != UNSPECIFIED_ORIGIN; + if (nSpecified == sizeSpecified) { + throw new SemanticException( + CommonMessages + .EXCEPTION_EXACTLY_ONE_OF_THE_N_AND_SIZE_ARGUMENTS_MUST_BE_SPECIFIED_FOR_LTTB_54AF0733); + } + + Mode mode; + if (nSpecified) { + if (slideSpecified || originSpecified) { + throw new SemanticException( + CommonMessages + .EXCEPTION_THE_N_ARGUMENT_OF_LTTB_CANNOT_BE_COMBINED_WITH_THE_SLIDE_OR_ORIGIN_ARGUMENTS_C2FF1FE1); + } + if (n < MIN_TARGET_COUNT) { + throw new SemanticException( + CommonMessages.EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_AT_LEAST_3_29CE2B87); + } + mode = Mode.TARGET_COUNT; + } else { + if (size <= 0) { + throw new UDFException( + CommonMessages + .EXCEPTION_INVALID_SCALAR_ARGUMENT_SIZE_SHOULD_BE_A_POSITIVE_VALUE_3ECF76E0); + } + if (!slideSpecified) { + slide = size; + } else if (slide <= 0) { + throw new UDFException( + CommonMessages + .EXCEPTION_INVALID_SCALAR_ARGUMENT_SLIDE_SHOULD_BE_A_POSITIVE_VALUE_F019E091); + } + boolean isTimeWindow = + arguments.containsKey(WINDOW_MODE_PARAMETER_NAME) + && (boolean) ((ScalarArgument) arguments.get(WINDOW_MODE_PARAMETER_NAME)).getValue(); + if (!isTimeWindow && originSpecified) { + throw new SemanticException( + QueryMessages + .EXCEPTION_THE_ORIGIN_ARGUMENT_IS_ONLY_SUPPORTED_IN_TIME_WINDOW_MODE_B3F358B9); + } + mode = isTimeWindow ? Mode.TIME_WINDOW : Mode.COUNT_WINDOW; + } + + DescribedSchema.Builder schemaBuilder = new DescribedSchema.Builder(); + if (mode == Mode.TIME_WINDOW) { + schemaBuilder + .addField(OUTPUT_WINDOW_START_COLUMN, Type.TIMESTAMP) + .addField(OUTPUT_WINDOW_END_COLUMN, Type.TIMESTAMP); + } else { + schemaBuilder.addField(OUTPUT_WINDOW_INDEX_COLUMN, Type.INT64); + } + + List partitionTypes = new ArrayList<>(); + for (int partitionIndex : partitionIndexes) { + Type type = tableArgument.getFieldTypes().get(partitionIndex); + partitionTypes.add(type); + schemaBuilder.addField(tableArgument.getFieldNames().get(partitionIndex).get(), type); + } + + // Rejects every non-numeric participant column with the shared "not allowed columns" message. + List participantIndexes = + WindowTVFUtils.getCalculationIndexes(tableArgument, excludedIndexes, null); + if (participantIndexes.isEmpty()) { + throw new SemanticException(CommonMessages.EXCEPTION_NO_CALCULATE_COLUMNS); + } + List participantTypes = new ArrayList<>(); + for (int participantIndex : participantIndexes) { + Type type = tableArgument.getFieldTypes().get(participantIndex); + String columnName = tableArgument.getFieldNames().get(participantIndex).get(); + participantTypes.add(type); + schemaBuilder.addField(columnName + TIME_SUFFIX, Type.TIMESTAMP); + schemaBuilder.addField(columnName, type); + } + + MapTableFunctionHandle.Builder handleBuilder = + new MapTableFunctionHandle.Builder() + .addProperty(MODE_PROPERTY, mode.name()) + .addProperty(PARTITION_TYPES_PROPERTY, WindowTVFUtils.joinTypes(partitionTypes)) + .addProperty(PARTICIPANT_TYPES_PROPERTY, WindowTVFUtils.joinTypes(participantTypes)); + if (mode == Mode.TARGET_COUNT) { + handleBuilder.addProperty(N_PARAMETER_NAME, n); + } else { + handleBuilder.addProperty(SIZE_PARAMETER_NAME, size).addProperty(SLIDE_PARAMETER_NAME, slide); + if (mode == Mode.TIME_WINDOW) { + handleBuilder.addProperty(ORIGIN_PARAMETER_NAME, originSpecified ? origin : 0L); + } + } + + List requiredColumns = new ArrayList<>(); + requiredColumns.add(timeColumnIndex); + requiredColumns.addAll(partitionIndexes); + requiredColumns.addAll(participantIndexes); + + return TableFunctionAnalysis.builder() + .properColumnSchema(schemaBuilder.build()) + .requireRecordSnapshot(false) + .requiredColumns(DATA_PARAMETER_NAME, requiredColumns) + .handle(handleBuilder.build()) + .build(); + } + + private static long getLong(Map arguments, String name) { + return (long) ((ScalarArgument) arguments.get(name)).getValue(); + } + + @Override + public TableFunctionHandle createTableFunctionHandle() { + return new MapTableFunctionHandle(); + } + + @Override + public TableFunctionProcessorProvider getProcessorProvider( + TableFunctionHandle tableFunctionHandle) { + MapTableFunctionHandle handle = (MapTableFunctionHandle) tableFunctionHandle; + Mode mode = Mode.valueOf((String) handle.getProperty(MODE_PROPERTY)); + Type[] partitionTypes = + WindowTVFUtils.parseTypes((String) handle.getProperty(PARTITION_TYPES_PROPERTY)); + Type[] participantTypes = + WindowTVFUtils.parseTypes((String) handle.getProperty(PARTICIPANT_TYPES_PROPERTY)); + // Resolved once so that every processor of this provider enforces the same limit the operator + // reserves, even if lttb_buffer_size_in_bytes is hot-reloaded while the query runs. + long maxBufferedBytes = maxBufferBytes(); + + return new LTTBProcessorProvider( + mode, partitionTypes, participantTypes, handle, maxBufferedBytes); + } + + /** + * The provider of one LTTB invocation. It reports the budget it resolved at construction, so the + * operator reserves exactly the limit its processors enforce. + */ + private static final class LTTBProcessorProvider + implements TableFunctionProcessorProvider, TableFunctionProcessorMemoryBudget { + private final Mode mode; + private final Type[] partitionTypes; + private final Type[] participantTypes; + private final MapTableFunctionHandle handle; + private final long maxBufferedBytes; + + private LTTBProcessorProvider( + Mode mode, + Type[] partitionTypes, + Type[] participantTypes, + MapTableFunctionHandle handle, + long maxBufferedBytes) { + this.mode = mode; + this.partitionTypes = partitionTypes; + this.participantTypes = participantTypes; + this.handle = handle; + this.maxBufferedBytes = maxBufferedBytes; + } + + @Override + public long getEstimatedMaxBufferedBytes() { + return maxBufferedBytes; + } + + @Override + public TableFunctionDataProcessor getDataProcessor() { + ParticipantColumn[] participantColumns = + createParticipantColumns(participantTypes, partitionTypes.length + 1); + switch (mode) { + case TARGET_COUNT: + return new TargetCountLTTBDataProcessor( + (long) handle.getProperty(N_PARAMETER_NAME), + partitionTypes, + participantColumns, + maxBufferedBytes); + case TIME_WINDOW: + return new TimeWindowLTTBDataProcessor( + (long) handle.getProperty(SIZE_PARAMETER_NAME), + (long) handle.getProperty(SLIDE_PARAMETER_NAME), + (long) handle.getProperty(ORIGIN_PARAMETER_NAME), + partitionTypes, + participantColumns, + maxBufferedBytes); + case COUNT_WINDOW: + return new CountWindowLTTBDataProcessor( + (long) handle.getProperty(SIZE_PARAMETER_NAME), + (long) handle.getProperty(SLIDE_PARAMETER_NAME), + partitionTypes, + participantColumns, + maxBufferedBytes); + default: + throw new IllegalStateException(String.valueOf(mode)); + } + } + } + + private static ParticipantColumn[] createParticipantColumns(Type[] types, int firstInputIndex) { + ParticipantColumn[] columns = new ParticipantColumn[types.length]; + for (int i = 0; i < types.length; i++) { + columns[i] = new ParticipantColumn(firstInputIndex + i, types[i]); + } + return columns; + } + + // --------------------------------------------------------------------------------------------- + // LTTB core + // --------------------------------------------------------------------------------------------- + + /** + * Standard LTTB selection over an ordered point sequence. + * + *

When {@code count <= n} every index is returned. Otherwise the first and last points are + * retained, bucket {@code i} covers {@code [floor(i*(count-2)/(n-2))+1, + * floor((i+1)*(count-2)/(n-2))+1)}, and for every bucket the candidate forming the largest + * triangle with the anchor and the lookahead average wins. The final point is a bucket of its + * own, so the last bucket looks ahead to it, and ties are broken by the earliest timestamp. + * + *

{@code NaN} and infinite values are eligible points, but they cannot serve as a triangle + * vertex: an undefined area would make every candidate tie and the bucket would return its + * earliest point regardless of the data. The anchor is therefore the most recent finite selected + * point (or the first finite point), and {@code C} averages only the finite points of the next + * bucket that has one — skipping buckets without one, and falling back to the last finite point + * of the partition when there is no such bucket, which includes a non-finite final point. A + * bucket with no finite candidate returns its earliest point without moving the anchor. + * Non-finite points are still selected and returned when their bucket has no finite alternative. + * + * @return ascending indexes of the selected points + */ + static int[] selectTargetCount(long[] times, double[] values, int count, long n) { + return selectTargetCount(times, values, null, count, n); + } + + private static int[] selectTargetCount( + long[] times, double[] values, long[] integralValues, int count, long n) { + if (count <= n) { + int[] all = new int[count]; + for (int i = 0; i < count; i++) { + all[i] = i; + } + return all; + } + + int[] selected = new int[(int) n]; + int selectedCount = 0; + selected[selectedCount++] = 0; + long bucketCount = n - 2; + long intermediate = count - 2L; + // The anchor starts at the earliest finite point so that every area it participates in has a + // representable origin. It only moves to a selected point; a bucket with no finite candidate + // leaves it in place. + int anchor = 0; + while (anchor < count && !isFiniteValue(values, integralValues, anchor)) { + anchor++; + } + boolean hasAnchor = anchor < count; + // C averages the finite points of the next bucket that has one, so the lookahead bucket only + // moves forward and every bucket is scanned at most once. A value past the last bucket marks + // that there is none left and C becomes the last finite point of the partition. + int lastFinite = count - 1; + while (lastFinite >= 0 && !isFiniteValue(values, integralValues, lastFinite)) { + lastFinite--; + } + long lookaheadBucket = -1; + for (long bucket = 0; bucket < bucketCount; bucket++) { + int currentStart = bucketBoundary(bucket, intermediate, bucketCount); + int currentEnd = bucketBoundary(bucket + 1, intermediate, bucketCount); + + long anchorTime = times[hasAnchor ? anchor : 0]; + double anchorValue = hasAnchor ? values[anchor] : 0; + long integralAnchor = hasAnchor && integralValues != null ? integralValues[anchor] : 0; + long next = Math.max(bucket + 1, lookaheadBucket); + while (next <= bucketCount + && !hasFinitePoint(values, integralValues, next, count, intermediate, bucketCount)) { + next++; + } + lookaheadBucket = next; + int lookaheadStart; + int lookaheadEnd; + if (lookaheadBucket == bucketCount + 1) { + // No later bucket has a finite point: use the last finite point, or the final point when + // the whole partition is non-finite. + lookaheadStart = lastFinite >= 0 ? lastFinite : count - 1; + lookaheadEnd = lookaheadStart + 1; + } else { + lookaheadStart = bucketBoundary(lookaheadBucket, intermediate, bucketCount); + lookaheadEnd = + lookaheadBucket == bucketCount + ? count + : bucketBoundary(lookaheadBucket + 1, intermediate, bucketCount); + } + int pick = + selectBucketPoint( + times, + values, + integralValues, + currentStart, + currentEnd, + anchorTime, + anchorValue, + integralAnchor, + times, + values, + integralValues, + lookaheadStart, + lookaheadEnd); + selected[selectedCount++] = pick; + if (isFiniteValue(values, integralValues, pick)) { + anchor = pick; + hasAnchor = true; + } + } + selected[selectedCount] = count - 1; + return selected; + } + + /** First index of bucket {@code bucket}; bucket {@code bucketCount} is the final point. */ + private static int bucketBoundary(long bucket, long intermediate, long bucketCount) { + return (int) (bucket * intermediate / bucketCount) + 1; + } + + /** Whether {@code bucket} holds a point that can serve as {@code C}. */ + private static boolean hasFinitePoint( + double[] values, + long[] integralValues, + long bucket, + int count, + long intermediate, + long bucketCount) { + int start = bucketBoundary(bucket, intermediate, bucketCount); + int end = bucket == bucketCount ? count : bucketBoundary(bucket + 1, intermediate, bucketCount); + for (int i = start; i < end; i++) { + if (isFiniteValue(values, integralValues, i)) { + return true; + } + } + return false; + } + + /** + * Whether the participant value at {@code index} is finite: integral columns always are, and a + * floating-point value qualifies when it is neither NaN nor infinite. Such a value can serve as a + * triangle vertex and is representable as an exact decimal. + */ + private static boolean isFiniteValue(double[] values, long[] integralValues, int index) { + return integralValues != null || Double.isFinite(values[index]); + } + + /** Score candidates against the next bucket average, keeping the first candidate on ties. */ + private static int selectBucketPoint( + long[] times, + double[] values, + long[] integralValues, + int start, + int end, + long anchorTime, + double anchorValue, + long integralAnchor, + long[] nextTimes, + double[] nextValues, + long[] nextIntegralValues, + int nextStart, + int nextEnd) { + if (end - start == 1) { + return start; + } + if (integralValues != null) { + try { + return argMaxIntegralArea( + times, + integralValues, + start, + end, + anchorTime, + integralAnchor, + nextTimes, + nextIntegralValues, + nextStart, + nextEnd); + } catch (ArithmeticException overflow) { + // A difference, sum or cross-product can exceed the long range. + } + } else { + int pick = + argMaxFloatingArea( + times, + values, + start, + end, + anchorTime, + anchorValue, + nextTimes, + nextValues, + nextStart, + nextEnd); + if (pick != NOT_SELECTED) { + return pick; + } + } + return argMaxAreaExactly( + times, + values, + integralValues, + start, + end, + anchorTime, + anchorValue, + integralAnchor, + nextTimes, + nextValues, + nextIntegralValues, + nextStart, + nextEnd); + } + + /** Returns NOT_SELECTED if rounding could change which candidate has the largest area. */ + private static int argMaxFloatingArea( + long[] times, + double[] values, + int start, + int end, + long anchorTime, + double anchorValue, + long[] nextTimes, + double[] nextValues, + int nextStart, + int nextEnd) { + double sumTime = 0; + double sumValue = 0; + double sumAbsTime = 0; + double sumAbsValue = 0; + int finiteCount = 0; + for (int i = nextStart; i < nextEnd; i++) { + if (Double.isFinite(nextValues[i])) { + double time = differenceAsDouble(nextTimes[i], anchorTime); + double value = nextValues[i] - anchorValue; + sumTime += time; + sumValue += value; + sumAbsTime += Math.abs(time); + sumAbsValue += Math.abs(value); + finiteCount++; + } + } + if (finiteCount == 0) { + return start; + } + + // Every determinant has the same denominator. Keeping the sums avoids rounding the two + // coordinates of the mean separately. Bound cancellation by summing absolute terms: each + // sum has at most finiteCount roundings, plus the coordinate differences and determinant. + // The factor of two also covers rounding in the bound itself. + double errorUlps = 2.0 * (finiteCount + 8); + int pick = start; + double bestUpper = -1; + double bestLower = -1; + double runnerUpUpper = -1; + for (int i = start; i < end; i++) { + if (!Double.isFinite(values[i])) { + continue; + } + double time = differenceAsDouble(times[i], anchorTime); + double value = values[i] - anchorValue; + double area = Math.abs(sumTime * value - time * sumValue); + double scale = sumAbsTime * Math.abs(value) + Math.abs(time) * sumAbsValue; + double error = scale == 0 ? 0 : errorUlps * Math.ulp(scale); + double upper = area + error; + if (!Double.isFinite(upper)) { + return NOT_SELECTED; + } + if (upper > bestUpper) { + runnerUpUpper = bestUpper; + bestUpper = upper; + bestLower = area - error; + pick = i; + } else { + runnerUpUpper = Math.max(runnerUpUpper, upper); + } + } + if (runnerUpUpper < 0 || bestUpper == 0 || bestLower > runnerUpUpper) { + return pick; + } + return NOT_SELECTED; + } + + /** Compare scaled triangle areas using the lookahead sums, preserving integer precision. */ + private static int argMaxIntegralArea( + long[] times, + long[] values, + int start, + int end, + long anchorTime, + long anchorValue, + long[] nextTimes, + long[] nextValues, + int nextStart, + int nextEnd) { + long sumTime = 0; + long sumValue = 0; + for (int i = nextStart; i < nextEnd; i++) { + sumTime = Math.addExact(sumTime, Math.subtractExact(nextTimes[i], anchorTime)); + sumValue = Math.addExact(sumValue, Math.subtractExact(nextValues[i], anchorValue)); + } + int pick = start; + long maxArea = 0; + for (int i = start; i < end; i++) { + long value = Math.subtractExact(values[i], anchorValue); + long time = Math.subtractExact(times[i], anchorTime); + long determinant = + Math.subtractExact( + Math.multiplyExact(sumTime, value), Math.multiplyExact(time, sumValue)); + // abs(MIN_VALUE) represents 2^63 when compared as an unsigned long. + long area = Math.abs(determinant); + if (Long.compareUnsigned(area, maxArea) > 0) { + maxArea = area; + pick = i; + } + } + return pick; + } + + /** + * Exact fallback for overflow and ambiguous floating-point comparisons. Multiplying all areas by + * the lookahead point count lets us use sums instead of dividing by that count, keeping the + * comparison exact even for recurring averages. The normal path does not allocate decimal values. + * + *

A {@code NaN} or infinite participant cannot be represented by {@link BigDecimal}, so such a + * candidate is skipped and ties resolve to the earliest point. The caller only reaches this + * method when the anchor and the lookahead point are finite, so the {@link BigDecimal} + * conversions of those two origins and of the lookahead values are always well defined. + */ + private static int argMaxAreaExactly( + long[] times, + double[] values, + long[] integralValues, + int start, + int end, + long anchorTime, + double anchorValue, + long integralAnchor, + long[] nextTimes, + double[] nextValues, + long[] nextIntegralValues, + int nextStart, + int nextEnd) { + BigDecimal timeOrigin = BigDecimal.valueOf(anchorTime); + BigDecimal valueOrigin = + integralValues == null ? new BigDecimal(anchorValue) : BigDecimal.valueOf(integralAnchor); + BigDecimal sumTime = BigDecimal.ZERO; + BigDecimal sumValue = BigDecimal.ZERO; + for (int i = nextStart; i < nextEnd; i++) { + if (!isFiniteValue(nextValues, nextIntegralValues, i)) { + continue; + } + sumTime = sumTime.add(BigDecimal.valueOf(nextTimes[i]).subtract(timeOrigin)); + sumValue = sumValue.add(exactValue(nextValues, nextIntegralValues, i).subtract(valueOrigin)); + } + int pick = start; + BigDecimal maxArea = null; + for (int i = start; i < end; i++) { + if (!isFiniteValue(values, integralValues, i)) { + continue; + } + BigDecimal time = BigDecimal.valueOf(times[i]).subtract(timeOrigin); + BigDecimal value = exactValue(values, integralValues, i).subtract(valueOrigin); + BigDecimal area = sumTime.multiply(value).subtract(time.multiply(sumValue)).abs(); + if (maxArea == null || area.compareTo(maxArea) > 0) { + maxArea = area; + pick = i; + } + } + return pick; + } + + private static BigDecimal exactValue(double[] values, long[] integralValues, int index) { + // The constructor preserves the actual binary floating-point value, including tiny deltas. + return integralValues == null + ? new BigDecimal(values[index]) + : BigDecimal.valueOf(integralValues[index]); + } + + private static double differenceAsDouble(long value, long origin) { + long difference = value - origin; + // Subtract before converting so nearby integers retain their precision. For spans exceeding + // the long range, use floating-point subtraction instead of the overflowed long difference. + return ((value ^ origin) & (value ^ difference)) < 0 + ? (double) value - (double) origin + : (double) difference; + } + + // --------------------------------------------------------------------------------------------- + // Column access and buffering + // --------------------------------------------------------------------------------------------- + + /** Reservations include array capacity, including both old and new arrays during growth. */ + static final class BufferMemoryBudget { + private final long limit; + private long reservedBytes; + + BufferMemoryBudget(long limit) { + this.limit = limit; + } + + void reserve(long bytes) { + if (bytes > limit - reservedBytes) { + throw new SemanticException( + String.format( + CommonMessages + .EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D, + limit)); + } + reservedBytes += bytes; + } + + void release(long bytes) { + reservedBytes -= bytes; + } + } + + private static final class ParticipantColumn { + private final int inputIndex; + private final Type type; + + private ParticipantColumn(int inputIndex, Type type) { + this.inputIndex = inputIndex; + this.type = type; + } + + private boolean isIntegral() { + return type == Type.INT32 || type == Type.INT64; + } + + /** + * Appends the record's value to {@code buffer} if it is non-null. All non-null values are + * eligible, including {@code NaN} and the infinities: the definition only excludes {@code NULL} + * participants, and dropping non-finite values would silently turn populated input into an + * all-{@code NULL} result. + */ + private void collect(Record record, long time, PointBuffer buffer) { + if (record.isNull(inputIndex)) { + return; + } + switch (type) { + case INT32: + buffer.addIntegral(time, record.getInt(inputIndex)); + break; + case INT64: + buffer.addIntegral(time, record.getLong(inputIndex)); + break; + case FLOAT: + buffer.addFloating(time, record.getFloat(inputIndex)); + break; + case DOUBLE: + buffer.addFloating(time, record.getDouble(inputIndex)); + break; + default: + throw new IllegalArgumentException( + String.format( + CommonMessages.EXCEPTION_UNSUPPORTED_LTTB_VALUE_TYPE_ARG_3E60F6FE, type)); + } + } + + private boolean isNull(Record record) { + return record.isNull(inputIndex); + } + + /** The value as a double, which is lossy only for INT64 values above 2^53. */ + private double floatingValue(Record record) { + switch (type) { + case INT32: + return record.getInt(inputIndex); + case INT64: + return record.getLong(inputIndex); + case FLOAT: + return record.getFloat(inputIndex); + case DOUBLE: + return record.getDouble(inputIndex); + default: + throw new IllegalArgumentException( + String.format( + CommonMessages.EXCEPTION_UNSUPPORTED_LTTB_VALUE_TYPE_ARG_3E60F6FE, type)); + } + } + + /** The exact value of an integral column, or {@code 0} for a floating-point column. */ + private long integralValue(Record record) { + switch (type) { + case INT32: + return record.getInt(inputIndex); + case INT64: + return record.getLong(inputIndex); + default: + return 0L; + } + } + + private void write( + ColumnBuilder timeBuilder, ColumnBuilder valueBuilder, PointBuffer buffer, int index) { + writePoint( + timeBuilder, + valueBuilder, + buffer.times[index], + buffer.values[index], + buffer.integralValues == null ? 0L : buffer.integralValues[index]); + } + + /** Writes one point; the integral value is only meaningful for an integral column. */ + private void writePoint( + ColumnBuilder timeBuilder, + ColumnBuilder valueBuilder, + long time, + double value, + long integral) { + timeBuilder.writeLong(time); + switch (type) { + case INT32: + valueBuilder.writeInt((int) integral); + break; + case INT64: + valueBuilder.writeLong(integral); + break; + case FLOAT: + valueBuilder.writeFloat((float) value); + break; + case DOUBLE: + valueBuilder.writeDouble(value); + break; + default: + throw new IllegalArgumentException( + String.format( + CommonMessages.EXCEPTION_UNSUPPORTED_LTTB_VALUE_TYPE_ARG_3E60F6FE, type)); + } + } + } + + /** + * Growable buffer of eligible points for one participant column. Integral columns additionally + * keep the exact {@code long} value so INT64 output is not rounded through {@code double}. + */ + static final class PointBuffer { + private static final long INSTANCE_SIZE = + RamUsageEstimator.shallowSizeOfInstance(PointBuffer.class); + private static final long[] EMPTY_LONGS = new long[0]; + private static final double[] EMPTY_DOUBLES = new double[0]; + + private final BufferMemoryBudget memoryBudget; + private long[] times = EMPTY_LONGS; + private double[] values = EMPTY_DOUBLES; + private long[] integralValues; + private int size; + private int onlyFiniteIndex = NOT_SELECTED; + + PointBuffer(boolean integral, BufferMemoryBudget memoryBudget) { + this.memoryBudget = memoryBudget; + if (memoryBudget != null) { + memoryBudget.reserve(INSTANCE_SIZE); + } + integralValues = integral ? EMPTY_LONGS : null; + } + + private static long arrayBytes(int capacity, boolean integral) { + if (capacity == 0) { + // Empty buffers share their backing arrays until the first eligible point arrives. + return 0; + } + return RamUsageEstimator.sizeOfLongArray(capacity) + + RamUsageEstimator.sizeOfDoubleArray(capacity) + + (integral ? RamUsageEstimator.sizeOfLongArray(capacity) : 0); + } + + private void release() { + if (memoryBudget != null) { + memoryBudget.release(INSTANCE_SIZE + arrayBytes(times.length, integralValues != null)); + } + } + + void addFloating(long time, double value) { + ensureCapacity(); + times[size] = time; + values[size] = value; + size++; + } + + void addIntegral(long time, long value) { + ensureCapacity(); + times[size] = time; + values[size] = value; + integralValues[size] = value; + size++; + } + + /** Appends a point whose exact integral value is only meaningful for an integral column. */ + void add(long time, double value, long integral) { + if (integralValues == null) { + addFloating(time, value); + } else { + ensureCapacity(); + times[size] = time; + values[size] = value; + integralValues[size] = integral; + size++; + } + } + + /** Drops the last point, which is used to move the partition's last eligible point out. */ + void truncateLast() { + size--; + } + + /** + * Records the index of a closed bucket's sole finite candidate, if any. Recomputed after + * removing the partition's final point from the bucket. + */ + private boolean indexFinitePoints() { + onlyFiniteIndex = NOT_SELECTED; + for (int i = 0; i < size; i++) { + if (Double.isFinite(values[i])) { + if (onlyFiniteIndex != NOT_SELECTED) { + onlyFiniteIndex = NOT_SELECTED; + return true; + } + onlyFiniteIndex = i; + } + } + return onlyFiniteIndex != NOT_SELECTED; + } + + private void ensureCapacity() { + if (size < times.length) { + return; + } + if (size >= MAX_BUFFERED_POINTS) { + throw new SemanticException( + String.format( + CommonMessages + .EXCEPTION_LTTB_BUFFERS_AT_MOST_ARG_ELIGIBLE_POINTS_PER_COLUMN_IN_ONE_PARTITION_OR_WINDOW_4C746D82, + MAX_BUFFERED_POINTS)); + } + int newCapacity = + size == 0 + ? INITIAL_CAPACITY + : (int) Math.min((long) times.length * 2, MAX_BUFFERED_POINTS); + long oldArrayBytes = arrayBytes(times.length, integralValues != null); + if (memoryBudget != null) { + // Reserve before copying: the old arrays remain live until their replacements exist. + memoryBudget.reserve(arrayBytes(newCapacity, integralValues != null)); + } + times = Arrays.copyOf(times, newCapacity); + values = Arrays.copyOf(values, newCapacity); + if (integralValues != null) { + integralValues = Arrays.copyOf(integralValues, newCapacity); + } + if (memoryBudget != null) { + memoryBudget.release(oldArrayBytes); + } + } + + int size() { + return size; + } + + boolean isEmpty() { + return size == 0; + } + + long time(int index) { + return times[index]; + } + + double value(int index) { + return values[index]; + } + } + + // --------------------------------------------------------------------------------------------- + // Processors + // --------------------------------------------------------------------------------------------- + + /** + * Partition-local timestamp uniqueness of the input rows. The input is ordered by {@code + * TIMECOL}, so a duplicate timestamp is always adjacent to its predecessor; the last accepted + * timestamp is kept in the instance so the rule also spans input blocks of the same partition. + */ + static final class TimestampUniquenessChecker { + private long previousTimestamp; + private boolean hasPreviousTimestamp; + + void check(long time) { + if (hasPreviousTimestamp && time == previousTimestamp) { + throw new SemanticException( + String.format( + CommonMessages + .EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD, + time)); + } + previousTimestamp = time; + hasPreviousTimestamp = true; + } + } + + private abstract static class AbstractLTTBDataProcessor implements TableFunctionDataProcessor { + protected final Type[] partitionTypes; + protected final Object[] partitionValues; + protected final ParticipantColumn[] participantColumns; + private final TimestampUniquenessChecker timestampChecker = new TimestampUniquenessChecker(); + + protected AbstractLTTBDataProcessor( + Type[] partitionTypes, ParticipantColumn[] participantColumns) { + this.partitionTypes = partitionTypes; + this.partitionValues = new Object[partitionTypes.length]; + this.participantColumns = participantColumns; + } + + /** + * Rejects a null or repeated timestamp in the partition. Runs at the partition input boundary, + * before per-column {@code NULL} filtering and before window expansion, so a row shared by + * several overlapping windows is still a single input row. + */ + protected final long readTimestamp(Record input) { + if (input.isNull(0)) { + throw new SemanticException(QueryMessages.TIME_COLUMN_SHOULD_NOT_BE_NULL); + } + long time = input.getLong(0); + timestampChecker.check(time); + return time; + } + + protected final PointBuffer[] newBuffers(BufferMemoryBudget memoryBudget) { + PointBuffer[] buffers = new PointBuffer[participantColumns.length]; + for (int i = 0; i < buffers.length; i++) { + buffers[i] = new PointBuffer(participantColumns[i].isIntegral(), memoryBudget); + } + return buffers; + } + + /** Partition columns are constant within a partition; keep the first non-null value. */ + protected final void capturePartitionValues(Record input) { + for (int i = 0; i < partitionTypes.length; i++) { + int inputIndex = i + 1; + if (partitionValues[i] == null && !input.isNull(inputIndex)) { + partitionValues[i] = WindowTVFUtils.readValue(input, inputIndex, partitionTypes[i]); + } + } + } + + protected final void collect(Record input, long time, PointBuffer[] buffers) { + for (int i = 0; i < participantColumns.length; i++) { + participantColumns[i].collect(input, time, buffers[i]); + } + } + + /** + * Writes one output row. {@code windowColumnCount} leading builders were already filled by the + * caller; {@code selectedIndexes[i]} is {@link #NOT_SELECTED} when column {@code i} has no + * point. + */ + protected final void writeRow( + List builders, + int windowColumnCount, + PointBuffer[] buffers, + int[] selectedIndexes) { + int builderIndex = windowColumnCount; + for (int i = 0; i < partitionTypes.length; i++) { + WindowTVFUtils.writeValue( + builders.get(builderIndex++), partitionValues[i], partitionTypes[i]); + } + for (int i = 0; i < participantColumns.length; i++) { + ColumnBuilder timeBuilder = builders.get(builderIndex++); + ColumnBuilder valueBuilder = builders.get(builderIndex++); + if (selectedIndexes[i] == NOT_SELECTED) { + timeBuilder.appendNull(); + valueBuilder.appendNull(); + } else { + participantColumns[i].write(timeBuilder, valueBuilder, buffers[i], selectedIndexes[i]); + } + } + } + } + + /** Buffers the whole partition and applies the standard LTTB algorithm in {@link #finish}. */ + private static final class TargetCountLTTBDataProcessor extends AbstractLTTBDataProcessor + implements BatchedTableFunctionDataProcessor { + private final long n; + private final PointBuffer[] buffers; + private final BufferMemoryBudget memoryBudget; + private boolean hasRows; + private int[][] selections; + private int[] selectedIndexes; + private int rowCount; + private int nextRow; + + private TargetCountLTTBDataProcessor( + long n, + Type[] partitionTypes, + ParticipantColumn[] participantColumns, + long maxBufferedBytes) { + super(partitionTypes, participantColumns); + this.n = n; + this.memoryBudget = new BufferMemoryBudget(maxBufferedBytes); + memoryBudget.reserve(RamUsageEstimator.sizeOfObjectArray(participantColumns.length)); + this.buffers = newBuffers(memoryBudget); + } + + @Override + public void process( + Record input, + List properColumnBuilders, + ColumnBuilder passThroughIndexBuilder) { + hasRows = true; + long time = readTimestamp(input); + capturePartitionValues(input); + collect(input, time, buffers); + } + + @Override + public boolean finishBatch(List builders, BooleanSupplier blockFull) { + if (!hasRows) { + return true; + } + if (selections == null) { + prepareSelections(); + } + while (nextRow < rowCount) { + builders.get(0).writeLong(0L); + for (int i = 0; i < participantColumns.length; i++) { + selectedIndexes[i] = + nextRow < selections[i].length ? selections[i][nextRow] : NOT_SELECTED; + } + writeRow(builders, 1, buffers, selectedIndexes); + nextRow++; + if (blockFull.getAsBoolean()) { + break; + } + } + return nextRow == rowCount; + } + + private void prepareSelections() { + long selectionBytes = + RamUsageEstimator.sizeOfObjectArray(participantColumns.length) + + RamUsageEstimator.sizeOfIntArray(participantColumns.length); + for (PointBuffer buffer : buffers) { + selectionBytes += RamUsageEstimator.sizeOfIntArray((int) Math.min(buffer.size, n)); + } + memoryBudget.reserve(selectionBytes); + selections = new int[participantColumns.length][]; + selectedIndexes = new int[participantColumns.length]; + for (int i = 0; i < participantColumns.length; i++) { + PointBuffer buffer = buffers[i]; + selections[i] = + selectTargetCount(buffer.times, buffer.values, buffer.integralValues, buffer.size, n); + rowCount = Math.max(rowCount, selections[i].length); + } + } + + @Override + public void beforeDestroy() { + Arrays.fill(buffers, null); + selections = null; + selectedIndexes = null; + memoryBudget.reservedBytes = 0; + } + } + + /** + * One window of the partition: the eligible points that fall in it, per participant column. The + * first and last eligible point of a partition are not stored here, because they form buckets of + * their own. + */ + private abstract static class WindowState { + protected final PointBuffer[] buffers; + final WindowState[] nextFinite; + protected final long endExclusive; + + private WindowState(PointBuffer[] buffers, long endExclusive) { + this.buffers = buffers; + this.nextFinite = new WindowState[buffers.length]; + this.endExclusive = endExclusive; + } + + protected abstract void writeWindowColumns(List builders); + + protected abstract int getWindowColumnCount(); + } + + private static final class TimeWindowState extends WindowState { + private final long windowStart; + + private TimeWindowState(PointBuffer[] buffers, long windowStart, long endExclusive) { + super(buffers, endExclusive); + this.windowStart = windowStart; + } + + @Override + protected void writeWindowColumns(List builders) { + builders.get(0).writeLong(windowStart); + builders.get(1).writeLong(endExclusive); + } + + @Override + protected int getWindowColumnCount() { + return 2; + } + } + + private static final class CountWindowState extends WindowState { + private final long windowIndex; + + private CountWindowState(PointBuffer[] buffers, long endExclusive, long windowIndex) { + super(buffers, endExclusive); + this.windowIndex = windowIndex; + } + + @Override + protected void writeWindowColumns(List builders) { + builders.get(0).writeLong(windowIndex); + } + + @Override + protected int getWindowColumnCount() { + return 1; + } + } + + /** One output cell of window mode: a selected point, or the first/last eligible point. */ + private static final class WindowRow { + private final long time; + private final double value; + private final long integral; + + private WindowRow(long time, double value, long integral) { + this.time = time; + this.value = value; + this.integral = integral; + } + + private static WindowRow of(PointBuffer buffer, int index) { + return new WindowRow( + buffer.times[index], + buffer.values[index], + buffer.integralValues == null ? 0L : buffer.integralValues[index]); + } + } + + /** + * Window/bucket mode. Windows are constructed like M4, and {@code SIZE} defines a bucket rather + * than the input range of a separate standard LTTB invocation; the result is standard LTTB whose + * buckets are the windows: + * + *

    + *
  • Per partition and participant column, the first eligible point {@code F} and the last + * eligible point {@code L} that fall in a window are buckets of their own and are always + * returned. {@code F} is reported by the first window that contains it and {@code L} by the + * last one, so a window emits up to three rows: {@code F}, its selected point and {@code + * L}. + *
  • Every other window contributes one bucket made of its remaining eligible points. The + * anchor chain starts at {@code F}: for a window bucket {@code A} is the previously + * selected point, {@code C} is the average point of the next window bucket that has points + * (and {@code L} when there is none), ties go to the earliest point, and buckets without + * points are skipped. Overlapping windows ({@code SLIDE < SIZE}) keep one chain. + *
  • A window in which no participant column has an eligible point emits no row. + *
+ * + *

Rows are padded by position, as in M4. {@code L} is only known at the end of the partition, + * so a window is emitted once the bucket that supplies its {@code C} is closed and known not to + * end the partition, or in {@link #finish}. + * + *

Non-finite values stay eligible, but a {@code NaN} or infinite point cannot be a triangle + * vertex: {@code A} is the most recent finite selected point (or the first finite eligible + * point), {@code C} averages only finite points and skips buckets without one, falling back to + * the last finite eligible point, and a bucket without a finite candidate returns its earliest + * point without moving {@code A}. + */ + private abstract static class AbstractWindowLTTBDataProcessor + extends AbstractLTTBDataProcessor implements BatchedTableFunctionDataProcessor { + private static final long WINDOW_INSTANCE_SIZE = + Math.max( + RamUsageEstimator.shallowSizeOfInstance(TimeWindowState.class), + RamUsageEstimator.shallowSizeOfInstance(CountWindowState.class)); + + protected final long size; + protected final long slide; + protected final Deque activeWindows = new ArrayDeque<>(); + private final Deque pendingWindows = new ArrayDeque<>(); + // Closed buckets with finite points, in window order for each column. + private final WindowState[] firstPendingFinite; + private final WindowState[] lastPendingFinite; + private final BufferMemoryBudget memoryBudget; + private final long windowMetadataBytes; + + private final boolean[] hasFirstEligible; + private final long[] firstEligibleTimes; + private final double[] firstEligibleValues; + private final long[] integralFirstEligibleValues; + private final WindowState[] firstEligibleWindows; + private final boolean[] hasLastEligible; + private final long[] lastEligibleTimes; + private final double[] lastEligibleValues; + private final long[] integralLastEligibleValues; + private final long[] lastEligiblePositions; + private final boolean[] hasLastFinite; + private final long[] lastFiniteTimes; + private final double[] lastFiniteValues; + private final long[] integralLastFiniteValues; + private final boolean[] hasFirstFinite; + private final long[] firstFiniteTimes; + private final double[] firstFiniteValues; + private final long[] integralFirstFiniteValues; + private final boolean[] hasAnchor; + private final long[] anchorTimes; + private final double[] anchorValues; + private final long[] integralAnchorValues; + private final WindowState[] lastRowWindows; + private boolean finishing; + private Record pendingInput; + private long pendingTime; + private WindowRow[][] outputRows; + private int outputRowCount; + private int nextOutputRow; + + protected AbstractWindowLTTBDataProcessor( + long size, + long slide, + Type[] partitionTypes, + ParticipantColumn[] participantColumns, + long maxBufferedBytes) { + super(partitionTypes, participantColumns); + this.size = size; + this.slide = slide; + this.memoryBudget = new BufferMemoryBudget(maxBufferedBytes); + int columnCount = participantColumns.length; + long referenceArrayBytes = RamUsageEstimator.sizeOfObjectArray(columnCount); + // Each of the five remembered points has a presence flag, time, and floating and integral + // values. The last eligible point also keeps its position. Four arrays link columns to + // windows. + long longArrayBytes = RamUsageEstimator.sizeOfLongArray(columnCount); + long pointStateBytes = + RamUsageEstimator.sizeOfBooleanArray(columnCount) + + 2 * longArrayBytes + + RamUsageEstimator.sizeOfDoubleArray(columnCount); + memoryBudget.reserve(5 * pointStateBytes + longArrayBytes + 4 * referenceArrayBytes); + this.firstPendingFinite = new WindowState[columnCount]; + this.lastPendingFinite = new WindowState[columnCount]; + this.windowMetadataBytes = WINDOW_INSTANCE_SIZE + 4 * referenceArrayBytes; + this.hasFirstEligible = new boolean[columnCount]; + this.firstEligibleTimes = new long[columnCount]; + this.firstEligibleValues = new double[columnCount]; + this.integralFirstEligibleValues = new long[columnCount]; + this.firstEligibleWindows = new WindowState[columnCount]; + this.hasLastEligible = new boolean[columnCount]; + this.lastEligibleTimes = new long[columnCount]; + this.lastEligibleValues = new double[columnCount]; + this.integralLastEligibleValues = new long[columnCount]; + this.lastEligiblePositions = new long[columnCount]; + this.hasLastFinite = new boolean[columnCount]; + this.lastFiniteTimes = new long[columnCount]; + this.lastFiniteValues = new double[columnCount]; + this.integralLastFiniteValues = new long[columnCount]; + this.hasFirstFinite = new boolean[columnCount]; + this.firstFiniteTimes = new long[columnCount]; + this.firstFiniteValues = new double[columnCount]; + this.integralFirstFiniteValues = new long[columnCount]; + this.hasAnchor = new boolean[columnCount]; + this.anchorTimes = new long[columnCount]; + this.anchorValues = new double[columnCount]; + this.integralAnchorValues = new long[columnCount]; + this.lastRowWindows = new WindowState[columnCount]; + } + + protected final PointBuffer[] newWindowBuffers() { + // Even an all-NULL window allocates state, so reserve before creating any of its buffers. + memoryBudget.reserve(windowMetadataBytes); + return newBuffers(memoryBudget); + } + + private void releaseWindow(W window) { + for (int i = 0; i < participantColumns.length; i++) { + if (firstEligibleWindows[i] == window) { + firstEligibleWindows[i] = null; + } + if (lastRowWindows[i] == window) { + lastRowWindows[i] = null; + } + if (firstPendingFinite[i] == window) { + firstPendingFinite[i] = window.nextFinite[i]; + if (firstPendingFinite[i] == null) { + lastPendingFinite[i] = null; + } + } + window.buffers[i].release(); + } + memoryBudget.release(windowMetadataBytes); + } + + @Override + public final void process( + Record input, + List properColumnBuilders, + ColumnBuilder passThroughIndexBuilder) { + processInput(input, properColumnBuilders, null); + drainOutput(properColumnBuilders, () -> false); + } + + @Override + public final void processInput(Record input, List builders, IoTDBLocal local) { + pendingTime = readTimestamp(input); + capturePartitionValues(input); + closeWindows(position(pendingTime)); + // The iterator stays on this record until drainOutput finishes. Release ready windows before + // opening the windows for this row, so the old and new buffers need not fit simultaneously. + pendingInput = input; + } + + protected abstract long position(long time); + + protected abstract void processRecord(Record input, long time); + + protected enum WindowsForRow { + NONE, + FIRST, + ALL + } + + // A column's first eligible point is stored separately and reported by its earliest window. + // Later points are bucket candidates in every window that contains them. + protected final WindowsForRow windowsForRow(Record input) { + WindowsForRow windows = WindowsForRow.NONE; + for (int i = 0; i < participantColumns.length; i++) { + if (!participantColumns[i].isNull(input)) { + if (hasFirstEligible[i]) { + return WindowsForRow.ALL; + } + windows = WindowsForRow.FIRST; + } + } + return windows; + } + + /** + * Adds one input row to every open window that contains it. The first eligible point of a + * column is kept aside as the {@code F} bucket instead of being added to a window bucket. + */ + protected final void collectIntoWindows(long position, Record input, long time) { + for (int i = 0; i < participantColumns.length; i++) { + // A point that falls in a gap of a SLIDE > SIZE layout belongs to no window at all. + if (participantColumns[i].isNull(input) || activeWindows.isEmpty()) { + continue; + } + double value = participantColumns[i].floatingValue(input); + long integral = participantColumns[i].integralValue(input); + if (Double.isFinite(value)) { + if (!hasFirstFinite[i]) { + hasFirstFinite[i] = true; + firstFiniteTimes[i] = time; + firstFiniteValues[i] = value; + integralFirstFiniteValues[i] = integral; + } + hasLastFinite[i] = true; + lastFiniteTimes[i] = time; + lastFiniteValues[i] = value; + integralLastFiniteValues[i] = integral; + } + if (!hasFirstEligible[i]) { + hasFirstEligible[i] = true; + firstEligibleTimes[i] = time; + firstEligibleValues[i] = value; + integralFirstEligibleValues[i] = integral; + firstEligibleWindows[i] = activeWindows.peekFirst(); + continue; + } + hasLastEligible[i] = true; + lastEligibleTimes[i] = time; + lastEligibleValues[i] = value; + integralLastEligibleValues[i] = integral; + lastEligiblePositions[i] = position; + for (W window : activeWindows) { + window.buffers[i].add(time, value, integral); + } + } + } + + /** Moves the windows that ended before {@code position} into the pending queue. */ + private void closeWindows(long position) { + while (!activeWindows.isEmpty() && activeWindows.peekFirst().endExclusive <= position) { + W window = activeWindows.removeFirst(); + if (canEmitAnyRow(window)) { + pendingWindows.addLast(window); + indexFiniteBuckets(window); + } else { + // A closed window that holds no bucket and reports no F can never emit a row, and L is + // never its own row because L was collected into every bucket that contains it. Queueing + // it would let it hold a place in front of later windows — and its buffers — until the + // partition ends, so release it now. + releaseWindow(window); + } + } + } + + private void indexFiniteBuckets(WindowState window) { + for (int i = 0; i < participantColumns.length; i++) { + window.nextFinite[i] = null; + if (window.buffers[i].indexFinitePoints()) { + if (lastPendingFinite[i] == null) { + firstPendingFinite[i] = window; + } else { + lastPendingFinite[i].nextFinite[i] = window; + } + lastPendingFinite[i] = window; + } + } + } + + /** Whether {@code window} can still contribute at least one output row. */ + private boolean canEmitAnyRow(W window) { + for (int i = 0; i < participantColumns.length; i++) { + if (window == firstEligibleWindows[i] || !window.buffers[i].isEmpty()) { + return true; + } + } + return false; + } + + @Override + public final boolean finishBatch(List builders, BooleanSupplier blockFull) { + if (!finishing) { + moveLastEligibleOutOfBuckets(); + } + return drainOutput(builders, blockFull); + } + + /** + * {@code L} is the last eligible point of a column and is a bucket of its own, but it was + * collected into the window buckets that contain it. Now that the partition has ended, remove + * it from the bucket it ends and remember which window reports it. + */ + private void moveLastEligibleOutOfBuckets() { + finishing = true; + while (!activeWindows.isEmpty()) { + pendingWindows.addLast(activeWindows.removeFirst()); + } + // Removing L can turn a formerly finite lookahead bucket into an empty or non-finite one. + Arrays.fill(firstPendingFinite, null); + Arrays.fill(lastPendingFinite, null); + for (WindowState window : pendingWindows) { + for (int i = 0; i < participantColumns.length; i++) { + PointBuffer bucket = window.buffers[i]; + if (bucket.isEmpty() || !containsPosition(window, lastEligiblePositions[i])) { + continue; + } + if (bucket.time(bucket.size() - 1) == lastEligibleTimes[i]) { + bucket.truncateLast(); + lastRowWindows[i] = window; + } + } + indexFiniteBuckets(window); + } + for (int i = 0; i < participantColumns.length; i++) { + if (!hasLastEligible[i]) { + // A single eligible point is both F and L and was already reported as F. + lastRowWindows[i] = null; + } + } + } + + @Override + public final void beforeDestroy() { + pendingInput = null; + outputRows = null; + activeWindows.clear(); + pendingWindows.clear(); + Arrays.fill(firstPendingFinite, null); + Arrays.fill(lastPendingFinite, null); + Arrays.fill(firstEligibleWindows, null); + Arrays.fill(lastRowWindows, null); + // Also covers a reservation made by a window whose construction failed at the limit. + memoryBudget.reservedBytes = 0; + } + + @Override + public final boolean drainOutput(List builders, BooleanSupplier blockFull) { + while (true) { + W window = pendingWindows.peekFirst(); + if (window == null || !isReady(window)) { + if (pendingInput == null) { + return true; + } + processRecord(pendingInput, pendingTime); + pendingInput = null; + continue; + } + if (outputRows == null) { + selectOutputRows(window); + } + boolean full = false; + while (nextOutputRow < outputRowCount && !full) { + window.writeWindowColumns(builders); + writeWindowRow(builders, window.getWindowColumnCount(), outputRows, nextOutputRow++); + full = blockFull.getAsBoolean(); + } + if (nextOutputRow == outputRowCount) { + releaseWindow(pendingWindows.removeFirst()); + outputRows = null; + } + if (full) { + return pendingInput == null + && (pendingWindows.isEmpty() || !isReady(pendingWindows.peekFirst())); + } + } + } + + /** + * Whether the first pending window can be emitted. A window must wait while moving {@code L} + * into its own bucket could change its output or the lookahead used to choose its sample. + * + *

A column with fewer than two eligible points has no {@code L}: the only point is {@code F} + * and was never collected into a bucket. {@link #lastEligiblePositions} still holds its default + * value then, so it must not be consulted — position {@code 0} would otherwise match the first + * window and stall every later window until the partition ends. + */ + private boolean isReady(W window) { + if (finishing) { + return true; + } + for (int i = 0; i < participantColumns.length; i++) { + if (hasLastEligible[i] && containsPosition(window, lastEligiblePositions[i])) { + // The last window containing L reports it. Earlier overlapping windows drop it. + // Compare offsets so the next window start need not fit in a long. + long windowStart = window.endExclusive - size; + boolean shared = lastEligiblePositions[i] - windowStart >= slide; + int candidateCount = window.buffers[i].size(); + // Dropping a trailing non-finite point leaves the pick and anchor unchanged if another + // candidate remains. In L's own window only a singleton gives the same output either way. + boolean sameOutput = + shared + ? candidateCount > 1 && !Double.isFinite(lastEligibleValues[i]) + : candidateCount == 1; + if (!sameOutput) { + return false; + } + } + // A sole finite candidate wins for every possible C. + if (firstPendingFinite[i] != window || window.buffers[i].onlyFiniteIndex != NOT_SELECTED) { + continue; + } + WindowState lookahead = window.nextFinite[i]; + if (lookahead == null) { + return false; + } + // Moving a finite L out of a multi-point average can change C. If L is the only + // finite point, it is both the current average and the final fallback. + if (hasLastEligible[i] + && containsPosition(lookahead, lastEligiblePositions[i]) + && Double.isFinite(lastEligibleValues[i]) + && lookahead.buffers[i].onlyFiniteIndex == NOT_SELECTED) { + return false; + } + } + return true; + } + + /** A one-point lookahead when {@code C} is the last finite point. */ + private PointBuffer singlePoint(long time, double value, int column) { + PointBuffer point = new PointBuffer(participantColumns[column].isIntegral(), null); + point.add( + time, + value, + participantColumns[column].isIntegral() ? integralLastFiniteValues[column] : 0L); + return point; + } + + /** Whether {@code position} falls in {@code window}; every window is {@code size} long. */ + private boolean containsPosition(WindowState window, long position) { + return position >= window.endExclusive - size && position < window.endExclusive; + } + + private void selectOutputRows(W window) { + // Selection advances the anchors. Keep the selected cells when a block ends mid-window. + outputRows = new WindowRow[participantColumns.length][]; + nextOutputRow = 0; + outputRowCount = 0; + for (int i = 0; i < participantColumns.length; i++) { + outputRows[i] = selectWindowRows(window, i); + outputRowCount = Math.max(outputRowCount, outputRows[i].length); + } + } + + private void writeWindowRow( + List builders, int windowColumnCount, WindowRow[][] rows, int row) { + int builderIndex = windowColumnCount; + for (int i = 0; i < partitionTypes.length; i++) { + WindowTVFUtils.writeValue( + builders.get(builderIndex++), partitionValues[i], partitionTypes[i]); + } + for (int i = 0; i < participantColumns.length; i++) { + ColumnBuilder timeBuilder = builders.get(builderIndex++); + ColumnBuilder valueBuilder = builders.get(builderIndex++); + if (row < rows[i].length) { + WindowRow cell = rows[i][row]; + participantColumns[i].writePoint( + timeBuilder, valueBuilder, cell.time, cell.value, cell.integral); + } else { + timeBuilder.appendNull(); + valueBuilder.appendNull(); + } + } + } + + /** + * The rows of one window for one participant column, in output order: {@code F}, the point + * selected from the window bucket, and {@code L}. + */ + private WindowRow[] selectWindowRows(W window, int column) { + WindowRow first = window == firstEligibleWindows[column] ? firstEligibleRow(column) : null; + WindowRow last = window == lastRowWindows[column] ? lastEligibleRow(column) : null; + PointBuffer bucket = window.buffers[column]; + WindowRow pick = bucket.isEmpty() ? null : pickInBucket(window, column, bucket); + WindowRow[] result = + new WindowRow[(first == null ? 0 : 1) + (pick == null ? 0 : 1) + (last == null ? 0 : 1)]; + int index = 0; + if (first != null) { + result[index++] = first; + } + if (pick != null) { + result[index++] = pick; + } + if (last != null) { + result[index] = last; + } + return result; + } + + private WindowRow firstEligibleRow(int column) { + return new WindowRow( + firstEligibleTimes[column], + firstEligibleValues[column], + integralFirstEligibleValues[column]); + } + + private WindowRow lastEligibleRow(int column) { + return new WindowRow( + lastEligibleTimes[column], + lastEligibleValues[column], + integralLastEligibleValues[column]); + } + + /** Selects the point of {@code bucket} with the largest triangle against {@code A} and C. */ + private WindowRow pickInBucket(W window, int column, PointBuffer bucket) { + if (firstPendingFinite[column] != window) { + return WindowRow.of(bucket, 0); + } + if (bucket.onlyFiniteIndex != NOT_SELECTED) { + return updateAnchor(bucket, bucket.onlyFiniteIndex, column); + } + long anchorTime; + double anchorValue; + long integralAnchor; + if (hasAnchor[column]) { + anchorTime = anchorTimes[column]; + anchorValue = anchorValues[column]; + integralAnchor = integralAnchorValues[column]; + } else if (hasFirstFinite[column]) { + // The chain starts at F, or at the first finite eligible point when F is not finite. + anchorTime = firstFiniteTimes[column]; + anchorValue = firstFiniteValues[column]; + integralAnchor = integralFirstFiniteValues[column]; + } else { + // Only non-finite values exist; every area is undefined and the earliest point wins. + return WindowRow.of(bucket, 0); + } + + WindowState lookaheadWindow = window.nextFinite[column]; + PointBuffer lookahead; + if (lookaheadWindow != null) { + lookahead = lookaheadWindow.buffers[column]; + } else if (finishing && hasLastFinite[column]) { + // No later bucket carries a finite point: C is the last finite eligible point. + lookahead = singlePoint(lastFiniteTimes[column], lastFiniteValues[column], column); + } else { + return WindowRow.of(bucket, 0); + } + + int pick = + selectBucketPoint( + bucket.times, + bucket.values, + bucket.integralValues, + 0, + bucket.size(), + anchorTime, + anchorValue, + integralAnchor, + lookahead.times, + lookahead.values, + lookahead.integralValues, + 0, + lookahead.size()); + if (!isFiniteValue(bucket.values, bucket.integralValues, pick)) { + // The bucket has no finite candidate; return its earliest point and keep A unchanged. + return WindowRow.of(bucket, 0); + } + return updateAnchor(bucket, pick, column); + } + + private WindowRow updateAnchor(PointBuffer bucket, int index, int column) { + WindowRow row = WindowRow.of(bucket, index); + hasAnchor[column] = true; + anchorTimes[column] = row.time; + anchorValues[column] = row.value; + integralAnchorValues[column] = row.integral; + return row; + } + } + + private static final class TimeWindowLTTBDataProcessor + extends AbstractWindowLTTBDataProcessor { + private final long origin; + private boolean nextWindowStartInitialized = false; + private boolean windowsExhausted; + private long nextWindowStart; + + private TimeWindowLTTBDataProcessor( + long size, + long slide, + long origin, + Type[] partitionTypes, + ParticipantColumn[] participantColumns, + long maxBufferedBytes) { + super(size, slide, partitionTypes, participantColumns, maxBufferedBytes); + this.origin = origin; + } + + @Override + protected long position(long time) { + return time; + } + + @Override + protected void processRecord(Record input, long time) { + if (!windowsExhausted) { + long firstCandidateStart = getFirstWindowStart(time); + if (!nextWindowStartInitialized || nextWindowStart < firstCandidateStart) { + nextWindowStart = firstCandidateStart; + nextWindowStartInitialized = true; + } + + if (!windowsExhausted && nextWindowStart <= time) { + if (time > Long.MAX_VALUE - size) { + // Check the latest aligned end even when this row has no values. + long lastStart = time - (time - nextWindowStart) % slide; + if (lastStart > Long.MAX_VALUE - size) { + throw windowBoundaryOverflow(); + } + } + WindowsForRow windows = windowsForRow(input); + if (windows == WindowsForRow.NONE) { + return; + } + while (nextWindowStart <= time + && (windows == WindowsForRow.ALL || activeWindows.isEmpty())) { + activeWindows.addLast( + new TimeWindowState(newWindowBuffers(), nextWindowStart, nextWindowStart + size)); + if (nextWindowStart > Long.MAX_VALUE - slide) { + windowsExhausted = true; + break; + } + nextWindowStart += slide; + } + } + } + + collectIntoWindows(time, input, time); + } + + /** First aligned start whose window ends strictly after the current timestamp. */ + private long getFirstWindowStart(long time) { + try { + long distance = Math.subtractExact(Math.subtractExact(time, origin), size); + long steps = Math.addExact(Math.floorDiv(distance, slide), 1); + return Math.addExact(origin, Math.multiplyExact(steps, slide)); + } catch (ArithmeticException e) { + // Only intermediate arithmetic may overflow, e.g. time near Long.MIN_VALUE. + // Fall back to exact arithmetic before deciding whether the actual boundary is valid. + BigInteger step = BigInteger.valueOf(slide); + BigInteger[] quotientAndRemainder = + BigInteger.valueOf(time) + .subtract(BigInteger.valueOf(origin)) + .subtract(BigInteger.valueOf(size)) + .divideAndRemainder(step); + BigInteger steps = quotientAndRemainder[0]; + if (quotientAndRemainder[1].signum() >= 0) { + steps = steps.add(BigInteger.ONE); + } + BigInteger start = BigInteger.valueOf(origin).add(steps.multiply(step)); + if (start.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { + // The input lies in a gap and the next aligned window is beyond the time domain. + windowsExhausted = true; + return Long.MAX_VALUE; + } + try { + return start.longValueExact(); + } catch (ArithmeticException overflow) { + throw windowBoundaryOverflow(); + } + } + } + + private SemanticException windowBoundaryOverflow() { + return new SemanticException( + CommonMessages.EXCEPTION_LTTB_WINDOW_BOUNDARIES_EXCEED_THE_TIMESTAMP_RANGE_7C0FC7E2); + } + } + + private static final class CountWindowLTTBDataProcessor + extends AbstractWindowLTTBDataProcessor { + private long rowCount = 0; + private long nextWindowIndex = 0; + + private CountWindowLTTBDataProcessor( + long size, + long slide, + Type[] partitionTypes, + ParticipantColumn[] participantColumns, + long maxBufferedBytes) { + super(size, slide, partitionTypes, participantColumns, maxBufferedBytes); + } + + @Override + protected long position(long time) { + return rowCount; + } + + @Override + protected void processRecord(Record input, long time) { + long position = rowCount++; + long lastIndex = position / slide; + if (lastIndex * slide > Long.MAX_VALUE - size) { + throw new SemanticException( + CommonMessages.EXCEPTION_LTTB_COUNT_WINDOW_BOUNDARIES_EXCEED_THE_INT64_RANGE_5BC980CA); + } + + if (nextWindowIndex <= lastIndex) { + WindowsForRow windows = windowsForRow(input); + if (windows == WindowsForRow.NONE) { + return; + } + // A NULL prefix may span many starts. Materialize only windows still containing this row, + // keeping their indexes on the original grid (including windows that emitted no rows). + long firstIndex = position < size ? 0 : (position - size) / slide + 1; + nextWindowIndex = Math.max(nextWindowIndex, firstIndex); + while (nextWindowIndex <= lastIndex + && (windows == WindowsForRow.ALL || activeWindows.isEmpty())) { + long end = nextWindowIndex * slide + size; + activeWindows.addLast(new CountWindowState(newWindowBuffers(), end, nextWindowIndex++)); + } + } + + collectIntoWindows(position, input, time); + } + } +} diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBNumericBoundaryTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBNumericBoundaryTest.java new file mode 100644 index 0000000000000..74fdf64a4d8e3 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBNumericBoundaryTest.java @@ -0,0 +1,387 @@ +/* + * 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.commons.udf.builtin.relational.tvf; + +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; +import org.apache.iotdb.udf.api.type.Type; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.read.common.block.column.DoubleColumnBuilder; +import org.apache.tsfile.read.common.block.column.LongColumnBuilder; +import org.junit.Test; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class LTTBNumericBoundaryTest { + + @Test + public void testIntegralAreasSurviveCancellation() { + // The doubled areas are 1 and 3. Rounding the two cross-products separately gives 1 and 0. + // The larger scale also forces the products beyond the range of long. + for (long scale : new long[] {1L << 28, 1L << 34}) { + long[] times = {0, 1, scale - 2, scale + 1}; + Long[][] values = {{0L}, {1L}, {scale - 3}, {scale}}; + long[] expected = {0, scale - 2, scale + 1}; + assertArrayEquals(expected, longValues(sample("TARGET_COUNT", 3, 3, 0, times, values)[1])); + assertArrayEquals(expected, longValues(sample("COUNT_WINDOW", 4, 4, 0, times, values)[1])); + assertArrayEquals( + expected, longValues(sample("TIME_WINDOW", scale + 2, scale + 2, 0, times, values)[2])); + } + } + + @Test + public void testInt64TargetCountPreservesPeakAtLargeBaselines() { + Long[][] values = {{0L}, {1L}, {8L}, {2L}, {0L}, {0L}}; + for (long offset : new long[] {0, 1L << 60, Long.MIN_VALUE, Long.MAX_VALUE - 8}) { + Column[] output = sample("TARGET_COUNT", 3, 3, 0, times(6), translate(values, offset)); + assertArrayEquals(new long[] {0, 2, 5}, longValues(output[1])); + assertArrayEquals(new long[] {offset, offset + 8, offset}, longValues(output[2])); + } + } + + @Test + public void testInt64TargetCountUsesRelativeNextBucketAverage() { + Long[][] values = {{0L}, {1L}, {8L}, {2L}, {0L}, {0L}, {9L}, {1L}, {3L}, {0L}}; + long[][] expected = {{0, 6, 9}, {0, 2, 6, 9}, {0, 2, 4, 6, 9}}; + for (long offset : new long[] {1L << 60, Long.MIN_VALUE, Long.MAX_VALUE - 9}) { + for (int n = 3; n <= 5; n++) { + Column[] output = sample("TARGET_COUNT", n, n, 0, times(10), translate(values, offset)); + assertArrayEquals(expected[n - 3], longValues(output[1])); + for (int row = 0; row < output[1].getPositionCount(); row++) { + int selectedTime = (int) output[1].getLong(row); + assertEquals(offset + values[selectedTime][0], output[2].getLong(row)); + } + } + } + } + + @Test + public void testInt64WindowsKeepIndependentAnchorsAcrossNullBuckets() { + Long[][] values = { + {0L, 0L}, {1L, 0L}, {2L, 0L}, + {null, 0L}, {null, 1L}, {null, 2L}, + {null, null}, {null, null}, {null, null}, + {0L, 0L}, {0L, 0L}, {0L, 0L} + }; + long[] offsets = {1L << 60, Long.MIN_VALUE}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + for (long slide : new long[] {1, 3, 4}) { + Column[] expected = sample(mode, 3, slide, 0, times(12), values); + Column[] actual = sample(mode, 3, slide, 0, times(12), translate(values, offsets)); + int firstValueColumn = mode.equals("TIME_WINDOW") ? 3 : 2; + for (int column = 0; column < actual.length; column++) { + assertEquals(expected[column].getPositionCount(), actual[column].getPositionCount()); + for (int row = 0; row < actual[column].getPositionCount(); row++) { + assertEquals(expected[column].isNull(row), actual[column].isNull(row)); + if (!actual[column].isNull(row)) { + long offset = + column >= firstValueColumn && (column - firstValueColumn) % 2 == 0 + ? offsets[(column - firstValueColumn) / 2] + : 0; + assertEquals(expected[column].getLong(row) + offset, actual[column].getLong(row)); + } + } + } + } + } + } + + @Test + public void testInt64DifferencesSpanningLongRangeDoNotWrap() { + Long[][] values = { + {Long.MIN_VALUE}, {0L}, {Long.MAX_VALUE}, {0L}, {Long.MIN_VALUE}, {Long.MIN_VALUE} + }; + Column[] target = sample("TARGET_COUNT", 3, 3, 0, times(6), values); + assertArrayEquals(new long[] {0, 2, 5}, longValues(target[1])); + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + Column[] output = sample(mode, 2, 2, 0, times(6), values); + // F(t0) and L(t5) are reported by the first and the last window, and the windows in between + // keep their own picks, so the time values span the exact int64 range without wrapping. + assertArrayEquals(new long[] {0L, 1L, 2L, 4L, 5L}, longValues(output[output.length - 2])); + assertArrayEquals( + new long[] {Long.MIN_VALUE, 0L, Long.MAX_VALUE, Long.MIN_VALUE, Long.MIN_VALUE}, + longValues(output[output.length - 1])); + } + } + + @Test + public void testCollinearDoublesKeepEarliestCandidate() { + // The lookahead mean is (25/3, 25). Rounding 25/3 before scoring would select t=5. + long[] time = {0, 1, 2, 5, 6, 7, 12, 13}; + Double[][] values = {{0.0}, {3.0}, {6.0}, {15.0}, {18.0}, {21.0}, {36.0}, {39.0}}; + for (String mode : new String[] {"TARGET_COUNT", "COUNT_WINDOW"}) { + Column[] output = sample(mode, 4, 4, 0, time, values, Type.DOUBLE); + assertArrayEquals(new long[] {0, 1, 6, 13}, longValues(output[1])); + } + } + + @Test + public void testFloatingLookaheadSurvivesCancellation() { + // The lookahead values sum to 1. Losing that 1 makes the points at t=1,2,3 appear tied. + double[] values = {0, 0, 0, 0, 1e16, 1, -1e16, 0}; + for (String mode : new String[] {"TARGET_COUNT", "COUNT_WINDOW"}) { + Column[] output = sampleFloating(mode, 4, values); + assertArrayEquals(new long[] {0, 3, 4, 7}, longValues(output[1])); + } + } + + @Test + public void testFiniteDoublesPreserveSelectionsWhenAreasOverflow() { + assertFloatingScaleInvariant(new double[] {0, 4, 8, 2, 0, 0}); + } + + @Test + public void testFiniteDoublesPreserveSelectionsWhenLookaheadSumOverflows() { + assertFloatingScaleInvariant(new double[] {0, 4, 8, 7, 7, 0}); + } + + @Test + public void testFiniteDoublesPreserveSelectionsWhenDifferencesOverflow() { + assertFloatingScaleInvariant(new double[] {-8, 4, 8, 2, -8, -8}); + } + + @Test + public void testOverflowFallbackKeepsEarliestAreaTie() { + Column[] output = + sampleFloating("TARGET_COUNT", 3, new double[] {0, 1.6e308, 1.6e308, 0, 0, 0}); + assertArrayEquals(new long[] {0, 1, 5}, longValues(output[1])); + } + + @Test(timeout = 5000) + public void testCountWindowRejectsUnrepresentableEnd() { + SemanticException failure = + assertThrows( + SemanticException.class, + () -> + sample("COUNT_WINDOW", Long.MAX_VALUE, 1, 0, times(2), new Long[][] {{1L}, {2L}})); + assertEquals( + CommonMessages.EXCEPTION_LTTB_COUNT_WINDOW_BOUNDARIES_EXCEED_THE_INT64_RANGE_5BC980CA, + failure.getMessage()); + } + + @Test(timeout = 5000) + public void testCountWindowWithLargeSlideDoesNotCreateExtraWindow() { + Column[] output = + sample( + "COUNT_WINDOW", Long.MAX_VALUE, Long.MAX_VALUE, 0, times(2), new Long[][] {{1L}, {2L}}); + // Two rows: F(t0) and L(t1) of the single window that received input. + assertArrayEquals(new long[] {0, 0}, longValues(output[0])); + assertArrayEquals(new long[] {0, 1}, longValues(output[1])); + } + + private static void assertFloatingScaleInvariant(double[] values) { + double[] scaled = new double[values.length]; + for (int i = 0; i < values.length; i++) { + scaled[i] = values[i] * 2e307; + } + for (String mode : new String[] {"TARGET_COUNT", "COUNT_WINDOW", "TIME_WINDOW"}) { + for (int size : new int[] {3, 4}) { + Column[] expected = sampleFloating(mode, size, values); + Column[] actual = sampleFloating(mode, size, scaled); + int timeColumn = actual.length - 2; + assertArrayEquals( + mode + ": " + size, longValues(expected[timeColumn]), longValues(actual[timeColumn])); + for (int row = 0; row < actual[timeColumn].getPositionCount(); row++) { + assertEquals( + scaled[(int) actual[timeColumn].getLong(row)], + actual[timeColumn + 1].getDouble(row), + 0.0); + } + } + } + } + + private static Column[] sampleFloating(String mode, long size, double[] values) { + Double[][] rows = new Double[values.length][1]; + for (int i = 0; i < values.length; i++) { + rows[i][0] = values[i]; + } + return sample(mode, size, size, 0, times(values.length), rows, Type.DOUBLE); + } + + @Test(timeout = 5000) + public void testTimeWindowRejectsUnrepresentableEnd() { + assertWindowOverflow(2, 2, 0, Long.MAX_VALUE - 1); + assertWindowOverflow(1, 1, 0, Long.MAX_VALUE); + } + + @Test(timeout = 5000) + public void testTimeWindowRejectsUnrepresentableStart() { + assertWindowOverflow(3, 3, 0, Long.MIN_VALUE); + } + + @Test(timeout = 5000) + public void testTimeWindowAllowsIntermediateOverflow() { + for (long origin : new long[] {0, Long.MIN_VALUE, Long.MAX_VALUE - 1}) { + Column[] output = + sample("TIME_WINDOW", 2, 2, origin, new long[] {Long.MIN_VALUE}, new Long[][] {{7L}}); + assertEquals(1, output[0].getPositionCount()); + assertEquals(Long.MIN_VALUE, output[0].getLong(0)); + assertEquals(Long.MIN_VALUE + 2, output[1].getLong(0)); + assertEquals(Long.MIN_VALUE, output[2].getLong(0)); + assertEquals(7L, output[3].getLong(0)); + } + } + + @Test(timeout = 5000) + public void testTimeWindowStopsAdvancingPastLongMax() { + Column[] output = + sample( + "TIME_WINDOW", + 2, + 3, + Long.MAX_VALUE - 2, + new long[] {Long.MAX_VALUE - 2, Long.MAX_VALUE - 1, Long.MAX_VALUE}, + new Long[][] {{0L}, {8L}, {1L}}); + // F(Long.MAX_VALUE - 2) and L(Long.MAX_VALUE - 1) are two rows of the same window; the last + // input lies in the following gap, so it belongs to no window. + assertEquals(2, output[0].getPositionCount()); + assertEquals(Long.MAX_VALUE - 2, output[0].getLong(0)); + assertEquals(Long.MAX_VALUE, output[1].getLong(0)); + assertEquals(Long.MAX_VALUE - 2, output[2].getLong(0)); + assertEquals(0L, output[3].getLong(0)); + assertEquals(Long.MAX_VALUE - 1, output[2].getLong(1)); + assertEquals(8L, output[3].getLong(1)); + } + + @Test(timeout = 5000) + public void testTimeWindowSkipsGapBeforeUnrepresentableNextStart() { + Column[] output = + sample( + "TIME_WINDOW", + 2, + 3, + Long.MAX_VALUE - 2, + new long[] {Long.MAX_VALUE}, + new Long[][] {{1L}}); + assertEquals(0, output[0].getPositionCount()); + } + + private static void assertWindowOverflow(long size, long slide, long origin, long time) { + SemanticException failure = + assertThrows( + SemanticException.class, + () -> + sample("TIME_WINDOW", size, slide, origin, new long[] {time}, new Long[][] {{1L}})); + assertEquals( + CommonMessages.EXCEPTION_LTTB_WINDOW_BOUNDARIES_EXCEED_THE_TIMESTAMP_RANGE_7C0FC7E2, + failure.getMessage()); + } + + private static long[] longValues(Column column) { + long[] values = new long[column.getPositionCount()]; + for (int i = 0; i < values.length; i++) { + values[i] = column.getLong(i); + } + return values; + } + + private static long[] times(int count) { + long[] times = new long[count]; + for (int i = 0; i < count; i++) { + times[i] = i; + } + return times; + } + + private static Long[][] translate(Long[][] values, long... offsets) { + Long[][] translated = new Long[values.length][offsets.length]; + for (int i = 0; i < values.length; i++) { + for (int j = 0; j < offsets.length; j++) { + translated[i][j] = values[i][j] == null ? null : Math.addExact(values[i][j], offsets[j]); + } + } + return translated; + } + + private static Column[] sample( + String mode, long size, long slide, long origin, long[] times, Long[][] values) { + return sample(mode, size, slide, origin, times, values, Type.INT64); + } + + private static Column[] sample( + String mode, long size, long slide, long origin, long[] times, Number[][] values, Type type) { + int columns = values[0].length; + MapTableFunctionHandle handle = + new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, mode) + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "") + .addProperty( + LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, + String.join(",", Collections.nCopies(columns, type.name()))) + .addProperty(LTTBTableFunction.N_PARAMETER_NAME, size) + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, size) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, slide) + .addProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME, origin) + .build(); + TableFunctionDataProcessor processor = + new LTTBTableFunction().getProcessorProvider(handle).getDataProcessor(); + List builders = new ArrayList<>(); + int outputColumns = (mode.equals("TIME_WINDOW") ? 2 : 1) + 2 * columns; + for (int i = 0; i < outputColumns; i++) { + int firstValueColumn = mode.equals("TIME_WINDOW") ? 3 : 2; + builders.add( + type == Type.DOUBLE && i >= firstValueColumn && (i - firstValueColumn) % 2 == 0 + ? new DoubleColumnBuilder(null, 16) + : new LongColumnBuilder(null, 16)); + } + try { + for (int i = 0; i < times.length; i++) { + processor.process(record(times[i], values[i]), builders, null); + } + processor.finish(builders, null); + return builders.stream().map(ColumnBuilder::build).toArray(Column[]::new); + } finally { + processor.beforeDestroy(); + } + } + + private static Record record(long time, Number[] values) { + return (Record) + Proxy.newProxyInstance( + Record.class.getClassLoader(), + new Class[] {Record.class}, + (proxy, method, arguments) -> { + int index = (int) arguments[0]; + switch (method.getName()) { + case "getLong": + return index == 0 ? time : values[index - 1].longValue(); + case "getDouble": + return values[index - 1].doubleValue(); + case "isNull": + return index != 0 && values[index - 1] == null; + default: + throw new UnsupportedOperationException(method.getName()); + } + }); + } +} diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBRegressionTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBRegressionTest.java new file mode 100644 index 0000000000000..f0717da5f6c33 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBRegressionTest.java @@ -0,0 +1,471 @@ +/* + * 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.commons.udf.builtin.relational.tvf; + +import org.apache.iotdb.commons.conf.CommonConfig; +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; +import org.apache.iotdb.commons.i18n.QueryMessages; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.read.common.block.column.DoubleColumnBuilder; +import org.apache.tsfile.read.common.block.column.LongColumnBuilder; +import org.junit.Test; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class LTTBRegressionTest { + private static final long NANOSECOND_EPOCH = 1_780_000_000_000_000_000L; + + @Test + public void testTargetCountIsInvariantUnderTimestampTranslation() { + double[] values = {0, 1, 8, 2, 0, 0, 9, 1, -3, 0}; + long[] times = new long[values.length]; + for (int i = 0; i < times.length; i++) { + times[i] = i; + } + for (int n : new int[] {3, 4, 5}) { + int[] expected = LTTBTableFunction.selectTargetCount(times, values, times.length, n); + for (long origin : new long[] {NANOSECOND_EPOCH, Long.MIN_VALUE, Long.MAX_VALUE - 10}) { + long[] shifted = Arrays.stream(times).map(time -> time + origin).toArray(); + assertArrayEquals( + expected, LTTBTableFunction.selectTargetCount(shifted, values, shifted.length, n)); + } + } + } + + @Test + public void testWindowsAreInvariantUnderTimestampTranslation() { + Double[][] rows = {{0.0}, {1.0}, {8.0}, {2.0}, {0.0}, {0.0}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + for (long slide : new long[] {1, 2, 3}) { + List expected = sample(mode, 2, slide, 0, rows); + List actual = sample(mode, 2, slide, NANOSECOND_EPOCH, rows); + int timeIndex = actual.size() - 2; + assertEquals( + expected.get(timeIndex).getPositionCount(), actual.get(timeIndex).getPositionCount()); + for (int i = 0; i < actual.get(timeIndex).getPositionCount(); i++) { + assertEquals( + expected.get(timeIndex).build().getLong(i), + actual.get(timeIndex).build().getLong(i) - NANOSECOND_EPOCH); + assertEquals( + expected.get(timeIndex + 1).build().getDouble(i), + actual.get(timeIndex + 1).build().getDouble(i), + 0.0); + } + } + } + } + + @Test + public void testWindowsSkipNullBucketsIndependentlyPerColumn() { + Double[][] rows = { + {0.0, 0.0}, {1.0, 0.0}, {2.0, 0.0}, + {null, 0.0}, {null, 1.0}, {null, 2.0}, + {null, null}, {null, null}, {null, null}, + {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} + }; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 3, 3, 0, rows); + int timeIndex = mode.equals("TIME_WINDOW") ? 2 : 1; + // W0 reports F(t0) and its pick(t2); W1 has no eligible point for the first column, so the + // first column emits no cell there while the second column keeps its own chain; the last + // window reports its pick and then L(t11). + assertEquals(5, out.get(0).getPositionCount()); + assertEquals(0, out.get(timeIndex).build().getLong(0)); + assertEquals(2, out.get(timeIndex).build().getLong(1)); + assertTrue(out.get(timeIndex).build().isNull(2)); + assertEquals(9, out.get(timeIndex).build().getLong(3)); + assertEquals(11, out.get(timeIndex).build().getLong(4)); + assertEquals(0, out.get(timeIndex + 2).build().getLong(0)); + assertEquals(2, out.get(timeIndex + 2).build().getLong(1)); + assertEquals(5, out.get(timeIndex + 2).build().getLong(2)); + assertEquals(9, out.get(timeIndex + 2).build().getLong(3)); + assertEquals(11, out.get(timeIndex + 2).build().getLong(4)); + } + } + + @Test + public void testTrailingNullWindowsUseFinalNonemptyBucketFallback() { + Double[][] rows = {{0.0}, {5.0}, {0.0}, {null}, {null}, {null}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 3, 3, 0, rows); + int timeIndex = out.size() - 2; + // W0 reports F(t0), its pick(t1) and L(t2); W1 is all NULL and emits no row. + assertEquals(3, out.get(timeIndex).getPositionCount()); + assertEquals(0, out.get(timeIndex).build().getLong(0)); + assertEquals(1, out.get(timeIndex).build().getLong(1)); + assertEquals(2, out.get(timeIndex).build().getLong(2)); + assertEquals(5.0, out.get(timeIndex + 1).build().getDouble(1), 0.0); + } + } + + /** + * SIZE defines a bucket, not the input range of a separate standard LTTB invocation: the buckets + * share one anchor chain per partition and column, so an overlapping window continues from the + * point the preceding window selected instead of restarting at its own first point. Bucket {@code + * [1,4)} selecting {@code t=1} is only reachable with a chained anchor: with a fresh anchor at + * its own first point the largest triangle of that bucket would be {@code t=2} instead. Every + * window emits exactly one row, so the overlapping run yields one row per window. + */ + @Test + public void testOverlappingWindowsContinueTheAnchorChain() { + Double[][] rows = {{0.0}, {1.0}, {8.0}, {2.0}, {0.0}, {0.0}}; + + // Count buckets [0,3), [1,4), ..., [5,8) over six rows. F(t0) is reported by the first bucket + // and L(t5) by the last one, so the overlap yields seven rows: W0 t0,t2; W1 t1; W2 t2; W3 t3; + // W4 t4; W5 t4,t5. W1 selecting t=1 continues from the point W0 selected; a fresh anchor at its + // own first point would pick t=2 instead. + List countWindow = sample("COUNT_WINDOW", 3, 1, 0, rows); + Column countPicks = countWindow.get(countWindow.size() - 2).build(); + assertEquals(7, countPicks.getPositionCount()); + assertEquals(0, countPicks.getLong(0)); + assertEquals(2, countPicks.getLong(1)); + assertEquals(1, countPicks.getLong(2)); + assertEquals(2, countPicks.getLong(3)); + assertEquals(3, countPicks.getLong(4)); + assertEquals(4, countPicks.getLong(5)); + assertEquals(5, countPicks.getLong(6)); + + // Time buckets [0,3), [1,4), ... with SLIDE = 1 a row also opens the buckets that started + // before the first timestamp but have not ended yet, so eight buckets cover the six rows and + // keep the same one-chain rule. W0 reports t0 and its pick t2, W1 picks t1 from the chained + // anchor, and the last bucket reports only L(t5) because its own bucket holds just t4. + List timeWindow = sample("TIME_WINDOW", 3, 1, 0, rows); + Column timePicks = timeWindow.get(timeWindow.size() - 2).build(); + assertEquals(8, timePicks.getPositionCount()); + long[] expectedTimes = {0, 1, 2, 1, 2, 3, 4, 5}; + for (int i = 0; i < expectedTimes.length; i++) { + assertEquals(expectedTimes[i], timePicks.getLong(i)); + } + } + + /** + * With {@code SLIDE > SIZE} the gaps between windows belong to no bucket. A row in a gap is + * neither collected into a bucket nor eligible as {@code F} or {@code L}, because only points + * that fall in a window can be reported. Here the windows are {@code [0,2)} and {@code [3,5)}; t5 + * falls in the gap {@code [5,6)} and is therefore dropped, while the last point that does fall in + * a window is t4. + */ + @Test + public void testTimeWindowGapRowsAreDropped() { + Double[][] rows = {{0.0}, {1.0}, {2.0}, {3.0}, {4.0}, {5.0}}; + List out = sample("TIME_WINDOW", 2, 3, 0, rows); + Column picks = out.get(out.size() - 2).build(); + // The first window holds t0 and t1: it reports F(t0) and picks t1. The second holds t3 and + // t4: it picks t3 and reports L(t4), the last point that falls in a window. + long[] expected = {0, 1, 3, 4}; + assertEquals(expected.length, picks.getPositionCount()); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], picks.getLong(i)); + } + } + + /** + * Both endpoints are buckets of their own, so two eligible points in one window emit two rows + * even though the window bucket between them is empty: {@code F} and then {@code L}. + */ + @Test + public void testTwoEligiblePointsEmitTheirOwnRows() { + Double[][] rows = {{0.0}, {8.0}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 3, 3, 0, rows); + int timeIndex = out.size() - 2; + assertEquals(2, out.get(timeIndex).getPositionCount()); + assertEquals(0, out.get(timeIndex).build().getLong(0)); + assertEquals(0.0, out.get(timeIndex + 1).build().getDouble(0), 0.0); + assertEquals(1, out.get(timeIndex).build().getLong(1)); + assertEquals(8.0, out.get(timeIndex + 1).build().getDouble(1), 0.0); + } + } + + /** + * A non-finite point stays eligible, but it never serves as {@code A} or {@code C}: the last + * window looks ahead to the last finite eligible point instead of the non-finite last point, so + * the selections do not depend on whether the final value is finite. + */ + @Test + public void testWindowModeIgnoresNonFiniteValuesAsTriangleVertices() { + Double[][] finiteTail = {{0.0}, {5.0}, {1.0}, {2.0}, {9.0}, {3.0}, {0.0}}; + Double[][] nonFiniteTail = {{0.0}, {5.0}, {1.0}, {2.0}, {9.0}, {3.0}, {Double.NaN}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + int timeIndex = mode.equals("TIME_WINDOW") ? 2 : 1; + List finite = sample(mode, 3, 3, 0, finiteTail); + List nonFinite = sample(mode, 3, 3, 0, nonFiniteTail); + // W0 reports F(t0) and picks t1; W1 picks t4; the last window reports L. The last row of + // the non-finite run is the non-finite point itself, which is still returned. + assertEquals(4, nonFinite.get(timeIndex).getPositionCount()); + assertEquals(0, nonFinite.get(timeIndex).build().getLong(0)); + assertEquals(1, nonFinite.get(timeIndex).build().getLong(1)); + assertEquals(4, nonFinite.get(timeIndex).build().getLong(2)); + assertEquals(6, nonFinite.get(timeIndex).build().getLong(3)); + assertEquals(5.0, nonFinite.get(timeIndex + 1).build().getDouble(1), 0.0); + assertEquals(9.0, nonFinite.get(timeIndex + 1).build().getDouble(2), 0.0); + assertTrue(Double.isNaN(nonFinite.get(timeIndex + 1).build().getDouble(3))); + for (int i = 0; i < 3; i++) { + assertEquals( + finite.get(timeIndex).build().getLong(i), nonFinite.get(timeIndex).build().getLong(i)); + } + } + } + + /** + * A column whose only eligible point in a window is non-finite still returns it as the pick of + * that window, and the columns stay aligned by output position. + */ + @Test + public void testWindowModeReturnsNonFiniteCandidate() { + Double[][] rows = {{0.0, 1.0}, {1.0, 2.0}, {2.0, 3.0}, {3.0, Double.NaN}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 2, 2, 0, rows); + int timeIndex = mode.equals("TIME_WINDOW") ? 2 : 1; + // W0 reports F(t0) for both columns and picks t1; W1 picks t2 and reports L(t3). The second + // column's last eligible point is non-finite, so it is returned as L of the last window. + assertEquals(4, out.get(timeIndex).getPositionCount()); + assertEquals(0, out.get(timeIndex).build().getLong(0)); + assertEquals(1, out.get(timeIndex).build().getLong(1)); + assertEquals(2, out.get(timeIndex).build().getLong(2)); + assertEquals(3, out.get(timeIndex).build().getLong(3)); + assertEquals(0.0, out.get(timeIndex + 1).build().getDouble(0), 0.0); + assertEquals(1.0, out.get(timeIndex + 1).build().getDouble(1), 0.0); + assertEquals(2.0, out.get(timeIndex + 1).build().getDouble(2), 0.0); + assertEquals(3.0, out.get(timeIndex + 1).build().getDouble(3), 0.0); + assertEquals(1.0, out.get(timeIndex + 3).build().getDouble(0), 0.0); + assertEquals(2.0, out.get(timeIndex + 3).build().getDouble(1), 0.0); + assertEquals(3.0, out.get(timeIndex + 3).build().getDouble(2), 0.0); + assertTrue(Double.isNaN(out.get(timeIndex + 3).build().getDouble(3))); + } + } + + /** + * A window without any eligible point emits no row, like M4: the number of rows is the largest + * number of points selected by a participant column, so an all-NULL partition emits nothing. + */ + @Test + public void testWindowWithNoEligiblePointsEmitsNoRow() { + Double[][] rows = {{null}, {null}, {null}, {null}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 2, 2, 0, rows); + int timeIndex = out.size() - 2; + assertEquals(0, out.get(timeIndex).getPositionCount()); + assertEquals(0, out.get(timeIndex + 1).getPositionCount()); + } + } + + /** + * A window whose bucket has no finite candidate returns its earliest point without moving {@code + * A}, so the next window is still scored against the last finite pick. + */ + @Test + public void testWindowModeNonFiniteBucketKeepsAnchor() { + Double[][] rows = {{0.0}, {1.0}, {Double.NaN}, {Double.NaN}, {0.5}, {9.0}, {3.0}, {0.0}}; + for (String mode : new String[] {"COUNT_WINDOW", "TIME_WINDOW"}) { + List out = sample(mode, 2, 2, 0, rows); + int timeIndex = mode.equals("TIME_WINDOW") ? 2 : 1; + // W0 reports F(t0) and picks t1; W1 holds only NaN, returns t2 and keeps A = t1; W2 scores + // t4 (area 8.5) and t5 (area 32) against A = t1 and C = t6; W3 picks t6 and reports L(t7). + long[] expected = {0, 1, 2, 5, 6, 7}; + assertEquals(expected.length, out.get(timeIndex).getPositionCount()); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], out.get(timeIndex).build().getLong(i)); + } + } + } + + @Test + public void testNullTimestampIsRejectedAndEpochZeroIsPreserved() { + for (String mode : new String[] {"TARGET_COUNT", "COUNT_WINDOW", "TIME_WINDOW"}) { + TableFunctionDataProcessor processor = processor(mode, 3, 3, 0, 1); + try { + processor.process(record(null, 1.0), Collections.emptyList(), null); + fail("Expected a null time column to be rejected in " + mode); + } catch (SemanticException expected) { + assertEquals(QueryMessages.TIME_COLUMN_SHOULD_NOT_BE_NULL, expected.getMessage()); + } finally { + processor.beforeDestroy(); + } + + List output = sample(mode, 3, 3, 0, new Double[][] {{1.0}}); + int timeIndex = output.size() - 2; + assertEquals(1, output.get(timeIndex).getPositionCount()); + assertEquals(0L, output.get(timeIndex).build().getLong(0)); + } + } + + @Test + public void testTargetColumnsShareMemoryBudget() { + TableFunctionDataProcessor processor = processor("TARGET_COUNT", 3, 3, 0, 8); + try { + for (int i = 0; i < 350_000; i++) { + // timestamps must be unique within the partition, so advance the input time + processor.process( + record((long) i, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0), + Collections.emptyList(), + null); + } + fail( + "Expected a controlled memory-limit exception before buffering 350000 rows in eight columns"); + } catch (SemanticException expected) { + // Match the same localized message as the window-memory regression suite. + assertEquals( + String.format( + CommonMessages + .EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D, + LTTBTableFunction.DEFAULT_MAX_BUFFER_BYTES), + expected.getMessage()); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testWindowColumnStateCountsTowardMemoryBudget() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + long budget = 32 * 1024L; + try { + config.setLttbBufferSize(budget); + for (String mode : Arrays.asList("COUNT_WINDOW", "TIME_WINDOW")) { + SemanticException exception = + assertThrows(SemanticException.class, () -> processor(mode, 1, 1, 0, 512)); + assertEquals( + String.format( + CommonMessages + .EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D, + budget), + exception.getMessage()); + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + @Test + public void testOverlappingWindowsWithManyNullColumnsFitMemoryBudget() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(4L * 1024 * 1024); + Double[][] dense = new Double[120][1]; + Double[][] sparse = new Double[120][128]; + for (int i = 0; i < dense.length; i++) { + dense[i][0] = (double) i; + sparse[i][0] = dense[i][0]; + } + List expected = sample("COUNT_WINDOW", 120, 1, 0, dense); + List actual = sample("COUNT_WINDOW", 120, 1, 0, sparse); + int rows = expected.get(0).getPositionCount(); + assertEquals(121, rows); + for (int i = 0; i < actual.size(); i++) { + Column column = actual.get(i).build(); + assertEquals(rows, column.getPositionCount()); + Column reference = i < expected.size() ? expected.get(i).build() : null; + for (int row = 0; row < rows; row++) { + if (reference == null) { + assertTrue(column.isNull(row)); + } else if (i == 2) { + assertEquals(reference.getDouble(row), column.getDouble(row), 0.0); + } else { + assertEquals(reference.getLong(row), column.getLong(row)); + } + } + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + private static List sample( + String mode, long size, long slide, long origin, Double[][] rows) { + int columns = rows[0].length; + TableFunctionDataProcessor processor = processor(mode, size, slide, origin, columns); + List builders = new ArrayList<>(); + builders.add(new LongColumnBuilder(null, 16)); + if (mode.equals("TIME_WINDOW")) { + builders.add(new LongColumnBuilder(null, 16)); + } + for (int i = 0; i < columns; i++) { + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + } + try { + for (int i = 0; i < rows.length; i++) { + processor.process(record(origin + i, rows[i]), builders, null); + } + processor.finish(builders, null); + return builders; + } finally { + processor.beforeDestroy(); + } + } + + private static TableFunctionDataProcessor processor( + String mode, long size, long slide, long origin, int columns) { + MapTableFunctionHandle handle = + new MapTableFunctionHandle.Builder() + .addProperty(LTTBTableFunction.MODE_PROPERTY, mode) + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "") + .addProperty( + LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, + String.join(",", Collections.nCopies(columns, "DOUBLE"))) + .addProperty(LTTBTableFunction.N_PARAMETER_NAME, size) + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, size) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, slide) + .addProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME, origin) + .build(); + return new LTTBTableFunction().getProcessorProvider(handle).getDataProcessor(); + } + + private static Record record(Long time, Double... values) { + // A lightweight row avoids Mockito invocation bookkeeping in the memory-limit test. + return (Record) + Proxy.newProxyInstance( + Record.class.getClassLoader(), + new Class[] {Record.class}, + (proxy, method, arguments) -> { + int index = (int) arguments[0]; + switch (method.getName()) { + case "getLong": + return time == null ? 0L : time; + case "getDouble": + return values[index - 1]; + case "isNull": + return index == 0 ? time == null : values[index - 1] == null; + default: + throw new UnsupportedOperationException(method.getName()); + } + }); + } +} diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunctionTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunctionTest.java new file mode 100644 index 0000000000000..2979b4fe68050 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBTableFunctionTest.java @@ -0,0 +1,370 @@ +/* + * 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.commons.udf.builtin.relational.tvf; + +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; +import org.apache.iotdb.commons.i18n.QueryMessages; +import org.apache.iotdb.udf.api.exception.UDFException; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.TableFunctionAnalysis; +import org.apache.iotdb.udf.api.relational.table.argument.Argument; +import org.apache.iotdb.udf.api.relational.table.argument.ScalarArgument; +import org.apache.iotdb.udf.api.relational.table.argument.TableArgument; +import org.apache.iotdb.udf.api.type.Type; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class LTTBTableFunctionTest { + + @Test + public void testTargetCountPreservesEndpointsAndPeak() { + long[] times = {0, 1, 2, 3, 4, 5}; + double[] values = {0, 1, 8, 2, 0, 0}; + + assertArrayEquals( + new int[] {0, 2, 5}, LTTBTableFunction.selectTargetCount(times, values, 6, 3)); + } + + @Test + public void testTargetCountReturnsAllShortSeries() { + long[] times = {0, 1}; + double[] values = {1, 2}; + + assertArrayEquals(new int[] {0, 1}, LTTBTableFunction.selectTargetCount(times, values, 2, 3)); + } + + @Test + public void testTargetCountBreaksAreaTiesByStableInputOrder() { + long[] times = {0, 1, 2, 3, 4}; + double[] values = {0, 4, 4, 1, 0}; + + assertArrayEquals( + new int[] {0, 1, 4}, LTTBTableFunction.selectTargetCount(times, values, 5, 3)); + } + + @Test + public void testAnalyzeTargetCountOutputSchema() throws UDFException { + LTTBTableFunction function = new LTTBTableFunction(); + TableFunctionAnalysis analysis = function.analyze(targetCountArguments(3L)); + + assertEquals( + "window_index", analysis.getProperColumnSchema().get().getFields().get(0).getName().get()); + assertEquals( + "device", analysis.getProperColumnSchema().get().getFields().get(1).getName().get()); + assertEquals( + "s1_time", analysis.getProperColumnSchema().get().getFields().get(2).getName().get()); + assertEquals("s1", analysis.getProperColumnSchema().get().getFields().get(3).getName().get()); + assertEquals( + Arrays.asList(0, 1, 2), + analysis.getRequiredColumns().get(LTTBTableFunction.DATA_PARAMETER_NAME)); + } + + @Test + public void testAnalyzeRejectsTargetCountBelowThree() throws UDFException { + try { + new LTTBTableFunction().analyze(targetCountArguments(2L)); + fail(); + } catch (SemanticException e) { + // compare against the constant so the test also passes under -P with-zh-locale + assertEquals( + CommonMessages.EXCEPTION_THE_N_ARGUMENT_OF_LTTB_MUST_BE_AT_LEAST_3_29CE2B87, + e.getMessage()); + } + } + + @Test + public void testAnalyzeRejectsNAndSizeTogether() throws UDFException { + Map arguments = targetCountArguments(3L); + arguments.put(LTTBTableFunction.SIZE_PARAMETER_NAME, new ScalarArgument(Type.INT64, 2L)); + try { + new LTTBTableFunction().analyze(arguments); + fail(); + } catch (SemanticException e) { + assertEquals( + CommonMessages + .EXCEPTION_EXACTLY_ONE_OF_THE_N_AND_SIZE_ARGUMENTS_MUST_BE_SPECIFIED_FOR_LTTB_54AF0733, + e.getMessage()); + } + } + + @Test + public void testAnalyzeRejectsTargetCountWithOrigin() throws UDFException { + Map arguments = targetCountArguments(3L); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, new ScalarArgument(Type.TIMESTAMP, 1000L)); + try { + new LTTBTableFunction().analyze(arguments); + fail(); + } catch (SemanticException e) { + // compare against the constant so the test also passes under -P with-zh-locale + assertEquals( + CommonMessages + .EXCEPTION_THE_N_ARGUMENT_OF_LTTB_CANNOT_BE_COMBINED_WITH_THE_SLIDE_OR_ORIGIN_ARGUMENTS_C2FF1FE1, + e.getMessage()); + } + } + + @Test + public void testAnalyzeRejectsOriginInCountWindowMode() throws UDFException { + Map arguments = windowArguments(2L, 2L, false); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, new ScalarArgument(Type.TIMESTAMP, 1000L)); + try { + new LTTBTableFunction().analyze(arguments); + fail(); + } catch (SemanticException e) { + assertEquals( + QueryMessages + .EXCEPTION_THE_ORIGIN_ARGUMENT_IS_ONLY_SUPPORTED_IN_TIME_WINDOW_MODE_B3F358B9, + e.getMessage()); + } + } + + @Test + public void testAnalyzeAcceptsOriginInTimeWindowMode() throws UDFException { + Map arguments = windowArguments(2L, 2L, true); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, new ScalarArgument(Type.TIMESTAMP, 1000L)); + TableFunctionAnalysis analysis = new LTTBTableFunction().analyze(arguments); + MapTableFunctionHandle handle = (MapTableFunctionHandle) analysis.getTableFunctionHandle(); + assertEquals(1000L, handle.getProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME)); + } + + /** + * {@link Long#MIN_VALUE} is a legal timestamp, so it must not be confused with an absent ORIGIN: + * an explicit extreme origin is kept as given, not replaced by the epoch. + */ + @Test + public void testTimeWindowKeepsTheMinimumRepresentableOrigin() throws UDFException { + Map arguments = windowArguments(2L, 2L, true); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, + new ScalarArgument(Type.TIMESTAMP, Long.MIN_VALUE)); + arguments.put( + LTTBTableFunction.ORIGIN_SPECIFIED_PARAMETER_NAME, new ScalarArgument(Type.BOOLEAN, true)); + TableFunctionAnalysis analysis = new LTTBTableFunction().analyze(arguments); + MapTableFunctionHandle handle = (MapTableFunctionHandle) analysis.getTableFunctionHandle(); + assertEquals(Long.MIN_VALUE, handle.getProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME)); + } + + @Test + public void testAnalyzeRejectsMinimumOriginInCountWindowMode() throws UDFException { + Map arguments = windowArguments(2L, 2L, false); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, + new ScalarArgument(Type.TIMESTAMP, Long.MIN_VALUE)); + arguments.put( + LTTBTableFunction.ORIGIN_SPECIFIED_PARAMETER_NAME, new ScalarArgument(Type.BOOLEAN, true)); + try { + new LTTBTableFunction().analyze(arguments); + fail(); + } catch (SemanticException e) { + assertEquals( + QueryMessages + .EXCEPTION_THE_ORIGIN_ARGUMENT_IS_ONLY_SUPPORTED_IN_TIME_WINDOW_MODE_B3F358B9, + e.getMessage()); + } + } + + @Test + public void testTimeWindowWithoutOriginUsesTheEpoch() throws UDFException { + TableFunctionAnalysis analysis = new LTTBTableFunction().analyze(windowArguments(2L, 2L, true)); + MapTableFunctionHandle handle = (MapTableFunctionHandle) analysis.getTableFunctionHandle(); + assertEquals(0L, handle.getProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME)); + } + + @Test + public void testTargetCountKeepsNonFiniteValues() { + long[] times = {0, 1, 2}; + double[] values = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; + + // three eligible points with N => 3: every point must be returned, not discarded + assertArrayEquals( + new int[] {0, 1, 2}, LTTBTableFunction.selectTargetCount(times, values, 3, 3)); + } + + /** + * With {@code N < M} the algorithm computes triangle areas, so a non-finite participant reaches + * the area comparison. NaN and the infinities cannot form a finite area and {@link + * java.math.BigDecimal} cannot represent them, so such candidates must be skipped (earliest wins) + * instead of aborting the query with an unchecked {@code NumberFormatException}. + */ + @Test + public void testTargetCountSkipsNonFiniteCandidatesWhenSampling() { + long[] times = {0, 1, 2, 3, 4, 5}; + double[] values = {1.0, Double.NaN, Double.POSITIVE_INFINITY, 2.0, 3.0, 4.0}; + + // The only interior bucket is t1..t4 with C = the final point; t3 (area 4) beats t4 (area 2) + // and the non-finite candidates can never win. + assertArrayEquals( + new int[] {0, 3, 5}, LTTBTableFunction.selectTargetCount(times, values, 6, 3)); + } + + /** A bucket whose candidates are all non-finite keeps its earliest point, deterministically. */ + @Test + public void testTargetCountKeepsEarliestPointWhenAllCandidatesAreNonFinite() { + long[] times = {0, 1, 2, 3, 4, 5}; + double[] values = { + Double.NaN, + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NaN, + Double.NEGATIVE_INFINITY, + Double.NaN + }; + + assertArrayEquals( + new int[] {0, 1, 5}, LTTBTableFunction.selectTargetCount(times, values, 6, 3)); + } + + /** + * {@code C} must never be a non-finite point, because every area of the bucket would then be + * undefined and the bucket would fall back to its earliest point. A non-finite final point + * therefore hands {@code C} to the last finite point of the partition instead. + */ + @Test + public void testTargetCountNonFiniteFinalPointDoesNotBecomeLookahead() { + long[] times = {0, 1, 2, 3, 4, 5}; + assertArrayEquals( + new int[] {0, 2, 5}, + LTTBTableFunction.selectTargetCount(times, new double[] {0, 1, 9, 2, 0, Double.NaN}, 6, 3)); + assertArrayEquals( + new int[] {0, 2, 5}, + LTTBTableFunction.selectTargetCount( + times, new double[] {0, 1, 9, 2, 0, Double.POSITIVE_INFINITY}, 6, 3)); + assertArrayEquals( + new int[] {0, 2, 5}, + LTTBTableFunction.selectTargetCount( + times, new double[] {0, 1, 9, 2, Double.NaN, Double.NaN}, 6, 3)); + // The last bucket looks ahead to the last finite point t5 = 3, so t4 = 9 wins over t3 = 2. + assertArrayEquals( + new int[] {0, 1, 4, 6}, + LTTBTableFunction.selectTargetCount( + new long[] {0, 1, 2, 3, 4, 5, 6}, new double[] {0, 5, 1, 2, 9, 3, Double.NaN}, 7, 4)); + // Control: a finite final point is C of the last bucket and selects the same peak. + assertArrayEquals( + new int[] {0, 2, 5}, + LTTBTableFunction.selectTargetCount(times, new double[] {0, 1, 9, 2, 0, 0}, 6, 3)); + } + + /** + * A next bucket without a finite point is skipped: {@code C} averages the finite points of the + * next bucket that has one instead of collapsing to the last finite point of the partition. + */ + @Test + public void testTargetCountSkipsNonFiniteLookaheadBuckets() { + long[] times = {0, 1, 2, 3, 4, 5, 6, 7}; + double[] values = {0, 5, 4, Double.NaN, Double.NaN, 10, 10, -20}; + + // N => 5: C of the first bucket is (t5 + t6) / 2 = (5.5, 10), so t1 (area 17.5) beats t2 + // (area 2). C of the last bucket is the last finite point t6. + assertArrayEquals( + new int[] {0, 1, 3, 6, 7}, + LTTBTableFunction.selectTargetCount(times, values, times.length, 5)); + // N => 4: buckets [1,4) and [4,7); the first one skips its NaN point and picks t1, and the + // second one scores t5 and t6 against the final point t7. + assertArrayEquals( + new int[] {0, 1, 6, 7}, + LTTBTableFunction.selectTargetCount(times, values, times.length, 4)); + } + + @Test + public void testTimestampUniquenessAcceptsDistinctAndRejectsRepeatedTimestamps() { + LTTBTableFunction.TimestampUniquenessChecker checker = + new LTTBTableFunction.TimestampUniquenessChecker(); + checker.check(1L); + checker.check(2L); + checker.check(3L); + try { + checker.check(3L); + fail(); + } catch (SemanticException e) { + assertEquals( + String.format( + CommonMessages + .EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD, + 3L), + e.getMessage()); + } + } + + private static Map targetCountArguments(long n) { + Map arguments = new HashMap<>(); + arguments.put( + LTTBTableFunction.DATA_PARAMETER_NAME, + new TableArgument( + Arrays.asList(Optional.of("time"), Optional.of("device"), Optional.of("s1")), + Arrays.asList(Type.TIMESTAMP, Type.STRING, Type.DOUBLE), + Collections.singletonList("device"), + Collections.singletonList("time"), + false)); + arguments.put( + LTTBTableFunction.TIMECOL_PARAMETER_NAME, new ScalarArgument(Type.STRING, "time")); + arguments.put(LTTBTableFunction.N_PARAMETER_NAME, new ScalarArgument(Type.INT64, n)); + arguments.put( + LTTBTableFunction.SIZE_PARAMETER_NAME, + new ScalarArgument(Type.INT64, LTTBTableFunction.UNSPECIFIED_SIZE)); + arguments.put( + LTTBTableFunction.SLIDE_PARAMETER_NAME, + new ScalarArgument(Type.INT64, LTTBTableFunction.UNSPECIFIED_SLIDE)); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, + new ScalarArgument(Type.TIMESTAMP, LTTBTableFunction.UNSPECIFIED_ORIGIN)); + arguments.put( + LTTBTableFunction.WINDOW_MODE_PARAMETER_NAME, new ScalarArgument(Type.BOOLEAN, false)); + return arguments; + } + + private static Map windowArguments(long size, long slide, boolean timeWindow) { + Map arguments = new HashMap<>(); + arguments.put( + LTTBTableFunction.DATA_PARAMETER_NAME, + new TableArgument( + Arrays.asList(Optional.of("time"), Optional.of("device"), Optional.of("s1")), + Arrays.asList(Type.TIMESTAMP, Type.STRING, Type.DOUBLE), + Collections.singletonList("device"), + Collections.singletonList("time"), + false)); + arguments.put( + LTTBTableFunction.TIMECOL_PARAMETER_NAME, new ScalarArgument(Type.STRING, "time")); + arguments.put( + LTTBTableFunction.N_PARAMETER_NAME, + new ScalarArgument(Type.INT64, LTTBTableFunction.UNSPECIFIED_N)); + arguments.put(LTTBTableFunction.SIZE_PARAMETER_NAME, new ScalarArgument(Type.INT64, size)); + arguments.put(LTTBTableFunction.SLIDE_PARAMETER_NAME, new ScalarArgument(Type.INT64, slide)); + arguments.put( + LTTBTableFunction.ORIGIN_PARAMETER_NAME, + new ScalarArgument(Type.TIMESTAMP, LTTBTableFunction.UNSPECIFIED_ORIGIN)); + arguments.put( + LTTBTableFunction.WINDOW_MODE_PARAMETER_NAME, new ScalarArgument(Type.BOOLEAN, timeWindow)); + return arguments; + } +} diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBWindowMemoryTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBWindowMemoryTest.java new file mode 100644 index 0000000000000..cb573874f2d21 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/udf/builtin/relational/tvf/LTTBWindowMemoryTest.java @@ -0,0 +1,867 @@ +/* + * 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.commons.udf.builtin.relational.tvf; + +import org.apache.iotdb.commons.conf.CommonConfig; +import org.apache.iotdb.commons.conf.CommonDescriptor; +import org.apache.iotdb.commons.exception.SemanticException; +import org.apache.iotdb.commons.i18n.CommonMessages; +import org.apache.iotdb.commons.queryengine.plan.relational.function.BatchedTableFunctionDataProcessor; +import org.apache.iotdb.udf.api.relational.access.Record; +import org.apache.iotdb.udf.api.relational.table.MapTableFunctionHandle; +import org.apache.iotdb.udf.api.relational.table.processor.TableFunctionDataProcessor; +import org.apache.iotdb.udf.api.type.Type; + +import org.apache.tsfile.block.column.Column; +import org.apache.tsfile.block.column.ColumnBuilder; +import org.apache.tsfile.read.common.block.column.DoubleColumnBuilder; +import org.apache.tsfile.read.common.block.column.LongColumnBuilder; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +public class LTTBWindowMemoryTest { + + @Test + public void testCountWindowOverlapFailsBeforeExhaustingHeap() { + TableFunctionDataProcessor processor = processor(false, 1_000_000, 1, Type.DOUBLE); + try { + // Without the shared budget, 5000 rows retain over 280 MiB despite every individual + // window being far below MAX_BUFFERED_POINTS. This test also runs with a 128 MiB heap. + assertMemoryLimit( + () -> { + for (int i = 0; i < 5000; i++) { + // timestamps must be unique within the partition, so advance the input time + processor.process(record(i, 1.0), Collections.emptyList(), null); + } + }, + LTTBTableFunction.DEFAULT_MAX_BUFFER_BYTES); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testAllNullRowSkipsTimeWindowAllocation() { + TableFunctionDataProcessor processor = processor(true, 1_000_000, 1, Type.DOUBLE); + List builders = builders(true); + try { + processor.process(record(0, (Number) null), builders, null); + processor.finish(builders, null); + assertEquals(0, builders.get(0).getPositionCount()); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testAllNullRowsSkipCountWindowAllocation() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(8 * 1024); + TableFunctionDataProcessor processor = processor(false, 100_000, 1, Type.DOUBLE); + List builders = builders(false); + try { + for (int t = 0; t < 64; t++) { + processor.process(record(t, (Number) null), builders, null); + } + processor.finish(builders, null); + assertEquals(0, builders.get(0).getPositionCount()); + } finally { + processor.beforeDestroy(); + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + @Test + public void testCountWindowsAfterNullRowsKeepTheirOriginalIndexes() { + TableFunctionDataProcessor processor = processor(false, 5, 2, Type.DOUBLE); + List builders = builders(false); + try { + for (int t = 0; t <= 15; t++) { + Double value = t == 7 || t == 14 ? (double) t : null; + processor.process(record(t, value), builders, null); + } + processor.finish(builders, null); + Column indexes = builders.get(0).build(); + Column times = builders.get(1).build(); + assertEquals(2, indexes.getPositionCount()); + // F at position 7 belongs first to [4, 9), L at 14 belongs last to [14, 19). + assertEquals(2, indexes.getLong(0)); + assertEquals(7, times.getLong(0)); + assertEquals(7, indexes.getLong(1)); + assertEquals(14, times.getLong(1)); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testNullRowsPreserveTimeWindowAlignmentAndTimestampChecks() { + TableFunctionDataProcessor processor = processor(true, 4, 2, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(true)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + processor.process(record(0, null, null), builders, null); + processor.process(record(2, null, 5.0), builders, null); + processor.process(record(9, null, null), builders, null); + processor.process(record(10, null, 7.0), builders, null); + processor.finish(builders, null); + assertEquals(2, builders.get(0).getPositionCount()); + assertEquals(0, builders.get(0).build().getLong(0)); + assertEquals(10, builders.get(0).build().getLong(1)); + assertEquals(2, builders.get(4).build().getLong(0)); + assertEquals(10, builders.get(4).build().getLong(1)); + } finally { + processor.beforeDestroy(); + } + + TableFunctionDataProcessor duplicates = processor(true, 4, 2, Type.DOUBLE); + try { + duplicates.process(record(0, (Number) null), builders, null); + SemanticException error = + assertThrows( + SemanticException.class, () -> duplicates.process(record(0, 1.0), builders, null)); + assertEquals( + String.format( + CommonMessages + .EXCEPTION_LTTB_DOES_NOT_SUPPORT_DUPLICATE_TIMESTAMPS_BUT_TIMESTAMP_ARG_APPEARS_MORE_THAN_ONCE_IN_THE_SAME_PARTITION_7713FEDD, + 0), + error.getMessage()); + } finally { + duplicates.beforeDestroy(); + } + } + + @Test + public void testFirstPointOnlyNeedsItsEarliestTimeWindow() { + TableFunctionDataProcessor processor = processor(true, 3_600_000, 10, Type.DOUBLE); + List builders = builders(true); + try { + processor.process(record(0, 42.0), builders, null); + processor.finish(builders, null); + assertEquals(1, builders.get(0).getPositionCount()); + assertEquals(-3_599_990, builders.get(0).build().getLong(0)); + assertEquals(10, builders.get(1).build().getLong(0)); + assertEquals(0, builders.get(2).build().getLong(0)); + assertEquals(42.0, builders.get(3).build().getDouble(0), 0.0); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testFirstPointAfterNullPrefixOnlyNeedsItsEarliestCountWindow() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(4 * 1024); + TableFunctionDataProcessor processor = processor(false, 128, 1, Type.DOUBLE); + List builders = builders(false); + try { + for (int t = 0; t < 128; t++) { + processor.process(record(t, (Number) null), builders, null); + } + processor.process(record(128, 42.0), builders, null); + processor.finish(builders, null); + assertEquals(1, builders.get(0).getPositionCount()); + assertEquals(1, builders.get(0).build().getLong(0)); + assertEquals(128, builders.get(1).build().getLong(0)); + assertEquals(42.0, builders.get(2).build().getDouble(0), 0.0); + } finally { + processor.beforeDestroy(); + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + @Test + public void testLaterCandidatesOpenDeferredWindowsForAllColumns() { + TableFunctionDataProcessor processor = processor(true, 4, 2, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(true)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + processor.process(record(0, 0.0, null), builders, null); + processor.process(record(2, 8.0, 5.0), builders, null); + processor.process(record(3, 1.0, 7.0), builders, null); + processor.process(record(4, 0.0, null), builders, null); + processor.finish(builders, null); + assertEquals(4, builders.get(0).getPositionCount()); + long[] firstColumnTimes = {0, 2, 3, 4}; + Column starts = builders.get(0).build(); + Column first = builders.get(2).build(); + Column second = builders.get(4).build(); + for (int row = 0; row < firstColumnTimes.length; row++) { + assertEquals(2L * row - 2, starts.getLong(row)); + assertEquals(firstColumnTimes[row], first.getLong(row)); + } + assertTrue(second.isNull(0)); + assertEquals(2, second.getLong(1)); + assertEquals(3, second.getLong(2)); + assertTrue(second.isNull(3)); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testTimeWindowCreationIsBoundedForBucketCandidates() { + TableFunctionDataProcessor processor = processor(true, 1_000_000, 1, Type.DOUBLE); + List builders = builders(true); + try { + processor.process(record(0, 1.0), builders, null); + assertMemoryLimit( + () -> processor.process(record(1, 2.0), builders, null), + LTTBTableFunction.DEFAULT_MAX_BUFFER_BYTES); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testColumnsShareTheWindowBudget() { + TableFunctionDataProcessor processor = processor(false, 1_000_000, 1, Type.DOUBLE, Type.INT64); + try { + assertMemoryLimit( + () -> { + for (int i = 0; i < 1800; i++) { + // timestamps must be unique within the partition, so advance the input time + processor.process(record(i, 1.0, Long.MAX_VALUE), Collections.emptyList(), null); + } + }, + LTTBTableFunction.DEFAULT_MAX_BUFFER_BYTES); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testArrayGrowthReservesOldAndNewIntegralArrays() { + LTTBTableFunction.PointBuffer buffer = + new LTTBTableFunction.PointBuffer(true, new LTTBTableFunction.BufferMemoryBudget(4096)); + for (int i = 0; i < 64; i++) { + buffer.addIntegral(i, Long.MAX_VALUE); + } + // The retained 128-point buffer fits in 4096 bytes, but the old 64-point arrays and + // replacement arrays coexist during growth. Reject before replacing any array. + assertMemoryLimit(() -> buffer.addIntegral(64, Long.MAX_VALUE), 4096); + assertEquals(64, buffer.size()); + assertEquals(63, buffer.time(63)); + } + + @Test + public void testInitialBuffersShareCapacityBudget() { + LTTBTableFunction.BufferMemoryBudget budget = new LTTBTableFunction.BufferMemoryBudget(4096); + LTTBTableFunction.PointBuffer first = new LTTBTableFunction.PointBuffer(true, budget); + LTTBTableFunction.PointBuffer second = new LTTBTableFunction.PointBuffer(true, budget); + LTTBTableFunction.PointBuffer third = new LTTBTableFunction.PointBuffer(true, budget); + first.addIntegral(0, 1); + second.addIntegral(0, 1); + assertMemoryLimit(() -> third.addIntegral(0, 1), 4096); + assertEquals(0, third.size()); + } + + @Test + public void testEmittedWindowsReleaseBudgetForLongStream() { + TableFunctionDataProcessor processor = processor(false, 1, 1, Type.DOUBLE); + List builders = builders(false); + long outputRows = 0; + try { + // Total allocations exceed the budget, but only two windows remain live at a time. + for (int row = 0; row < 80_000; row++) { + // timestamps must be unique within the partition, so advance the input time + processor.process(record(row, 42.0), builders, null); + if (row % 512 == 511) { + outputRows += builders.get(0).getPositionCount(); + builders = builders(false); + } + } + processor.finish(builders, null); + outputRows += builders.get(0).getPositionCount(); + assertEquals(80_000, outputRows); + assertEquals(42.0, builders.get(2).build().getDouble(0), 0.0); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testColumnWithASingleEligiblePointDoesNotStallEmission() { + // Only the first row has a value, so hasLastEligible stays false and lastEligiblePositions + // keeps its default 0. Admission must not treat that sentinel as a real last position: the + // window holding it would then never become ready and the whole partition would be buffered. + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 1, 1, Type.DOUBLE); + List builders = builders(timeWindow); + long emittedBeforeFinish = 0; + try { + for (int row = 0; row < 80_000; row++) { + processor.process(record(row, row == 0 ? 42.0 : null), builders, null); + if (row % 512 == 511) { + emittedBeforeFinish += builders.get(0).getPositionCount(); + builders = builders(timeWindow); + } + } + // Windows must stream out while the partition is still being read. + assertTrue(emittedBeforeFinish > 0); + processor.finish(builders, null); + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testWindowsAfterTheLastValueDoNotStallEmission() { + // Two eligible points followed by a long NULL tail. The empty windows must release their + // buffers as they close so a sparse partition can span more windows than fit in the budget. + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 1, 1, Type.DOUBLE); + List builders = builders(timeWindow); + try { + for (int row = 0; row < 80_000; row++) { + Double value = null; + if (row == 0) { + value = 1.0; + } else if (row == 1) { + value = 5.0; + } + processor.process(record(row, value), builders, null); + } + processor.finish(builders, null); + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + ColumnBuilder valuesBuilder = builders.get(timeWindow ? 3 : 2); + // Window 0 reports F(t0), window 1 reports L(t1); the NULL tail emits nothing. + assertEquals(2, times.getPositionCount()); + assertEquals(0, times.build().getLong(0)); + assertEquals(1, times.build().getLong(1)); + assertEquals(1.0, valuesBuilder.build().getDouble(0), 0.0); + assertEquals(5.0, valuesBuilder.build().getDouble(1), 0.0); + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testDisjointSingletonsStreamAcrossNullAndNonFiniteTails() { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 1, 1, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(timeWindow)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + for (int time = 0; time < 16; time++) { + processor.process( + record(time, time < 2 ? (double) time : Double.NaN, time < 2 ? (double) time : null), + builders, + null); + // All earlier windows closed, even though neither column has a later finite point. + assertEquals(time, builders.get(0).getPositionCount()); + } + processor.finish(builders, null); + assertEquals(16, builders.get(0).getPositionCount()); + int firstTime = timeWindow ? 2 : 1; + for (int time = 0; time < 16; time++) { + assertEquals(time, builders.get(firstTime).build().getLong(time)); + assertEquals( + time < 2 ? (double) time : Double.NaN, + builders.get(firstTime + 1).build().getDouble(time), + 0.0); + if (time < 2) { + assertEquals(time, builders.get(firstTime + 2).build().getLong(time)); + assertEquals(time, builders.get(firstTime + 3).build().getDouble(time), 0.0); + } else { + assertTrue(builders.get(firstTime + 2).build().isNull(time)); + assertTrue(builders.get(firstTime + 3).build().isNull(time)); + } + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testDisjointFiniteSingletonUpdatesAnchor() { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 2, 2, Type.DOUBLE); + List builders = builders(timeWindow); + try { + Double[] values = {0.0, 10.0, Double.NaN, null, 0.0, 3.0, 0.0}; + for (int time = 0; time < values.length; time++) { + processor.process(record(time, values[time]), builders, null); + } + processor.finish(builders, null); + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + // A is (1,10) after the singleton and the NaN, so (4,0) beats (5,3) against C=(6,0). + long[] expected = {0, 1, 2, 4, 6}; + assertEquals(expected.length, times.getPositionCount()); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], times.build().getLong(i)); + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testSingleFiniteCandidateStreamsAndUpdatesAnchor() { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 3, 3, Type.DOUBLE); + List builders = builders(timeWindow); + try { + Double[] values = { + 0.0, Double.NaN, 10.0, Double.NaN, Double.NaN, Double.NaN, 0.0, 3.0, null, 0.0 + }; + for (int time = 0; time < values.length; time++) { + processor.process(record(time, values[time]), builders, null); + if (time == 3) { + // F and the sole finite candidate are known before any finite lookahead arrives. + assertEquals(2, builders.get(0).getPositionCount()); + } + } + processor.finish(builders, null); + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + // With A=(2,10) and C=(9,0), t=6 beats t=7. The stale anchor (0,0) would pick t=7. + long[] expected = {0, 2, 3, 6, 9}; + assertEquals(expected.length, times.getPositionCount()); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], times.build().getLong(i)); + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testSparseSingletonLookaheadReleasesDenseWindows() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(32 * 1024); + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = + processor(timeWindow, 3, 3, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(timeWindow)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + Double[] sparse = {0.0, 0.0, 9.0, 0.0}; + for (int t = 0; t < 120; t++) { + processor.process( + record(t, t < sparse.length ? sparse[t] : null, (double) t), builders, null); + } + processor.finish(builders, null); + int firstTime = timeWindow ? 2 : 1; + Column sparseTimes = builders.get(firstTime).build(); + Column sparseValues = builders.get(firstTime + 1).build(); + Column denseTimes = builders.get(firstTime + 2).build(); + assertEquals(denseTimes.getPositionCount(), sparseTimes.getPositionCount()); + assertEquals(42, denseTimes.getPositionCount()); + int[] expectedSparse = {0, 2, 3}; + for (int i = 0; i < expectedSparse.length; i++) { + int t = expectedSparse[i]; + assertEquals(t, sparseTimes.getLong(i)); + assertEquals(sparse[t], sparseValues.getDouble(i), 0.0); + } + for (int i = expectedSparse.length; i < denseTimes.getPositionCount(); i++) { + assertTrue(sparseTimes.isNull(i)); + assertTrue(sparseValues.isNull(i)); + } + // All areas in the dense column tie. Each bucket keeps its earliest candidate. + assertEquals(0L, denseTimes.getLong(0)); + assertEquals(1L, denseTimes.getLong(1)); + for (int i = 2; i <= 40; i++) { + assertEquals(3L * (i - 1), denseTimes.getLong(i)); + } + assertEquals(119L, denseTimes.getLong(41)); + } finally { + processor.beforeDestroy(); + } + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + @Test + public void testExclusiveSingletonStreamsAcrossOverlappingWindows() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(32 * 1024); + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = + processor(timeWindow, 3, 2, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(timeWindow)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + for (int t = 0; t < 120; t++) { + processor.process(record(t, t < 2 ? (double) t : null, (double) t), builders, null); + } + // t=1 can only be reported by [0,3). The dense column keeps streaming. + assertTrue(builders.get(0).getPositionCount() > 0); + processor.finish(builders, null); + int firstTime = timeWindow ? 2 : 1; + Column sparseTimes = builders.get(firstTime).build(); + Column denseTimes = builders.get(firstTime + 2).build(); + assertEquals(62, denseTimes.getPositionCount()); + assertEquals(0, sparseTimes.getLong(0)); + assertEquals(1, sparseTimes.getLong(1)); + assertEquals(0, builders.get(0).build().getLong(1)); + for (int i = 2; i < sparseTimes.getPositionCount(); i++) { + assertTrue(sparseTimes.isNull(i)); + } + assertEquals(119, denseTimes.getLong(61)); + } finally { + processor.beforeDestroy(); + } + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + @Test + public void testSharedNonFiniteEndpointAllowsEarlierWindowToStream() { + CommonConfig config = CommonDescriptor.getInstance().getConfig(); + long previousBudget = config.getLttbBufferSize(); + try { + config.setLttbBufferSize(32 * 1024); + for (boolean timeWindow : new boolean[] {false, true}) { + for (boolean sparseColumnResumes : new boolean[] {false, true}) { + assertSharedNonFiniteEndpointStreams(timeWindow, sparseColumnResumes); + } + } + } finally { + config.setLttbBufferSize(previousBudget); + } + } + + private static void assertSharedNonFiniteEndpointStreams( + boolean timeWindow, boolean sparseColumnResumes) { + TableFunctionDataProcessor processor = processor(timeWindow, 3, 2, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(timeWindow)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + processor.process(record(0, 0.0, 0.0), builders, null); + processor.process(record(1, 1.0, 1.0), builders, null); + processor.process(record(2, Double.NaN, 2.0), builders, null); + for (int t = 3; t < 120; t++) { + processor.process(record(t, null, (double) t), builders, null); + } + // [0,3) picks t=1; [2,5) reports t=2 whether or not another sparse point arrives. + // Only the final dense windows may still be waiting for lookahead. + int timeIndex = timeWindow ? 2 : 1; + Column denseTimes = builders.get(timeIndex + 2).build(); + assertTrue(denseTimes.getPositionCount() > 0); + assertTrue(denseTimes.getLong(denseTimes.getPositionCount() - 1) >= 114); + if (sparseColumnResumes) { + processor.process(record(120, 120.0, 120.0), builders, null); + } + processor.finish(builders, null); + + Column times = builders.get(timeIndex).build(); + Column values = builders.get(timeIndex + 1).build(); + Column windows = builders.get(0).build(); + List sparseTimes = new ArrayList<>(); + for (int i = 0; i < times.getPositionCount(); i++) { + if (!times.isNull(i)) { + long time = times.getLong(i); + sparseTimes.add(time); + if (time == 2) { + assertEquals(timeWindow ? 2 : 1, windows.getLong(i)); + assertTrue(Double.isNaN(values.getDouble(i))); + } + } + } + assertEquals( + sparseColumnResumes ? Arrays.asList(0L, 1L, 2L, 120L) : Arrays.asList(0L, 1L, 2L), + sparseTimes); + } finally { + processor.beforeDestroy(); + } + } + + @Test + public void testSharedSingletonWaitsUntilItsEndpointStatusIsKnown() { + for (boolean timeWindow : new boolean[] {false, true}) { + for (boolean hasLaterPoint : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 3, 2, Type.DOUBLE); + List builders = builders(timeWindow); + try { + for (int t = 0; t < 6; t++) { + processor.process(record(t, t == 0 || t == 2 ? (double) t : null), builders, null); + } + if (hasLaterPoint) { + processor.process(record(6, 6.0), builders, null); + } + processor.finish(builders, null); + Column times = builders.get(timeWindow ? 2 : 1).build(); + Column windows = builders.get(0).build(); + assertEquals(hasLaterPoint ? 4 : 2, times.getPositionCount()); + assertEquals(0, times.getLong(0)); + assertEquals(2, times.getLong(1)); + if (hasLaterPoint) { + // Both [0,3) and [2,5) select t=2 as their only candidate. + assertEquals(0, windows.getLong(1)); + assertEquals(2, times.getLong(2)); + assertEquals(timeWindow ? 2 : 1, windows.getLong(2)); + assertEquals(6, times.getLong(3)); + } else { + // Only [2,5) owns the final endpoint. + assertEquals(timeWindow ? 2 : 1, windows.getLong(1)); + } + } finally { + processor.beforeDestroy(); + } + } + } + } + + @Test + public void testMultiPointLookaheadWaitsForTheFinalEndpoint() { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 3, 3, Type.DOUBLE); + List builders = builders(timeWindow); + try { + Double[] values = {0.0, 0.0, 5.0, 0.0, 20.0, null, null}; + for (int t = 0; t < values.length; t++) { + processor.process(record(t, values[t]), builders, null); + } + assertEquals(0, builders.get(0).getPositionCount()); + processor.finish(builders, null); + Column times = builders.get(timeWindow ? 2 : 1).build(); + // Using t3 alone as C selects t2. Averaging t3 and the final endpoint t4 selects t1. + long[] expected = {0, 2, 3, 4}; + assertEquals(expected.length, times.getPositionCount()); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i], times.getLong(i)); + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testSparseColumnsReleaseTheirFirstWindowWhenEmitted() throws Exception { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 1, 1, Type.DOUBLE, Type.DOUBLE); + List builders = new ArrayList<>(builders(timeWindow)); + builders.add(new LongColumnBuilder(null, 16)); + builders.add(new DoubleColumnBuilder(null, 16)); + try { + processor.process(record(0, 11.0, null), builders, null); + processor.process(record(1, null, 22.0), builders, null); + processor.process(record(2, null, null), builders, null); + assertEquals(2, builders.get(0).getPositionCount()); + Field field = processor.getClass().getSuperclass().getDeclaredField("firstEligibleWindows"); + field.setAccessible(true); + for (Object firstWindow : (Object[]) field.get(processor)) { + assertNull(firstWindow); + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testFiniteLookaheadBeyondNonFiniteBuckets() { + for (boolean timeWindow : new boolean[] {false, true}) { + BatchedTableFunctionDataProcessor processor = + (BatchedTableFunctionDataProcessor) processor(timeWindow, 3, 3, Type.DOUBLE); + List builders = builders(timeWindow); + try { + processor.process(record(0, 0.0), builders, null); + processor.process(record(1, 0.0), builders, null); + processor.process(record(2, 100.0), builders, null); + for (int i = 3; i < 900; i++) { + processor.process(record(i, Double.NaN), builders, null); + } + assertEquals(0, builders.get(0).getPositionCount()); + processor.process(record(900, 45_000.0), builders, null); + processor.process(record(901, (Number) null), builders, null); + processor.process(record(902, (Number) null), builders, null); + processor.processInput(record(903, 0.0), builders, null); + assertEquals(0, builders.get(0).getPositionCount()); + boolean drained = false; + while (!drained) { + int previousRows = builders.get(0).getPositionCount(); + drained = processor.drainOutput(builders, () -> true); + int added = builders.get(0).getPositionCount() - previousRows; + // A final call may only consume the pending input after the last output block filled. + assertTrue(added == 1 || (drained && added == 0)); + } + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + // C lies on the line through t=0 and t=2, so t=1 wins once its lookahead closes. + assertEquals(302, times.getPositionCount()); + assertEquals(1, times.build().getLong(1)); + assertEquals(897, times.build().getLong(300)); + processor.finish(builders, null); + assertEquals(303, times.getPositionCount()); + assertEquals(900, times.build().getLong(301)); + assertEquals(903, times.build().getLong(302)); + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testFinishSplitsThreeRowsOfOneWindow() { + for (boolean timeWindow : new boolean[] {false, true}) { + BatchedTableFunctionDataProcessor processor = + (BatchedTableFunctionDataProcessor) processor(timeWindow, 3, 3, Type.DOUBLE); + List builders = builders(timeWindow); + try { + for (int time = 0; time < 3; time++) { + processor.process(record(time, 5.0), builders, null); + } + for (int time = 0; time < 3; time++) { + assertEquals(time == 2, processor.finishBatch(builders, () -> true)); + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + assertEquals(1, times.getPositionCount()); + assertEquals(time, times.build().getLong(0)); + builders = builders(timeWindow); + } + } finally { + processor.beforeDestroy(); + } + } + } + + @Test + public void testWindowResultsArePreserved() { + for (boolean timeWindow : new boolean[] {false, true}) { + TableFunctionDataProcessor processor = processor(timeWindow, 2, 2, Type.DOUBLE); + List builders = builders(timeWindow); + double[] values = {0, 1, 8, 2, 0, 0}; + try { + for (int time = 0; time < values.length; time++) { + processor.process(record(time, values[time]), builders, null); + } + processor.finish(builders, null); + ColumnBuilder times = builders.get(timeWindow ? 2 : 1); + ColumnBuilder valuesBuilder = builders.get(timeWindow ? 3 : 2); + // W0 reports F(t0) and its pick(t1); W1 reports its pick(t2); W2 reports its pick(t4) and + // L(t5). + assertEquals(5, times.getPositionCount()); + assertEquals(0, times.build().getLong(0)); + assertEquals(1, times.build().getLong(1)); + assertEquals(2, times.build().getLong(2)); + assertEquals(4, times.build().getLong(3)); + assertEquals(5, times.build().getLong(4)); + assertEquals(0.0, valuesBuilder.build().getDouble(0), 0.0); + assertEquals(1.0, valuesBuilder.build().getDouble(1), 0.0); + assertEquals(8.0, valuesBuilder.build().getDouble(2), 0.0); + assertEquals(0.0, valuesBuilder.build().getDouble(3), 0.0); + assertEquals(0.0, valuesBuilder.build().getDouble(4), 0.0); + } finally { + processor.beforeDestroy(); + } + } + } + + private static TableFunctionDataProcessor processor( + boolean timeWindow, long size, long slide, Type... types) { + MapTableFunctionHandle handle = + new MapTableFunctionHandle.Builder() + .addProperty( + LTTBTableFunction.MODE_PROPERTY, timeWindow ? "TIME_WINDOW" : "COUNT_WINDOW") + .addProperty(LTTBTableFunction.PARTITION_TYPES_PROPERTY, "") + .addProperty( + LTTBTableFunction.PARTICIPANT_TYPES_PROPERTY, + WindowTVFUtils.joinTypes(Arrays.asList(types))) + .addProperty(LTTBTableFunction.SIZE_PARAMETER_NAME, size) + .addProperty(LTTBTableFunction.SLIDE_PARAMETER_NAME, slide) + .addProperty(LTTBTableFunction.ORIGIN_PARAMETER_NAME, 0L) + .build(); + return new LTTBTableFunction().getProcessorProvider(handle).getDataProcessor(); + } + + private static List builders(boolean timeWindow) { + if (timeWindow) { + return Arrays.asList( + new LongColumnBuilder(null, 16), + new LongColumnBuilder(null, 16), + new LongColumnBuilder(null, 16), + new DoubleColumnBuilder(null, 16)); + } + return Arrays.asList( + new LongColumnBuilder(null, 16), + new LongColumnBuilder(null, 16), + new DoubleColumnBuilder(null, 16)); + } + + private static Record record(long time, Number... values) { + // Avoid retaining invocation histories in the long-stream memory regression test. + Record record = mock(Record.class, withSettings().stubOnly()); + when(record.getLong(0)).thenReturn(time); + for (int i = 0; i < values.length; i++) { + when(record.isNull(i + 1)).thenReturn(values[i] == null); + if (values[i] instanceof Long) { + when(record.getLong(i + 1)).thenReturn(values[i].longValue()); + } else if (values[i] != null) { + when(record.getDouble(i + 1)).thenReturn(values[i].doubleValue()); + } + } + return record; + } + + private static void assertMemoryLimit(Runnable action, long limit) { + try { + action.run(); + fail("Expected the shared LTTB window memory limit"); + } catch (SemanticException e) { + assertEquals( + String.format( + CommonMessages + .EXCEPTION_LTTB_BUFFERS_EXCEED_LTTB_BUFFER_SIZE_IN_BYTES_ARG_BYTES_26BDE62D, + limit), + e.getMessage()); + } + } +}